diff --git a/app/artifacts/patient_appointment_density/appointments_1024x640.png b/app/artifacts/patient_appointment_density/appointments_1024x640.png index 83cfc4cee..64ef0aa17 100644 Binary files a/app/artifacts/patient_appointment_density/appointments_1024x640.png and b/app/artifacts/patient_appointment_density/appointments_1024x640.png differ diff --git a/app/artifacts/patient_appointment_density/appointments_1366x768.png b/app/artifacts/patient_appointment_density/appointments_1366x768.png index f927c4fa3..1a435e4c8 100644 Binary files a/app/artifacts/patient_appointment_density/appointments_1366x768.png and b/app/artifacts/patient_appointment_density/appointments_1366x768.png differ diff --git a/app/artifacts/patient_appointment_density/patients_1024x640.png b/app/artifacts/patient_appointment_density/patients_1024x640.png index bec10d926..a2e433bdb 100644 Binary files a/app/artifacts/patient_appointment_density/patients_1024x640.png and b/app/artifacts/patient_appointment_density/patients_1024x640.png differ diff --git a/app/artifacts/patient_appointment_density/patients_1366x768.png b/app/artifacts/patient_appointment_density/patients_1366x768.png index 9a8e0100d..d74ac6456 100644 Binary files a/app/artifacts/patient_appointment_density/patients_1366x768.png and b/app/artifacts/patient_appointment_density/patients_1366x768.png differ diff --git a/app/artifacts/prescription_list_density/prescriptions_1366x768.png b/app/artifacts/prescription_list_density/prescriptions_1366x768.png index 76ab87598..ff03f3f63 100644 Binary files a/app/artifacts/prescription_list_density/prescriptions_1366x768.png and b/app/artifacts/prescription_list_density/prescriptions_1366x768.png differ diff --git a/app/artifacts/reception_ai_exact/reception.png b/app/artifacts/reception_ai_exact/reception.png index dbd6c3b85..b1b47b8b9 100644 Binary files a/app/artifacts/reception_ai_exact/reception.png and b/app/artifacts/reception_ai_exact/reception.png differ diff --git a/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png b/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png index a16214673..1dc7109a1 100644 Binary files a/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png and b/app/artifacts/subwindow_exact/prescription_ai_report_920x760.png differ diff --git a/app/artifacts/subwindow_exact/prescription_detail_920x780.png b/app/artifacts/subwindow_exact/prescription_detail_920x780.png index c0143bd85..029dd3ca9 100644 Binary files a/app/artifacts/subwindow_exact/prescription_detail_920x780.png and b/app/artifacts/subwindow_exact/prescription_detail_920x780.png differ diff --git a/app/artifacts/subwindow_exact/prescription_editor_860x900.png b/app/artifacts/subwindow_exact/prescription_editor_860x900.png index faac679bd..750cac325 100644 Binary files a/app/artifacts/subwindow_exact/prescription_editor_860x900.png and b/app/artifacts/subwindow_exact/prescription_editor_860x900.png differ diff --git a/app/research/client-ui-design.md b/app/research/client-ui-design.md new file mode 100644 index 000000000..0a780bbb3 --- /dev/null +++ b/app/research/client-ui-design.md @@ -0,0 +1,72 @@ +# 医生工作站客户端设计规范 + +本轮覆盖现有 PySide6 客户端与 Vue 视频伴随窗口。按 `redesign-existing-projects` 审查现有页面,结合 `minimalist-ui` 的扁平化原则实施;医疗工作台保留信息密度,不套用营销页面的大留白、装饰动效或布局模板。 + +## 审查结论 + +- 主框架与业务页面原先并存科技蓝、紫蓝及多套中性色;登录、AI、诊单的控件也各自定义配色。 +- 页面内圆角、边框和层级不统一,部分阴影、悬浮位移和过渡使操作显得跳动。 +- 小窗口的表格、诊单与视频操作需要分别验证,不能依靠整体缩小解决。 +- 键盘焦点、禁用与选择状态应始终可识别,不通过改变控件几何位置表达状态。 + +## 视觉系统 + +设计变量以 `src/doctor_workstation/ui/design_system.py` 为准。旧页面通过 `clinical_stylesheet` 迁移已知的浅色主题颜色,新样式使用命名变量。医学数据曲线、模型标识色和深色主题不进行全局替色。 + +| 角色 | 值 | 使用场景 | +| --- | --- | --- | +| 主色 | `#4267B2` | 主操作、选中项、重要链接 | +| 主色浅底 | `#EAF0FB` | 选中背景、轻量状态 | +| 画布 | `#F5F7FA` | 主窗口背景 | +| 表面 | `#FFFFFF` | 内容区、对话框 | +| 次级表面 | `#F7F9FC` | 筛选栏、分组、只读区域 | +| 侧栏 | `#F0F3F8` | 导航区域 | +| 标题 / 正文 | `#223047` / `#344258` | 文字层级 | +| 次级文字 | `#647287` | 说明、辅助信息 | +| 边框 / 强边框 | `#E6EAF0` / `#D4DCE8` | 低对比结构线、输入边界 | +| 成功 / 警示 / 危险 | `#287B65` / `#96601D` / `#B54A59` | 保留明确语义,不只依赖颜色 | + +- 圆角:标签 6 px、输入与按钮 10 px、内容面板 16 px、独立窗口 20 px。 +- 间距:8 / 12 / 16 / 24 px,根据现有表格密度调整,不整体放大行高。 +- 字体:继续使用打包的中文字体与现有可读字号;标题层级通过字重、字号和间距体现。 +- 表面:纯色为主,轻边框划分区域,减少嵌套卡片与装饰阴影。 +- 按钮:每个操作组主次清晰;次要操作使用浅底或边框;终止、删除等危险操作保留语义色。 + +## 交互规范 + +- 悬浮、按下和焦点反馈不移动布局、不改变控件尺寸。 +- 动画短而克制;滚动可被键盘、拖动、程序定位与反向滚动即时打断;尊重减少动画设置。 +- 切换页面保留原有路由、权限和数据加载机制。 +- 登录表单保留密码存储、服务器设置与提交保护;组合密码框使用实际 Qt 焦点状态。 +- 大小窗口都必须能找到主要操作,优先局部滚动而非把全部内容压小。 +- 视频保留原有截图捕获、确认上传、大预览和小窗关闭返回大窗逻辑;视觉样式不改变媒体内容或尺寸计算。 + +## 覆盖范围 + +1. 登录与品牌区:扁平品牌面板、简洁功能说明、清晰表单与焦点。 +2. 主框架:导航、顶部搜索、工具按钮、标签与 AI 入口。 +3. 列表:挂号、接诊记录、患者、处方库、已开处方、业务订单及患者进度。 +4. 诊疗:接诊台、预约抽屉、诊单编辑与只读、指标和保存状态。 +5. 辅助窗口:AI 问诊、处方编辑、处方解读与报告控制台。 +6. 视频:通话控制、聊天、录制提示与截图确认。 + +## 验收方式 + +`scripts/render_client_design.py` 使用演示仓库生成 1440 × 900、1024 × 640 的真实页面,以及 1280 × 800、860 × 640 的登录页;输出 `artifacts/client-design/index.html` 与原尺寸 PNG。诊疗和 AI 弹窗使用现有专用渲染脚本验证。 + +检查重点:小窗操作可达、中文可读、表格信息密度、长文本换行、键盘焦点、布局稳定、登录与页面路由契约、视频截图与窗口状态回归。生产服务与真实患者资料不用于视觉验收。 + +本轮共享组件还覆盖筛选展开按钮、列表加载状态、聊天通知、更新提示、本机录音队列、媒体预览和上传进度。860 × 640 登录表单完整显示,不需要为纯留白滚动。 + +## 验证记录与边界 + +- 主框架、登录、遮罩与动效首轮 100 项通过;新增组合密码框键盘焦点检查通过。 +- 小窗登录与焦点补测 2 项、最终登录及主框架复查 68 项通过。 +- 筛选、无限列表、通知、更新窗口与本机录音队列 37 项通过。 +- 原生视频截图、截图预览尺寸、小窗关闭与视频契约 199 项通过。 +- 视频前端 26 项检查通过,生产 dist 已重新构建。 +- 当前视频 dist 在 1120 × 760、540 × 356、440 × 300 的合成画面中完成 27 项布局检查,截图与关闭事件正常,未访问外部服务。 +- 临床页面、AI、处方及图表分别完成专项测试和真实控件渲染,详细记录位于 `artifacts/client-design/*-report.md`。 +- 最终修改文件的 Ruff 与 `git diff --check` 均通过;AI 工作区及快捷操作权限最后复查 24 项通过。 + +此记录不表示整仓所有历史测试全部通过。扩展测试中存在已用原始 HEAD 复现的 AI 流式/延迟生命周期失败、共享 QApplication 样式引发的图表测试顺序依赖,以及 Windows Qt 网络模块异常;本轮没有改变相关业务行为。未连接真实面诊服务,也未重新打包或安装 Windows 客户端。 diff --git a/app/research/im-ai-assistance.md b/app/research/im-ai-assistance.md new file mode 100644 index 000000000..19774606a --- /dev/null +++ b/app/research/im-ai-assistance.md @@ -0,0 +1,75 @@ +# IM 问诊 AI 辅助 + +用户确认范围:在现有 IM 问诊窗口内增加「总结病情」「建议追问」「起草回复」。结果供医生审阅,医生主动填入输入框后编辑并手动发送。 + +## 集成契约 + +- 复用 `stream_diagnosis_ai`:总结使用 `summary`,追问和回复使用 `custom`。不新增模型配置、不把凭据传到浏览器、不新增服务端路由。 +- 每次生成前,通过 `sync_im_chat_messages(scope="current", sync_token=...)` 完成当前账号对话归档;响应 `completed=true` 且没有错误后才能调用 AI。准备失败明确报错,不静默降级为旧聊天。服务器按授权诊单聚合临床资料与归档 IM,提示词限定本次医生账号的近期对话。 +- 三项提示词保持 500 字以内;不在提示词中挤入、截断完整聊天或未发送草稿。 +- AI 独立后台 worker,不占用通话、录音和消息发送的队列。 + +原生配置 `DoctorCallConfig.imAi`:`{version:1, enabled:boolean, sessionId:string, reason?:string}`。宿主生成 sessionId,每个新窗口独立。上层将 AI 权限布尔值贯穿 launcher;默认拒绝。 + +浏览器到原生: + +```json +{"source":"doctor-call","event":"im-ai-request","sessionId":"host-uuid","requestId":"uuid","contextKey":"frontend-context","diagnosisId":"501","appointmentId":101,"action":"summary"} +``` + +取消使用同一组身份字段及 `event="im-ai-cancel"`。只允许 `summary | followup | reply`。宿主核验可信文档、窗口未关闭、AI 权限、会话、诊单、挂号和请求格式;实际 repository 调用始终使用宿主绑定诊单。 + +原生通过 `window.doctorConsultation.imAiResult(payload)` 返回相同身份字段与: + +```text +status: loading | streaming | success | error | cancelled +text?: 累积正文(流式及最终) +message?: 简短进度或错误 +modelLabel?: 服务端模型标签 +warnings?: string[] +``` + +所有数据使用 JSON 序列化,桥接正文仍为原始文本。页面通过受限 Markdown 渲染器显示标题、重点、列表和表格;原始 HTML 被转义,链接和图片只保留文字,不执行内容或加载外部资源。客户端截止时间 180 秒,超时发送取消;原生聊天同步有独立有界预算,AI 沿用现有 105 秒传输预算。取消请求由独立线程发送,GUI 不等待网络。停止只是停止本次接收,不冒称上游工作已确认停止。 + +## 界面与状态 + +- 宽屏右侧约 330 px 辅助区;窄屏可收起抽屉,独立滚动,操作和关闭可达。沿用现有蓝色、圆角和轻边框。 +- AI loading 不阻塞 IM 输入、发送、加载更多和视频控制。 +- 只有完整成功结果允许填入;追问与回复可填入,病情总结默认只读。非空草稿明确追加,超过 3000 字拒绝追加而不截断原文。 +- 切换会话清空 AI 状态和草稿;迟到、重复、身份不匹配结果全部忽略。 +- 异步手动发送成功仅清空当时提交且没有继续修改的草稿。 +- 结果注明医生复核,展示服务端临床复核提示;不会自动发送、写病历或开处方。 + +## 验证要求 + +离线 fake repository 验证同步续拉、失败不生成、取消、终态、身份隔离、权限与关闭;Node 测试验证桥接状态/计时器、草稿追加和发送隔离;使用真实构建产物和合成消息验证宽屏与紧凑窗口。回归截图、录音收尾、通话权限与 IM 流程。验证不得访问真实患者、IM 或 AI 服务。 + +## 交付与验证结果(2026-10-29) + +- `app.py` 在实际打开窗口时读取当前账号的 `tcm.diagnosis/aiAssistant` 权限,经 launcher 传入原生窗口;未配置权限时默认关闭,不采用聊天载荷中的权限标记。 +- 三项功能已接入真实 Qt bridge 和现有流式服务;宽屏常驻侧栏,980 px 及以下窗口使用可收起抽屉。中文输入法选词时按 Enter 不发送,异步发送不会清除医生随后编辑的草稿。 +- 合并后 Python 回归 **364 项通过**:包括新增 AI 服务/仓库/窗口、权限入口、IM、视频契约、截图、小窗关闭及大预览等。运行使用独立 `artifacts/im-ai/final-integration-tmp`,未访问外部服务。 +- 前端 **45 项 Node 行为测试通过**,`vue-tsc` 与 Vite 构建通过;实际 dist 在 1120×760、980×640、540×356、440×300 下 **42 项界面检查通过**。离线夹具只使用合成消息和结果,外部请求尝试为 0。 +- Ruff 与 `git diff --check` 通过。首次交付构建入口:`index-CnqWQu6O.js`、`index-BwArpbVK.css`。 +- 截图、可复现夹具和详细报告存放在 `app/artifacts/im-ai/`。未验证真实账号的模型响应;未生成 Windows 安装包。源码运行需重启客户端,已安装版本需重新打包后安装。 + +停止接收后,原生端会独立请求取消;在旧请求实际退出前重试会提示稍后再试,避免重复模型请求。聊天同步失败时不使用旧归档静默生成,助手显示错误并允许重试。 + +## 结果排版与切换改进(2026-10-29) + +- 模型输出的 Markdown 标题、加粗、列表、引用、代码和简单表格转换为安全的结构化展示;重点以加粗和浅蓝底色标记,结构标题使用蓝色引导线。不依据医学关键词自行推断重点。未闭合的流式片段保持可读原文。 +- 三项操作在当前窗口会话内分别保留状态、正文、模型标签和复核提示。顶部按钮首次点击生成,之后只切换查看;底部“重新生成/重试”才会再发请求。生成中可以阅读其他已完成结果,后台更新不能覆盖当前阅读页。 +- 每项保留独立滚动位置,换患者、关闭或重开会话时清空。结果仅保存在内存中,不增加本地患者内容持久化。 +- 填入草稿前去除 Markdown 排版符号,保留原文、数值和列表含义,再执行 3000 字长度检查;仍不覆盖原稿、不自动发送。 +- 本次前端 **61 项行为测试通过**,包含安全渲染、草稿转换、缓存、显式重生成、后台流式隔离及现有截图/通话守卫;TypeScript 与 Vite 构建通过。 +- 真实 dist 配合生产 AI controller 源码和离线宿主替身,在四种窗口尺寸完成 **20 项可点击/布局检查**,以及切换不发请求、显式刷新、后台生成、独立阅读位置、原稿追加及注入防护断言。外部请求为 0。 +- 证据:`artifacts/im-ai/refinements-visual-checks.json`、`render_im_ai_refinements.py` 与 `im-ai-styled-cached-*.png`。未打包安装程序。 + +## 可调宽度、首次总结与指标强调(2026-10-29) + +- 聊天与助手之间增加可左右拖动的分隔线,宽屏保留至少 480 px 聊天区域;窄屏抽屉也可调整,最大宽度仍留出可操作的边缘。支持方向键、Home/End、Enter 或双击恢复默认,Escape 取消本次拖动。窗口变更、失焦与关闭释放指针捕获。宽屏和抽屉宽度分别记忆在当前窗口内。 +- 进入有权限的 IM 会话后,首次总结等待当前登录、聊天、Qt 通道及原生 `imAiReady(sessionId)` 确认;准备等待最多 30 秒。每个会话只自动尝试一次,不因重连、标签切换、展开面板或失败自动重试。医生提前手动操作会取消待启动的自动总结。关闭和换会话清理计时器及旧结果。 +- 普通文本中的血糖、血压、糖化血红蛋白、体重等指标名称及带单位的数值自动强调,支持范围、小数和血压组合。名称加深,数值加粗并显示浅蓝底色,不依赖模型输出 Markdown。原始数值、单位、否定和不确定表述保持不变;没有新增医学阈值判断或自动风险分级。 +- **97 项前端测试、318 项客户端回归通过**,TypeScript、Vite 和 Ruff 检查通过,`git diff --check` 无问题。当前构建:`index-C_tMrPfb.js`、`index-CMN1CXTr.css`。 +- 实际构建页面在 1634×1008、1120×760、980×640、540×356、440×300 下完成真实 Qt 鼠标拖动、键盘调整、取消、跨断点释放及指标样式检查,**15 项布局/点击检查通过**,自动选择与请求次数断言通过,外部请求为 0。 +- 证据:`artifacts/im-ai/render_im_ai_resizing.py`、`resizing-visual-checks.json`、`im-ai-metrics-resizable-*.png`。本轮未生成安装包;原生就绪握手需重启使用最新源码的客户端。 diff --git a/app/scripts/render_client_design.py b/app/scripts/render_client_design.py new file mode 100644 index 000000000..4414ce522 --- /dev/null +++ b/app/scripts/render_client_design.py @@ -0,0 +1,143 @@ +"""Render the real native client with synthetic data for UI design review.""" + +from __future__ import annotations + +import argparse +import html +import json +import os +from pathlib import Path + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +os.environ.setdefault("DOCTOR_MOTION", "off") + +from PySide6.QtCore import QSettings, QThreadPool +from PySide6.QtGui import QImage +from PySide6.QtTest import QTest +from PySide6.QtWidgets import QApplication + +from doctor_workstation.services import DemoDoctorRepository +from doctor_workstation.ui import ShellWindow, apply_theme +from doctor_workstation.ui.login import LoginWindow + +ROUTES = { + "appointments": "挂号列表", + "consultations": "问诊列表", + "patients": "我的患者", + "prescription_library": "我的处方库", + "prescriptions": "已开处方", + "reception": "接诊台", +} + + +def settle(app: QApplication) -> None: + for _ in range(4): + QThreadPool.globalInstance().waitForDone(3000) + app.processEvents() + QTest.qWait(75) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=Path("artifacts/client-design")) + args = parser.parse_args() + output = args.output.resolve() + output.mkdir(parents=True, exist_ok=True) + app = QApplication.instance() or QApplication([]) + apply_theme(app) + repo = DemoDoctorRepository() + records = [] + + def capture(window, name: str, title: str) -> None: + settle(app) + filename = f"{name}.png" + if not window.grab().save(str(output / filename)): + raise RuntimeError(f"Could not save {filename}") + records.append({ + "title": title, "file": filename, + "width": window.width(), "height": window.height(), + }) + + # Isolate preview settings from the user's saved account and credentials. + settings = QSettings(str(output / "preview-login.ini"), QSettings.Format.IniFormat) + settings.clear() + login = LoginWindow(repo, settings=settings) + login.show() + for width, height in ((1280, 800), (860, 640)): + login.resize(width, height) + capture(login, f"login-{width}", "登录工作站") + login.close() + + session = repo.login(repo.DEMO_ACCOUNT, repo.DEMO_PASSWORD) + shell = ShellWindow( + repo, {"session": session, "demo_mode": True}, permissions=session.permissions, + ) + shell.show() + try: + for width, height in ((1440, 900), (1024, 640)): + shell.resize(width, height) + for route, title in ROUTES.items(): + shell.navigate(route) + capture(shell, f"{route}-{width}", title) + finally: + settle(app) + shell.close() + + # Include independently rendered dialog/media fixtures when available. + supplementary = [ + ("patient_orders_1366x768.png", "患者业务订单"), + ("patient_progress_1366x768.png", "患者进度"), + ("clinical-after/appointment_drawer_1440x900.png", "预约编辑"), + ("clinical-after/diagnosis_edit_1440x900.png", "诊单编辑"), + ("clinical-after/diagnosis_edit_1024x640.png", "诊单编辑 · 紧凑窗口"), + ("clinical-after/diagnosis_index_1440x900.png", "诊单列表"), + ("assistant-1440.png", "AI 问诊"), + ("assistant-1080.png", "AI 问诊 · 紧凑窗口"), + ("../subwindow_exact/prescription_editor_860x900.png", "处方编辑"), + ("../subwindow_exact/prescription_ai_report_920x760.png", "处方报告"), + ("video-call-1120x760.png", "视频面诊"), + ("video-call-440x300.png", "视频面诊 · 小窗"), + ("video-chat-440x300.png", "视频聊天 · 小窗"), + ("video-preview-1120x760.png", "视频截图确认"), + ] + for filename, title in supplementary: + preview = QImage(str(output / filename)) + if not preview.isNull(): + records.append({ + "title": title, "file": filename, + "width": preview.width(), "height": preview.height(), + }) + + (output / "gallery.json").write_text( + json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8", + ) + cards = [] + for record in records: + filename = html.escape(record["file"]) + title = html.escape(record["title"]) + cards.append( + f'

{title} {record["width"]} × {record["height"]}' + f'

{title}' + '
' + ) + (output / "index.html").write_text( + '' + '' + '医生工作站 · 客户端设计验收

医生工作站 · 客户端设计验收

' + '

使用演示数据渲染的真实客户端。点击图片查看原始尺寸。

' + + "".join(cards) + + '
', + encoding="utf-8", + ) + print(output / "index.html") + + +if __name__ == "__main__": + main() diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index fdc81e084..af97365f5 100644 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -41,6 +41,7 @@ from doctor_workstation.ui.widgets import ( friendly_error, gender_text, get_value, + has_permission, run_async, set_authentication_expired_handler, show_toast, @@ -939,6 +940,11 @@ class ApplicationController(QObject): open_im=open_im, patient_name=patient_name, patient_case=patient_case, + can_ai_assistant=has_permission( + getattr(self.shell_window, "permissions", None), + "tcm.diagnosis/aiAssistant", + default=False, + ), on_open_diagnosis=lambda current_id=diagnosis_id, current_key=call_key: ( self._open_video_diagnosis(current_id, call_key=current_key) ), diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py index 023fd9a73..3c40de4ad 100644 --- a/app/src/doctor_workstation/services/mock_repository.py +++ b/app/src/doctor_workstation/services/mock_repository.py @@ -4,6 +4,7 @@ from __future__ import annotations import hashlib import json +import re import struct import zlib from collections.abc import Callable, Mapping, Sequence @@ -2846,11 +2847,22 @@ class DemoDoctorRepository: } ) - def sync_im_chat_messages(self, diagnosis_id: int) -> dict[str, Any]: - """Acknowledge the same asynchronous sync contract in demo mode.""" + def sync_im_chat_messages( + self, diagnosis_id: int, *, scope: str = "", sync_token: str = "" + ) -> dict[str, Any]: + """Complete synthetic archive sync while retaining the legacy receipt.""" self._find_consultation(diagnosis_id) - return {"queued": True, "diagnosis_id": diagnosis_id} + if scope not in {"", "current"}: + raise ValueError("IM sync scope must be empty or current") + if not isinstance(sync_token, str) or ( + sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None + ): + raise ValueError("IM sync token is invalid") + return { + "queued": True, "diagnosis_id": diagnosis_id, + "completed": True, "phase": "completed", "errors": [], + } def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]: """Build demo audit rows from the diagnosis appointments.""" diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index aa3e01765..ec10c3109 100644 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -692,8 +692,10 @@ class DoctorRepository(Protocol): ) -> dict[str, Any]: """Return diagnosis IM messages, defaulting to the fast archive-only path.""" - def sync_im_chat_messages(self, diagnosis_id: int) -> Any: - """Queue the server-side IM archive synchronisation job.""" + def sync_im_chat_messages( + self, diagnosis_id: int, *, scope: str = "", sync_token: str = "" + ) -> Any: + """Advance one server-side archive page; inspect completed before using it.""" def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]: """Return per-diagnosis registration / cancellation audit rows.""" @@ -2602,12 +2604,27 @@ class RemoteDoctorRepository: ) return dict(_require_mapping(payload, "tcm.diagnosis/getImChatMessages")) - def sync_im_chat_messages(self, diagnosis_id: int) -> Any: - """Queue the confirmed shutdown-function archive sync endpoint.""" + def sync_im_chat_messages( + self, diagnosis_id: int, *, scope: str = "", sync_token: str = "" + ) -> Any: + """Advance a bounded archive page, preserving legacy no-option callers.""" if diagnosis_id <= 0: raise ValueError("diagnosis_id must be positive") - return self.client.post("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": diagnosis_id}) + if scope not in {"", "current"}: + raise ValueError("IM sync scope must be empty or current") + if not isinstance(sync_token, str) or ( + sync_token and re.fullmatch(r"[a-f0-9]{48}", sync_token) is None + ): + raise ValueError("IM sync token is invalid") + payload: dict[str, Any] = {"diagnosis_id": diagnosis_id} + if scope: + payload["scope"] = scope + if sync_token: + payload["sync_token"] = sync_token + return _client_request( + self.client, "post", "tcm.diagnosis/triggerImChatSync", payload, timeout=15.0 + ) def list_diagnosis_appointment_logs(self, diagnosis_id: int) -> list[dict[str, Any]]: """Return registration/cancellation logs from ``guahaoLogList``.""" diff --git a/app/src/doctor_workstation/ui/appointment_drawer.py b/app/src/doctor_workstation/ui/appointment_drawer.py index 19bcadfe1..aba2a6b9b 100644 --- a/app/src/doctor_workstation/ui/appointment_drawer.py +++ b/app/src/doctor_workstation/ui/appointment_drawer.py @@ -23,7 +23,6 @@ from PySide6.QtWidgets import ( QComboBox, QDialog, QFrame, - QGraphicsDropShadowEffect, QGraphicsOpacityEffect, QHBoxLayout, QLabel, @@ -43,6 +42,7 @@ from PySide6.QtWidgets import ( ) from ..core.appointment_modes import APPOINTMENT_MODES +from .design_system import clinical_stylesheet from .theme import main_window_target_rect from .widgets import ( display_text, @@ -84,8 +84,8 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose { min-height: 32px; max-height: 32px; padding: 0; - border: 0; - border-radius: 4px; + border: 1px solid transparent; + border-radius: $ds_radius_control; background-color: transparent; color: #606163; font-size: 22px; @@ -95,6 +95,10 @@ QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose { QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:hover { color: #1A1C1F; background-color: #F0F0F0; +} +QDialog#AppointmentDrawerOverlay QToolButton#AppointmentDrawerClose:focus { + border-color: $ds_focus; + background-color: $ds_accent_soft; } QDialog#AppointmentDrawerOverlay QScrollArea#AppointmentDrawerBody, @@ -110,7 +114,7 @@ QDialog#AppointmentDrawerOverlay QWidget#AppointmentDrawerBodyContent { } QDialog#AppointmentDrawerOverlay QLabel[appointmentLabel="true"] { - color: #1A1C1F; + color: $ds_muted; font-size: 14px; font-weight: 500; } @@ -125,7 +129,7 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit { min-height: 30px; padding: 0 11px; border: 1px solid #EDEDEE; - border-radius: 9px; + border-radius: 10px; background-color: #FFFFFF; color: #1A1C1F; selection-background-color: #EEF1FA; @@ -145,7 +149,14 @@ QDialog#AppointmentDrawerOverlay QPlainTextEdit:hover { QDialog#AppointmentDrawerOverlay QComboBox:focus, QDialog#AppointmentDrawerOverlay QLineEdit:focus, QDialog#AppointmentDrawerOverlay QPlainTextEdit:focus { - border: 2px solid #8B9AD9; + border: 1px solid #8B9AD9; +} +QDialog#AppointmentDrawerOverlay QComboBox:disabled, +QDialog#AppointmentDrawerOverlay QLineEdit:disabled, +QDialog#AppointmentDrawerOverlay QPlainTextEdit:disabled { + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog#AppointmentDrawerOverlay QComboBox::drop-down { @@ -197,7 +208,7 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"] { max-height: 38px; padding: 0; border: 1px solid #EDEDEE; - border-radius: 8px; + border-radius: 10px; background-color: #FFFFFF; color: #1A1C1F; font-size: 14px; @@ -221,15 +232,15 @@ QDialog#AppointmentDrawerOverlay QPushButton[appointmentDate="true"]:checked { } QDialog#AppointmentDrawerOverlay QFrame#AppointmentSlotsPanel { - background-color: #F7F7F7; + background-color: $ds_surface_alt; border: 0; - border-radius: 8px; + border-radius: $ds_radius_panel; } QDialog#AppointmentDrawerOverlay QLabel#AppointmentSlotsTitle { color: #1A1C1F; font-size: 15px; - font-weight: 500; + font-weight: 600; } QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots { @@ -247,13 +258,17 @@ QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots { QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:hover { background-color: #EEF1FA; } +QDialog#AppointmentDrawerOverlay QPushButton#AppointmentRefreshSlots:focus { + background-color: $ds_accent_soft; + border: 1px solid $ds_focus; +} QDialog#AppointmentDrawerOverlay QPushButton[appointmentSlot="true"] { min-width: 110px; min-height: 70px; padding: 0 8px; border: 2px solid #EDEDEE; - border-radius: 8px; + border-radius: 10px; background-color: #FFFFFF; color: #1A1C1F; } @@ -330,25 +345,25 @@ QDialog#AppointmentDrawerOverlay QLabel#AppointmentEmptyText { QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] { background-color: #EEF1FA; border: 1px solid #EDEDEE; - border-radius: 9px; + border-radius: 10px; } QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="warning"] { background-color: #FFF5E6; border: 1px solid #F6E3C4; - border-radius: 9px; + border-radius: 10px; } QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="danger"] { background-color: #FFF1F3; border: 1px solid #F7D7DC; - border-radius: 9px; + border-radius: 10px; } QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="success"] { background-color: #EAF9F3; border: 1px solid #D4F0E5; - border-radius: 9px; + border-radius: 10px; } QDialog#AppointmentDrawerOverlay QFrame#AppointmentAlert[kind="info"] QLabel { @@ -378,7 +393,7 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton { max-height: 30px; padding: 0 15px; border: 1px solid #EDEDEE; - border-radius: 9px; + border-radius: 10px; background-color: #FFFFFF; color: #1A1C1F; font-size: 13px; @@ -408,9 +423,14 @@ QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[prim } QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton:disabled { - color: #FFFFFF; - border-color: #EDEDEE; - background-color: #8E8F90; + color: $ds_disabled; + border-color: $ds_line; + background-color: $ds_disabled_surface; +} +QDialog#AppointmentDrawerOverlay QFrame#AppointmentDrawerFooter QPushButton[primary="true"]:pressed { + color: $ds_surface; + background-color: $ds_accent_pressed; + border-color: $ds_accent_pressed; } QDialog#AppointmentDrawerOverlay QFrame#AppointmentLoadingOverlay { @@ -487,6 +507,7 @@ _APPOINTMENT_DARK_REPLACEMENTS = ( ) # Light is the default application theme. Keep the replacement table available # for a future explicit dark-mode switch, but do not mutate the light source QSS. +APPOINTMENT_DRAWER_QSS = clinical_stylesheet(APPOINTMENT_DRAWER_QSS) def _as_int(value: Any, default: int = 0) -> int: @@ -733,35 +754,7 @@ class _EmptyIllustration(QWidget): painter.end() -class _HoverLiftButton(QPushButton): - """Button with a subtle two-pixel lift and blue-tinted shadow on hover.""" - - def __init__(self, text: str = "", parent: QWidget | None = None) -> None: - super().__init__(text, parent) - self._lifted = False - self._base_position = QPoint() - - def enterEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API - if self.isEnabled() and not self._lifted: - self._base_position = self.pos() - self.move(self.x(), self.y() - 2) - shadow = QGraphicsDropShadowEffect(self) - shadow.setBlurRadius(12) - shadow.setOffset(0, 4) - shadow.setColor(QColor(26, 28, 31, 72)) - self.setGraphicsEffect(shadow) - self._lifted = True - super().enterEvent(event) - - def leaveEvent(self, event: QEvent) -> None: # noqa: N802 - Qt API - if self._lifted: - self.move(self._base_position) - self.setGraphicsEffect(None) - self._lifted = False - super().leaveEvent(event) - - -class _SlotCard(_HoverLiftButton): +class _SlotCard(QPushButton): """Two-line time card matching Element's independent time/status typography.""" def __init__(self, time_text: str, status_text: str) -> None: @@ -819,8 +812,8 @@ class AppointmentDrawer(QDialog): self._today_blocking = False self._channel_names: dict[str, str] = {} self._doctor_buttons: dict[int, QRadioButton] = {} - self._date_buttons: dict[str, _HoverLiftButton] = {} - self._slot_buttons: dict[str, _HoverLiftButton] = {} + self._date_buttons: dict[str, QPushButton] = {} + self._slot_buttons: dict[str, QPushButton] = {} self._slot_available: dict[str, bool] = {} self._slot_restore_selection = "" self._active_loading = "" @@ -1426,7 +1419,7 @@ class AppointmentDrawer(QDialog): continue label = f"{parsed.toString('MM月dd日')} ({week_days[parsed.dayOfWeek() % 7]})" self.date_combo.addItem(label, value) - button = _HoverLiftButton(label) + button = QPushButton(label) button.setProperty("appointmentDate", True) button.setCheckable(True) button.setFixedSize(130, 40) diff --git a/app/src/doctor_workstation/ui/appointments_style.py b/app/src/doctor_workstation/ui/appointments_style.py index 194fd7bdc..134f8e343 100644 --- a/app/src/doctor_workstation/ui/appointments_style.py +++ b/app/src/doctor_workstation/ui/appointments_style.py @@ -2,143 +2,155 @@ from string import Template +from .design_system import clinical_stylesheet from .reception_style import body_family, heading_family def appointments_stylesheet() -> str: - return Template(_QSS).substitute(body=body_family(), heading=heading_family()) + return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family())) _QSS = """ -#AppointmentsPage { background: #F3F7FD; color: #273244; } +#AppointmentsPage { background: $ds_canvas; color: $ds_text; } #AppointmentsPage QLabel, #AppointmentsPage QPushButton, #AppointmentsPage QLineEdit, #AppointmentsPage QComboBox, #AppointmentsPage QTabBar, #AppointmentsPage QTableWidget { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; } #AppointmentsPage QWidget#PageHeader QLabel[role="pageTitle"] { - font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F; + font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading; } #AppointmentsPage QWidget#PageHeader QLabel[role="muted"], #AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumb"], #AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbSeparator"], #AppointmentsPage QWidget#PageHeader QLabel[role="breadcrumbCurrent"] { - color: #5D6B80; font-size: 13px; font-weight: 400; + color: $ds_muted; font-size: 13px; font-weight: 400; } #AppointmentsPage QFrame#AppointmentFilterPanel, #AppointmentsPage QFrame#AppointmentMainCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; } #AppointmentsPage QPushButton { - min-height: 30px; padding: 0 12px; border: 1px solid #DBE5F2; - border-radius: 6px; background: #FFFFFF; + min-height: 30px; padding: 0 12px; border: 1px solid transparent; + border-radius: $ds_radius_control; background: $ds_surface_alt; } -#AppointmentsPage QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; } -#AppointmentsPage QPushButton:pressed { background: #DCEAFF; } -#AppointmentsPage QPushButton:focus { border-color: #75A5F0; } +#AppointmentsPage QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; } +#AppointmentsPage QPushButton:pressed { background: $ds_accent_soft; } +#AppointmentsPage QPushButton:focus { border-color: $ds_focus; } #AppointmentsPage QPushButton[variant="primary"] { - background: #1769E8; color: #FFFFFF; border-color: #1769E8; + background: $ds_accent; color: $ds_surface; border-color: $ds_accent; } -#AppointmentsPage QPushButton[variant="primary"]:hover { background: #155BCC; } -#AppointmentsPage QPushButton[variant="primary"]:pressed { background: #124EA9; } +#AppointmentsPage QPushButton[variant="primary"]:hover { background: $ds_accent_hover; } +#AppointmentsPage QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; } +#AppointmentsPage QPushButton[variant="primary"]:focus { border-color: $ds_focus; } #AppointmentsPage QPushButton[variant="danger"] { - color: #B84652; background: #FFFFFF; border-color: #EFC8CE; + color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } -#AppointmentsPage QPushButton[variant="danger"]:hover { background: #FFF0F2; } +#AppointmentsPage QPushButton[variant="danger"]:hover { background: $ds_danger_soft; } +#AppointmentsPage QPushButton[variant="danger"]:pressed { border-color: $ds_danger; } #AppointmentsPage QPushButton[variant="ghost"] { background: transparent; border-color: transparent; } -#AppointmentsPage QPushButton:disabled { - color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; +#AppointmentsPage QPushButton[variant="ghost"]:hover { background: $ds_accent_soft; } +#AppointmentsPage QPushButton[variant="ghost"]:focus { border-color: $ds_focus; } +#AppointmentsPage QPushButton:disabled, #AppointmentsPage QPushButton[variant="primary"]:disabled, +#AppointmentsPage QPushButton[variant="danger"]:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; } #AppointmentsPage QLineEdit, #AppointmentsPage QComboBox { - min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF; + min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft; } -#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: #75A5F0; } +#AppointmentsPage QLineEdit:focus, #AppointmentsPage QComboBox:focus { border-color: $ds_focus; } #AppointmentsPage QLineEdit QToolButton { min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent; } -#AppointmentsPage QLineEdit QToolButton:focus { background: #EAF2FF; } +#AppointmentsPage QLineEdit QToolButton:focus { background: $ds_accent_soft; } #AppointmentsPage QPushButton#AppointmentSearchButton { min-height: 39px; max-height: 39px; min-width: 52px; } #AppointmentsPage QLineEdit#AppointmentPatientSearch { min-height: 39px; max-height: 39px; } #AppointmentsPage QPushButton[appointmentStat="true"] { - min-height: 34px; max-height: 34px; padding: 0 10px; background: #F4F7FC; - border-color: transparent; color: #5D6B80; font-size: 13px; + min-height: 34px; max-height: 34px; padding: 0 10px; background: $ds_canvas; + border-color: transparent; color: $ds_muted; font-size: 13px; } -#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: #1555B6; background: #EAF2FF; } +#AppointmentsPage QPushButton[appointmentStat="true"]:hover { color: $ds_accent; background: $ds_accent_soft; } #AppointmentsPage QPushButton[appointmentStat="true"]:checked { - color: #FFFFFF; background: #1769E8; border-color: #1769E8; + color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; } #AppointmentsPage QPushButton[appointmentStatKind="warning"][hasPending="true"]:!checked { - color: #9C681F; background: #FFF6E7; border-color: #EEDCBF; + color: $ds_warning; background: $ds_warning_soft; border-color: $ds_warning_soft; } -#AppointmentsPage QLabel#FilterRowLabel { color: #5D6B80; font-size: 13px; } -#AppointmentsPage QLabel#FilterDivider { color: #DBE5F2; padding: 0 10px; } +#AppointmentsPage QLabel#FilterRowLabel { color: $ds_muted; font-size: 13px; } +#AppointmentsPage QLabel#FilterDivider { color: $ds_line; padding: 0 10px; } #AppointmentsPage QTabBar#AppointmentStatusTabs::tab { - min-width: 52px; min-height: 32px; padding: 0 12px; color: #5D6B80; + min-width: 52px; min-height: 32px; padding: 0 12px; color: $ds_muted; background: transparent; border: 0; border-bottom: 2px solid transparent; font-size: 13px; } -#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: #1555B6; background: #F7FAFE; } +#AppointmentsPage QTabBar#AppointmentStatusTabs::tab:hover { color: $ds_accent; background: $ds_surface_alt; } #AppointmentsPage QTabBar#AppointmentStatusTabs::tab:selected { - color: #1769E8; background: transparent; border-bottom-color: #1769E8; + color: $ds_accent; background: transparent; border-bottom-color: $ds_accent; } #AppointmentsPage QPushButton[filterChoice="true"] { - min-height: 30px; max-height: 30px; padding: 0 12px; color: #5D6B80; + min-height: 30px; max-height: 30px; padding: 0 12px; color: $ds_muted; background: transparent; border-color: transparent; font-size: 13px; } -#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: #1555B6; background: #EAF2FF; } +#AppointmentsPage QPushButton[filterChoice="true"]:checked { color: $ds_accent; background: $ds_accent_soft; } +#AppointmentsPage QPushButton[filterChoice="true"]:focus, +#AppointmentsPage QPushButton[appointmentStat="true"]:focus { border-color: $ds_focus; } #AppointmentsPage QFrame#AppointmentToolbar { background: transparent; border: 0; } #AppointmentsPage QPushButton[compactAction="true"] { min-height: 36px; max-height: 36px; padding: 0 17px; font-size: 13px; } #AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:enabled { - color: #1769E8; border-color: #ADC8F0; + color: $ds_text; border-color: transparent; } +#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:hover { color: $ds_accent; background: $ds_accent_soft; } +#AppointmentsPage QFrame#AppointmentToolbar QPushButton[variant="secondary"]:focus { border-color: $ds_focus; } #AppointmentsPage QTableWidget#AppointmentTable { - background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0; - gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244; + background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0; + gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text; } -#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid #E6EDF6; } -#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: #EAF2FF; color: #273244; } +#AppointmentsPage QTableWidget#AppointmentTable::item { padding: 0; border: 0; border-bottom: 1px solid $ds_line; } +#AppointmentsPage QTableWidget#AppointmentTable::item:selected { background: $ds_accent_soft; color: $ds_text; } #AppointmentsPage QTableWidget#AppointmentTable QHeaderView::section { - min-height: 40px; padding: 0; background: #F5F8FD; color: #5D6B80; - border: 0; border-top: 1px solid #E1E9F4; border-bottom: 1px solid #E1E9F4; + min-height: 40px; padding: 0; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line; font-family: "$body"; font-size: 13px; font-weight: 400; } #AppointmentsPage QWidget[appointmentSelectionHost="true"] { background: transparent; border-left: 3px solid transparent; } -#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: #1769E8; } +#AppointmentsPage QWidget[appointmentSelectionHost="true"][selected="true"] { border-left-color: $ds_accent; } #AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator { - width: 16px; height: 16px; background: #FFFFFF; border: 1px solid #C8D5E6; border-radius: 3px; + width: 16px; height: 16px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px; } -#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; } +#AppointmentsPage QCheckBox[appointmentSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; } #AppointmentsPage QWidget[appointmentInfoHost="true"], #AppointmentsPage QWidget[appointmentImHost="true"] { background: transparent; } #AppointmentsPage QLabel[tableAppointmentStatus="true"] { - min-height: 20px; max-height: 20px; padding: 0 6px; color: #1555B6; - background: #EAF2FF; border-radius: 4px; font-size: 13px; + min-height: 20px; max-height: 20px; padding: 0 6px; color: $ds_accent; + background: $ds_accent_soft; border-radius: $ds_radius_small; font-size: 13px; } -#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: #9C681F; background: #FFF3DD; } -#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: #66758A; background: #EEF2F7; } -#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: #5D6B80; font-size: 13px; } +#AppointmentsPage QLabel[tableAppointmentStatusKind="warning"] { color: $ds_warning; background: $ds_warning_soft; } +#AppointmentsPage QLabel[tableAppointmentStatusKind="muted"] { color: $ds_muted; background: $ds_disabled_surface; } +#AppointmentsPage QLabel[tableAppointmentMeta="true"] { color: $ds_muted; font-size: 13px; } #AppointmentsPage QPushButton[tableCancelAction="true"] { - min-height: 20px; max-height: 20px; padding: 0 5px; color: #B84652; - background: #FFF0F2; border: 0; border-radius: 4px; font-size: 13px; + min-height: 20px; max-height: 20px; padding: 0 5px; color: $ds_danger; + background: $ds_danger_soft; border: 0; border-radius: $ds_radius_small; font-size: 13px; } #AppointmentsPage QPushButton[appointmentImAction="true"] { min-width: 62px; min-height: 32px; max-height: 32px; padding: 0 10px; - color: #1555B6; background: #EAF2FF; border-color: #C9DCF7; font-size: 13px; + color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-size: 13px; } -#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: #FFFFFF; background: #1769E8; } -#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: #8A97A9; background: #F3F6FB; border-color: #DFE7F2; } -#AppointmentsPage QWidget#Pager { background: #FFFFFF; border: 0; border-top: 1px solid #E1E9F4; } -#AppointmentsPage QWidget#Pager QLabel { color: #5D6B80; font-size: 13px; border: 0; } +#AppointmentsPage QPushButton[appointmentImAction="true"]:hover { color: $ds_accent_hover; border-color: $ds_line_strong; } +#AppointmentsPage QPushButton[appointmentImAction="true"]:focus { border-color: $ds_focus; } +#AppointmentsPage QPushButton[appointmentImAction="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; } +#AppointmentsPage QWidget#Pager { background: $ds_surface; border: 0; border-top: 1px solid $ds_line; } +#AppointmentsPage QWidget#Pager QLabel { color: $ds_muted; font-size: 13px; border: 0; } #AppointmentsPage QWidget#Pager QPushButton { min-width: 30px; max-width: 30px; min-height: 32px; max-height: 32px; - padding: 0; border: 1px solid #DBE5F2; background: #FFFFFF; color: #5D6B80; font-size: 13px; + padding: 0; border: 1px solid $ds_line; background: $ds_surface; color: $ds_muted; font-size: 13px; } -#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; } -#AppointmentsPage QWidget#Pager QPushButton:disabled { color: #9AA6B7; background: #F7F9FC; } +#AppointmentsPage QWidget#Pager QPushButton[active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; } +#AppointmentsPage QWidget#Pager QPushButton:focus { border-color: $ds_focus; } +#AppointmentsPage QWidget#Pager QPushButton:disabled { color: $ds_disabled; background: $ds_surface_alt; } """ diff --git a/app/src/doctor_workstation/ui/chat_notifications.py b/app/src/doctor_workstation/ui/chat_notifications.py index c5f2526fa..a29f21717 100644 --- a/app/src/doctor_workstation/ui/chat_notifications.py +++ b/app/src/doctor_workstation/ui/chat_notifications.py @@ -24,6 +24,7 @@ from PySide6.QtWidgets import ( QWidget, ) +from .design_system import clinical_stylesheet from .widgets import display_text, first_value, run_async # 后台 ChatNotifyLogic 写入的三种 type。 @@ -260,7 +261,7 @@ class ChatNotificationCenter(QWidget): super().__init__(host) self.repository = repository self.setObjectName("ChatNotifyLayer") - self.setStyleSheet(CHAT_NOTIFICATION_QSS) + self.setStyleSheet(clinical_stylesheet(CHAT_NOTIFICATION_QSS)) self.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, False) self._cards: dict[str, _NotificationCard] = {} self._pending: list[ChatNotification] = [] diff --git a/app/src/doctor_workstation/ui/consultations_style.py b/app/src/doctor_workstation/ui/consultations_style.py index 92359094d..286713d09 100644 --- a/app/src/doctor_workstation/ui/consultations_style.py +++ b/app/src/doctor_workstation/ui/consultations_style.py @@ -2,59 +2,67 @@ from string import Template +from .design_system import clinical_stylesheet from .reception_style import body_family, heading_family def consultations_stylesheet() -> str: - return Template(_QSS).substitute(body=body_family(), heading=heading_family()) + return clinical_stylesheet(Template(_QSS).safe_substitute(body=body_family(), heading=heading_family())) _QSS = """ #DiagnosisIndex, #DiagnosisIndexContent, #DiagnosisPageScroll { - background: #F3F7FD; color: #273244; border: 0; + background: $ds_canvas; color: $ds_text; border: 0; } #DiagnosisIndex QLabel, #DiagnosisIndex QPushButton, #DiagnosisIndex QToolButton, #DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox, #DiagnosisIndex QTableView { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; } #DiagnosisIndex QWidget#PageHeader QLabel[role="pageTitle"] { - font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F; + font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading; } #DiagnosisIndex QLabel[role="muted"], #DiagnosisIndex QLabel[role="breadcrumb"], #DiagnosisIndex QLabel[role="breadcrumbCurrent"], #DiagnosisIndex QLabel[role="breadcrumbSeparator"], #DiagnosisIndex QLabel[filterGroup="true"], #DiagnosisIndex QLabel[pagerMuted="true"] { - color: #5D6B80; font-size: 13px; + color: $ds_muted; font-size: 13px; } #DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; } #DiagnosisIndex QFrame#DiagnosisStatusCard, #DiagnosisIndex QFrame#DiagnosisQuickFilters, #DiagnosisIndex QFrame#DiagnosisListToolbar { background: transparent; border: 0; } #DiagnosisIndex QFrame#DiagnosisAdvancedFilters { - background: transparent; border: 0; border-top: 1px solid #E6EDF6; border-radius: 0; + background: transparent; border: 0; border-top: 1px solid $ds_line; border-radius: 0; } #DiagnosisIndex QPushButton { - min-height: 34px; padding: 0 13px; border: 1px solid #DBE5F2; - border-radius: 6px; background: #FFFFFF; + min-height: 34px; padding: 0 13px; border: 1px solid transparent; + border-radius: $ds_radius_control; background: $ds_surface_alt; } -#DiagnosisIndex QPushButton:hover { color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; } -#DiagnosisIndex QPushButton:pressed { background: #DCEAFF; } -#DiagnosisIndex QPushButton:focus { border-color: #75A5F0; } -#DiagnosisIndex QPushButton[variant="primary"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; } -#DiagnosisIndex QPushButton[variant="primary"]:hover { background: #155BCC; } -#DiagnosisIndex QPushButton[consultationTool="true"] { color: #1555B6; border-color: #C2D5EF; } -#DiagnosisIndex QPushButton[consultationDanger="true"] { color: #BE4B58; border-color: #EBCDD2; } -#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled { - color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; +#DiagnosisIndex QPushButton:hover { color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; } +#DiagnosisIndex QPushButton:pressed { background: $ds_accent_soft; } +#DiagnosisIndex QPushButton:focus { border-color: $ds_focus; } +#DiagnosisIndex QPushButton[variant="primary"] { color: $ds_surface; background: $ds_accent; border-color: $ds_accent; } +#DiagnosisIndex QPushButton[variant="primary"]:hover { background: $ds_accent_hover; } +#DiagnosisIndex QPushButton[variant="primary"]:pressed { background: $ds_accent_pressed; } +#DiagnosisIndex QPushButton[variant="primary"]:focus { border-color: $ds_focus; } +#DiagnosisIndex QPushButton[consultationTool="true"] { color: $ds_text; border-color: transparent; } +#DiagnosisIndex QPushButton[consultationTool="true"]:hover { color: $ds_accent; background: $ds_accent_soft; } +#DiagnosisIndex QPushButton[consultationDanger="true"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#DiagnosisIndex QPushButton[consultationDanger="true"]:hover { border-color: $ds_danger; } +#DiagnosisIndex QPushButton[consultationTool="true"]:focus, +#DiagnosisIndex QPushButton[consultationDanger="true"]:focus { border-color: $ds_focus; } +#DiagnosisIndex QPushButton:disabled, #DiagnosisIndex QPushButton[consultationDanger="true"]:disabled, +#DiagnosisIndex QPushButton[variant="primary"]:disabled, #DiagnosisIndex QPushButton[consultationTool="true"]:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; } #DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox { - min-height: 32px; padding: 0 10px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; border-radius: 6px; selection-background-color: #DCEAFF; + min-height: 32px; padding: 0 10px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft; font-size: 13px; } #DiagnosisIndex QLineEdit:focus, #DiagnosisIndex QComboBox:focus, -#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: #75A5F0; } +#DiagnosisIndex QDateEdit:focus, #DiagnosisIndex QSpinBox:focus { border-color: $ds_focus; } #DiagnosisIndex QLineEdit QToolButton { min-width: 0; min-height: 0; padding: 0; border: 0; background: transparent; } @@ -62,70 +70,77 @@ _QSS = """ width: 22px; border: 0; background: transparent; } #DiagnosisIndex QComboBox QAbstractItemView { - color: #273244; background: #FFFFFF; border: 1px solid #DBE5F2; - selection-background-color: #EAF2FF; selection-color: #1555B6; outline: 0; + color: $ds_text; background: $ds_surface; border: 1px solid $ds_line; + selection-background-color: $ds_accent_soft; selection-color: $ds_accent; outline: 0; } #DiagnosisIndex QWidget#DiagnosisStatusSearch QLineEdit, #DiagnosisIndex QWidget#DiagnosisStatusSearch QPushButton { min-height: 39px; max-height: 39px; } #DiagnosisIndex QToolButton { min-width: 0; min-height: 0; border: 0; padding: 0; background: transparent; } #DiagnosisIndex QToolButton[diagnosisChip="true"] { min-height: 32px; max-height: 32px; padding: 0 14px; border: 1px solid transparent; - border-radius: 5px; color: #5D6B80; background: transparent; font-size: 13px; + border-radius: $ds_radius_control; color: $ds_muted; background: transparent; font-size: 13px; } -#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: #F2F7FF; color: #1555B6; } -#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: #1769E8; color: #FFFFFF; } -#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; border-color: #E1E9F4; } -#DiagnosisIndex QToolButton[dateChoice="true"]:checked { border-color: #1769E8; } +#DiagnosisIndex QToolButton[diagnosisChip="true"]:hover { background: $ds_surface_alt; color: $ds_accent; } +#DiagnosisIndex QToolButton[diagnosisChip="true"]:checked { background: $ds_accent_soft; color: $ds_accent; font-weight: 600; } +#DiagnosisIndex QToolButton[dateChoice="true"] { padding: 0 17px; background: $ds_surface_alt; border-color: transparent; } +#DiagnosisIndex QToolButton[dateChoice="true"]:checked { background: $ds_accent_soft; border-color: transparent; } +#DiagnosisIndex QToolButton[diagnosisChip="true"]:focus { border-color: $ds_focus; } #DiagnosisIndex QToolButton[statusTab="true"] { min-height: 44px; max-height: 44px; padding: 0 20px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; } #DiagnosisIndex QToolButton[statusTab="true"]:checked { - color: #1769E8; background: transparent; border-bottom-color: #1769E8; + color: $ds_accent; background: transparent; border-bottom-color: $ds_accent; } +#DiagnosisIndex QToolButton[statusTab="true"]:focus { background: $ds_accent_soft; } #DiagnosisIndex QToolButton#DiagnosisMoreFilter { - min-height: 32px; padding: 0 6px; color: #5D6B80; font-size: 13px; + min-height: 32px; padding: 0 6px; color: $ds_muted; font-size: 13px; } -#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: #1769E8; background: #F2F7FF; } -#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: #E1E9F4; border: 0; } +#DiagnosisIndex QToolButton#DiagnosisMoreFilter:hover { color: $ds_accent; background: $ds_surface_alt; } +#DiagnosisIndex QFrame#DiagnosisFilterDivider { min-width: 1px; max-width: 1px; min-height: 20px; background: $ds_line; border: 0; } #DiagnosisIndex QFrame#DiagnosisDateRange { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px; + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control; } #DiagnosisIndex QDateEdit[diagnosisRangePart="true"] { min-height: 30px; padding: 0 4px; border: 0; } #DiagnosisIndex QTableView { - background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0; - gridline-color: #E6EDF6; selection-background-color: #EAF2FF; selection-color: #273244; + background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0; + gridline-color: $ds_line; selection-background-color: $ds_accent_soft; selection-color: $ds_text; } #DiagnosisIndex QTableView QHeaderView::section { - min-height: 41px; padding: 0; background: #F5F8FD; color: #5D6B80; - border: 0; border-bottom: 1px solid #E1E9F4; + min-height: 41px; padding: 0; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-bottom: 1px solid $ds_line; font-family: "$body"; font-size: 13px; font-weight: 400; } #DiagnosisIndex QToolButton[rowLink], #DiagnosisIndex QToolButton[appointmentCancel="true"] { - color: #1769E8; min-height: 26px; padding: 0 4px; border: 0; background: transparent; font-size: 13px; + color: $ds_accent; min-height: 26px; padding: 0 4px; border: 1px solid transparent; + border-radius: $ds_radius_small; background: transparent; font-size: 13px; } -#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: #BE4B58; } -#DiagnosisIndex QToolButton[rowLink]:hover { color: #1555B6; background: #DCEAFF; border-radius: 4px; } +#DiagnosisIndex QToolButton[appointmentCancel="true"] { color: $ds_danger; } +#DiagnosisIndex QToolButton[appointmentCancel="true"]:hover { background: $ds_danger_soft; } +#DiagnosisIndex QToolButton[rowLink]:hover { color: $ds_accent; background: $ds_accent_soft; border-radius: $ds_radius_small; } +#DiagnosisIndex QToolButton[rowLink]:focus, +#DiagnosisIndex QToolButton[appointmentCancel="true"]:focus { border-color: $ds_focus; } #DiagnosisIndex QToolButton[rowLink="muted"], #DiagnosisIndex QLabel[fixedMuted="true"] { - color: #5D6B80; font-size: 13px; + color: $ds_muted; font-size: 13px; } #DiagnosisIndex QToolButton#DiagnosisRowMore { padding-right: 18px; } #DiagnosisIndex QWidget#DiagnosisFixedCell { background: transparent; } -#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: #5D6B80; background: #FFFFFF; } -#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: #BE4B58; } -#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid #E1E9F4; } -#DiagnosisIndex QWidget#DiagnosisPager { background: #FFFFFF; border-top: 1px solid #E6EDF6; } +#DiagnosisIndex QLabel#DiagnosisTableEmpty { color: $ds_muted; background: $ds_surface; } +#DiagnosisIndex QLabel#DiagnosisTableEmpty[stateKind="error"] { color: $ds_danger; } +#DiagnosisIndex QTableView#DiagnosisFixedTable { border-left: 1px solid $ds_line; } +#DiagnosisIndex QWidget#DiagnosisPager { background: $ds_surface; border-top: 1px solid $ds_line; } #DiagnosisIndex QToolButton[pagerButton="true"] { min-width: 30px; max-width: 30px; min-height: 30px; max-height: 30px; - border: 1px solid #DBE5F2; border-radius: 5px; color: #5D6B80; background: #FFFFFF; + border: 1px solid $ds_line; border-radius: $ds_radius_control; color: $ds_muted; background: $ds_surface; } -#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: #FFFFFF; background: #1769E8; border-color: #1769E8; } -#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: #A4B0C0; background: #F6F8FC; } +#DiagnosisIndex QToolButton[pagerButton="true"][active="true"] { color: $ds_accent; background: $ds_accent_soft; border-color: transparent; font-weight: 600; } +#DiagnosisIndex QToolButton[pagerButton="true"]:focus { border-color: $ds_focus; } +#DiagnosisIndex QToolButton[pagerButton="true"]:disabled { color: $ds_disabled; background: $ds_disabled_surface; } #DiagnosisIndex QComboBox#DiagnosisPageSize { min-width: 95px; min-height: 30px; } #DiagnosisIndex QSpinBox#DiagnosisPageJumper { min-height: 30px; padding: 0 8px; } -#DiagnosisIndex QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#DiagnosisIndex QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#DiagnosisIndex QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } +#DiagnosisIndex QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#DiagnosisIndex QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#DiagnosisIndex QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } #DiagnosisIndex QScrollBar::add-line, #DiagnosisIndex QScrollBar::sub-line { width: 0; height: 0; } #DiagnosisIndex QScrollBar::add-page, #DiagnosisIndex QScrollBar::sub-page { background: transparent; } """ diff --git a/app/src/doctor_workstation/ui/design_system.py b/app/src/doctor_workstation/ui/design_system.py new file mode 100644 index 000000000..0319c8a9e --- /dev/null +++ b/app/src/doctor_workstation/ui/design_system.py @@ -0,0 +1,76 @@ +"""Clinical desktop design tokens, shared by native pages and dialog chrome. + +Keep data-series colours and video pixels outside this palette. Existing scoped +QSS can adopt the system without changing selectors, layout or permissions. +New rules should use the named ``$ds_*`` tokens rather than legacy colours. +""" + +from __future__ import annotations + +import re +from string import Template + +PALETTE = { + "canvas": "#F5F7FA", + "surface": "#FFFFFF", + "surface_alt": "#F7F9FC", + "sidebar": "#F0F3F8", + "line": "#E6EAF0", + "line_strong": "#D4DCE8", + "heading": "#223047", + "text": "#344258", + "muted": "#647287", + "disabled": "#8B96A6", + "disabled_surface": "#F0F2F5", + "accent": "#4267B2", + "accent_hover": "#355995", + "accent_pressed": "#2C4C82", + "accent_soft": "#EAF0FB", + "focus": "#6D8CCB", + "success": "#287B65", + "success_soft": "#EDF7F2", + "warning": "#96601D", + "warning_soft": "#FBF4E8", + "danger": "#B54A59", + "danger_soft": "#FCF0F2", +} + +RADII = {"small": 6, "control": 10, "panel": 16, "window": 20} +SPACING = {"small": 8, "control": 12, "group": 16, "section": 24} + +TOKENS = {f"ds_{name}": value for name, value in PALETTE.items()} +TOKENS.update({f"ds_radius_{name}": f"{value}px" for name, value in RADII.items()}) +TOKENS.update({f"ds_space_{name}": f"{value}px" for name, value in SPACING.items()}) + +# Explicit migration of the two existing native palettes. This adapter only +# touches six-digit colour literals; selectors and metrics stay page-owned. +_LEGACY_ROLES = { + "accent": ("1769E8", "4F63D9", "5761F4", "5267DF"), + "accent_hover": ("155BCC", "1555B6", "4156C4", "4356C4", "4055CA"), + "accent_pressed": ("124EA9", "354BB4"), + "accent_soft": ("EAF2FF", "EEF1FA", "EEF0FF", "F0F2FF", "DCEAFF", "EDF0FC"), + "focus": ("75A5F0", "8B9AD9"), + "canvas": ("F3F7FD", "F4F6FA", "F6F6F6"), + "surface_alt": ("F7F7F7", "F7FAFE", "F5F8FD", "F7F9FE", "F2F7FF"), + "sidebar": ("EDF4FF",), + "line": ("DBE5F2", "EDEDEE", "E5ECF6", "E6EDF6", "E7EDF7", "EDF0F5", "E7EBF2", "E6EAF5"), + "line_strong": ("E4E4E5", "C8D5E6", "C9DCF7", "ADC8F0", "B6CDEE"), + "heading": ("1A1C1F", "202C3F", "111F46"), + "text": ("273244", "263551", "24334A", "233149", "3F4E75"), + "muted": ("606163", "6A6B6D", "5D6B80", "7886AA", "708097"), + "disabled": ("8E8F90", "8A97A9", "9AA6B7"), + "disabled_surface": ("F2F2F2", "F0F0F0"), + "success_soft": ("EEF7F3", "EAF9F3"), + "warning": ("A9691D", "9C681F"), + "warning_soft": ("FCF5E9", "FFF5E6", "FFF6E7"), + "danger": ("BE4B58", "B84652"), + "danger_soft": ("FFF0F2", "FFF1F3"), +} +_LEGACY = {colour.lower(): PALETTE[role] for role, colours in _LEGACY_ROLES.items() for colour in colours} +_HEX = re.compile(r"#([0-9a-fA-F]{6})(?![0-9a-fA-F])") + + +def clinical_stylesheet(source: str) -> str: + """Resolve clinical tokens and migrate known legacy light-theme colours.""" + resolved = Template(source).safe_substitute(TOKENS) + return _HEX.sub(lambda match: _LEGACY.get(match[1].lower(), match[0]), resolved) diff --git a/app/src/doctor_workstation/ui/diagnosis_drawer.py b/app/src/doctor_workstation/ui/diagnosis_drawer.py index 231731f30..38dae4767 100644 --- a/app/src/doctor_workstation/ui/diagnosis_drawer.py +++ b/app/src/doctor_workstation/ui/diagnosis_drawer.py @@ -64,6 +64,7 @@ from PySide6.QtWidgets import ( ) from .chat_items import ChatItem, parse_chat_item +from .design_system import PALETTE, clinical_stylesheet from .diagnosis_editors import FlowLayout from .diagnosis_media import shared_image_manager from .diagnosis_terms import FIELD_DICTIONARIES, format_timestamp, shared_terms @@ -80,10 +81,7 @@ QFrame#DiagnosisDrawer { border-left: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerHeader { - background-color: qlineargradient( - x1:0, y1:0, x2:0, y2:1, - stop:0 #FFFFFF, stop:1 #F7F7F7 - ); + background-color: #FFFFFF; border-bottom: 1px solid #EDEDEE; } QFrame#DiagnosisDrawerFooter { @@ -105,7 +103,7 @@ QLabel#DiagnosisDrawerModeBadge, QLabel#DiagnosisReadonlyStatus, QLabel[diagnosisTag="true"] { padding: 4px 9px; - border-radius: 9px; + border-radius: $ds_radius_small; font-size: 12px; font-weight: 500; } @@ -159,8 +157,8 @@ QDialog QPushButton:pressed { border-color: #354BB4; } QDialog QPushButton:disabled { - color: #E4E4E5; - background-color: #FFFFFF; + color: $ds_disabled; + background-color: $ds_disabled_surface; border-color: #EDEDEE; } QDialog QPushButton[variant="primary"] { @@ -176,9 +174,9 @@ QDialog QPushButton[variant="primary"]:focus { border-color: #4156C4; } QDialog QPushButton[variant="primary"]:disabled { - color: #FFFFFF; - background-color: #F0F0F0; - border-color: #F0F0F0; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog QPushButton[variant="secondary"] { color: #4F63D9; @@ -267,9 +265,9 @@ QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:focus { border-color: #4156C4; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisSaveButton:disabled { - color: #FFFFFF; - background-color: #F0F0F0; - border-color: #F0F0F0; + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; } QDialog#DiagnosisDialogRoot QPushButton#DiagnosisFooterCloseButton { color: #606163; @@ -383,10 +381,10 @@ QFrame#DiagnosisFormHost { QFrame[diagnosisSection="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 12px; + border-radius: 16px; } QLabel[diagnosisFieldLabel="true"] { - color: #1A1C1F; + color: $ds_muted; font-size: 12px; font-weight: 500; } @@ -426,7 +424,7 @@ QDoubleSpinBox[diagnosisField="true"]:focus, QSpinBox[diagnosisField="true"]:focus, QTimeEdit[diagnosisField="true"]:focus { border: 1px solid #8B9AD9; - background-color: #F7F7F7; + background-color: $ds_surface; } QLineEdit[diagnosisField="true"][invalid="true"], QComboBox[diagnosisField="true"][invalid="true"], @@ -452,8 +450,8 @@ QLabel#DiagnosisSectionTitle { background-color: transparent; border: 0; padding: 0; - font-size: 13px; - font-weight: 500; + font-size: 14px; + font-weight: 600; letter-spacing: 0.02em; } QFrame#DiagnosisSectionAccent { @@ -470,9 +468,9 @@ QFrame#DiagnosisReadonlyPage { background-color: #F6F6F6; } QFrame#DiagnosisReadonlyHero { - background-color: #F7F7F7; - border: 1px solid #F0F0F0; - border-radius: 12px; + background-color: $ds_surface; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QLabel#DiagnosisReadonlyTitle { color: #1A1C1F; @@ -542,7 +540,7 @@ QFrame#DiagnosisReadonlyCaseCard, QFrame[diagnosisReadonlyCard="true"] { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 14px; + border-radius: 16px; } QLabel#DiagnosisReadonlyCardTitle { color: #1A1C1F; @@ -771,7 +769,7 @@ QWidget[diagnosisChoiceHost="true"] QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 999px; + border-radius: 10px; font-size: 12px; } QWidget[diagnosisChoiceHost="true"] QPushButton:hover, @@ -1068,6 +1066,7 @@ _DIAGNOSIS_BLUE_REPLACEMENTS = ( ) for _source_color, _theme_color in _DIAGNOSIS_BLUE_REPLACEMENTS: DIAGNOSIS_QSS = DIAGNOSIS_QSS.replace(_source_color, _theme_color) +DIAGNOSIS_QSS = clinical_stylesheet(DIAGNOSIS_QSS) def _text(value: Any, default: str = "—") -> str: @@ -1147,12 +1146,19 @@ class DiagnosisSwitch(QAbstractButton): track = QRectF(1, 3, self.width() - 2, self.height() - 6) checked = self.isChecked() painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#4F63D9" if checked else "#E4E4E5")) + painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"])) + if not self.isEnabled(): + painter.setOpacity(0.6) painter.drawRoundedRect(track, track.height() / 2, track.height() / 2) diameter = track.height() - 4 x = track.right() - diameter - 2 if checked else track.left() + 2 painter.setBrush(QColor("#FFFFFF")) painter.drawEllipse(QRectF(x, track.top() + 2, diameter, diameter)) + if self.hasFocus(): + painter.setOpacity(1) + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 11, 11) painter.end() @@ -1190,13 +1196,19 @@ class SaveStateButton(QPushButton): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) enabled = self.isEnabled() + idle_color = PALETTE["accent_pressed"] if self.isDown() else PALETTE["accent"] color = { - "success": "#287B65", - "error": "#BE4B58", - }.get(self._state, "#4F63D9" if enabled else "#8E8F90") + "success": PALETTE["success"], + "error": PALETTE["danger"], + "loading": PALETTE["accent"], + }.get(self._state, idle_color if enabled else PALETTE["disabled_surface"]) painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(QColor(color)) painter.drawRoundedRect(QRectF(self.rect()).adjusted(1, 1, -1, -1), 10, 10) + if self.hasFocus(): + painter.setPen(QPen(QColor(PALETTE["focus"]), 1)) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRoundedRect(QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5), 10, 10) label = { "loading": "正在保存", "success": "保存成功", @@ -1220,7 +1232,9 @@ class SaveStateButton(QPushButton): else: painter.drawLine(x + 3, center_y - 5, x + 12, center_y + 5) painter.drawLine(x + 12, center_y - 5, x + 3, center_y + 5) - painter.setPen(QColor("#FFFFFF")) + painter.setPen(QColor( + PALETTE["disabled"] if not enabled and self._state == "idle" else PALETTE["surface"] + )) painter.drawText( QRect(x + icon_width, 0, metrics.horizontalAdvance(label), self.height()), Qt.AlignmentFlag.AlignCenter, @@ -1815,10 +1829,10 @@ class MessageStrip(QFrame): self.glyph = QLabel("i") self.glyph.setFixedWidth(18) self.glyph.setAlignment(Qt.AlignmentFlag.AlignCenter) - self.glyph.setStyleSheet("font-weight:700; color:#4F63D9;") + self.glyph.setStyleSheet(clinical_stylesheet("font-weight:700; color:$ds_accent;")) self.label = QLabel() self.label.setWordWrap(True) - self.label.setStyleSheet("color:#1A1C1F; font-size:13px;") + self.label.setStyleSheet(clinical_stylesheet("color:$ds_text; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(self.label, 1) self.action_button = QPushButton() @@ -1894,7 +1908,7 @@ class LoadingOverlay(QFrame): layout.setSpacing(8) self.glyph = _LoadingSpinner(self) label = QLabel(text) - label.setStyleSheet("color:#606163; font-size:13px;") + label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) layout.addWidget(self.glyph) layout.addWidget(label) self.hide() @@ -1985,15 +1999,15 @@ class RecordTable(QTableWidget): Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter ) if column_index in danger_columns: - item.setForeground(QColor("#BE4B58")) + item.setForeground(QColor(PALETTE["danger"])) kind = semantic.get(column_index) if kind: palette = { - "success": ("#287B65", "#EAF9F3"), - "warning": ("#A9691D", "#FFF5E6"), - "danger": ("#BE4B58", "#FFF1F3"), - "info": ("#4F63D9", "#EEF1FA"), - "neutral": ("#6A6B6D", "#F7F7F7"), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) @@ -2033,20 +2047,20 @@ class BloodTrendChart(QWidget): plot = self.rect().adjusted(48, 24, -22, -38) values = [value for value in (*self._fasting, *self._postprandial) if value is not None] if not values or plot.width() <= 0 or plot.height() <= 0: - painter.setPen(QColor("#606163")) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, "当前时间范围暂无血糖数据") painter.end() return upper = max(12.0, max(values) * 1.15) - painter.setPen(QPen(QColor("#EDEDEE"), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) for step in range(5): y = plot.bottom() - round(plot.height() * step / 4) painter.drawLine(plot.left(), y, plot.right(), y) - painter.setPen(QColor("#606163")) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( 4, y - 8, 40, 16, Qt.AlignmentFlag.AlignRight, f"{upper * step / 4:.0f}" ) - painter.setPen(QPen(QColor("#EDEDEE"), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) count = max(1, len(self._dates) - 1) def point(index: int, value: float) -> QPointF: @@ -2076,7 +2090,7 @@ class BloodTrendChart(QWidget): painter.setPen(QColor("#A9691D")) painter.drawText(plot.left() + 100, 4, 110, 18, Qt.AlignmentFlag.AlignLeft, "● 餐后血糖") if self._dates: - painter.setPen(QColor("#606163")) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText( plot.left(), plot.bottom() + 8, @@ -2279,7 +2293,7 @@ class DailyRecordPanel(QFrame): self.todo_table.setMinimumHeight(180) todo_layout.addWidget(self.todo_table) self.todo_summary = QLabel("共 0 条") - self.todo_summary.setStyleSheet("color:#606163; font-size:13px;") + self.todo_summary.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:13px;")) todo_layout.addWidget(self.todo_summary, 0, Qt.AlignmentFlag.AlignRight) root.addWidget(todo_card) self.clear() @@ -2437,8 +2451,8 @@ class DailyRecordPanel(QFrame): for row_index, (metric, label) in enumerate(self.METRICS): label_item = QTableWidgetItem(label) label_item.setFont(label_font) - label_item.setForeground(QColor("#606163")) - label_item.setBackground(QColor("#F7F7F7")) + label_item.setForeground(QColor(PALETTE["muted"])) + label_item.setBackground(QColor(PALETTE["surface_alt"])) self.matrix.setItem(row_index, 0, label_item) for date_index, date in enumerate(dates, 1): b = blood.get(date) @@ -2491,11 +2505,11 @@ class DailyRecordPanel(QFrame): item = QTableWidgetItem(value) item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) if high: - item.setForeground(QColor("#BE4B58")) - item.setBackground(QColor("#FFF1F3")) + item.setForeground(QColor(PALETTE["danger"])) + item.setBackground(QColor(PALETTE["danger_soft"])) elif value.endswith("· 自录"): - item.setForeground(QColor("#1A1C1F")) - item.setBackground(QColor("#F7F7F7")) + item.setForeground(QColor(PALETTE["text"])) + item.setBackground(QColor(PALETTE["surface_alt"])) edit_kind = "" edit_source: Any = None if metric in {"fasting", "postprandial", "other", "bp", "western", "insulin"}: @@ -3022,7 +3036,7 @@ class ChatPanel(QWidget): toolbar_layout.setContentsMargins(0, 0, 0, 0) toolbar_layout.setSpacing(8) archive = QLabel("仅展示服务端已归档消息(only_archived=1)") - archive.setStyleSheet("color:#606163;font-size:12px;") + archive.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) toolbar_layout.addWidget(archive) toolbar_layout.addStretch(1) self.sync_button = QPushButton("同步最新(后台异步)") @@ -3298,7 +3312,7 @@ class CaseGrid(QFrame): if group_index: divider = QFrame() divider.setFrameShape(QFrame.Shape.HLine) - divider.setStyleSheet("border:0; border-top:1px dashed #E4E4E5;") + divider.setStyleSheet(clinical_stylesheet("border:0; border-top:1px solid $ds_line;")) self.root.addWidget(divider) group_title = QLabel(f"● {group_name}") group_title.setProperty("diagnosisCaseGroup", True) @@ -3456,11 +3470,11 @@ def readonly_card(title: str, object_name: str, body: QWidget) -> QFrame: def set_tag_item(item: QTableWidgetItem, kind: str) -> None: palette = { - "success": ("#287B65", "#EAF9F3"), - "warning": ("#A9691D", "#FFF5E6"), - "danger": ("#BE4B58", "#FFF1F3"), - "info": ("#4F63D9", "#EEF1FA"), - "neutral": ("#6A6B6D", "#F7F7F7"), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "info": (PALETTE["accent"], PALETTE["accent_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } foreground, background = palette.get(kind, palette["neutral"]) item.setForeground(QColor(foreground)) diff --git a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py index a2ecb96be..9a420b56d 100644 --- a/app/src/doctor_workstation/ui/diagnosis_index_widgets.py +++ b/app/src/doctor_workstation/ui/diagnosis_index_widgets.py @@ -67,21 +67,22 @@ from ..core.appointment_modes import ( can_appointment_video, ) from . import icons +from .design_system import PALETTE, clinical_stylesheet from .reception_style import TECH_BLUE, body_family, heading_family from .widgets import display_text, first_value, gender_text, get_value -PRIMARY = QColor("#4F63D9") -TEXT = QColor("#1A1C1F") -SECONDARY = QColor("#606163") -PLACEHOLDER = QColor("#8E8F90") +PRIMARY = QColor(PALETTE["accent"]) +TEXT = QColor(PALETTE["text"]) +SECONDARY = QColor(PALETTE["muted"]) +PLACEHOLDER = QColor(PALETTE["disabled"]) _INVALID_INDEX = QModelIndex() # The last two columns form the compact frozen pane. Video status and ending # time occupy separate lines; actions keep two inline links plus 更多, with # the remaining actions in its menu so clinical columns retain more space. _TABLE_COLUMN_WIDTHS = (48, 70, 60, 100, 175, 88, 120, 100, 72, 110, 96, 160) _BLUE_COLUMN_WIDTHS = (48, 70, 82, 102, 244, 90, 84, 90, 88, 122, 92, 158) -_BLUE_WARNING = QColor("#A9691D") -_BLUE_DANGER = QColor("#BE4B58") +_BLUE_WARNING = QColor(PALETTE["warning"]) +_BLUE_DANGER = QColor(PALETTE["danger"]) def _blue_font(pixels: int = 13, *, medium: bool = False) -> QFont: @@ -248,14 +249,14 @@ class _DiagnosisActionMenu(QMenu): return painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - painter.fillRect(rect, QColor("#FFFFFF")) + painter.fillRect(rect, QColor(PALETTE["surface"])) item_rect = rect painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#F7F7F7") if self.activeAction() is action else QColor("#FFFFFF")) + painter.setBrush(QColor(PALETTE["surface_alt"]) if self.activeAction() is action else QColor(PALETTE["surface"])) painter.drawRoundedRect(item_rect, 3, 3) icon_rect = QRect(item_rect.left() + 8, item_rect.center().y() - 9, 18, 18) action.icon().paint(painter, icon_rect) - painter.setPen(QColor("#BE4B58" if action.isEnabled() else "#8E8F90")) + painter.setPen(QColor(PALETTE["danger"] if action.isEnabled() else PALETTE["disabled"])) painter.drawText( item_rect.adjusted(34, 0, -10, 0), Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft, @@ -823,6 +824,8 @@ class DiagnosisTableModel(QAbstractTableModel): default="", ) return f"最近渠道:{channel}" if channel else "" + if column == 6: + return DiagnosisTableModel._display(row, column) if column == 7: return display_text(first_value(row, "assistant_name"), "") if column == 9: @@ -849,7 +852,7 @@ class DiagnosisHeader(QHeaderView): def paintSection(self, painter: QPainter, rect: QRect, logical_index: int) -> None: # noqa: N802 if self.tech_blue: painter.save() - painter.fillRect(rect, QColor("#F5F8FD")) + painter.fillRect(rect, QColor(PALETTE["surface_alt"])) painter.setPen(QPen(QColor(TECH_BLUE["line"]), 1)) painter.drawLine(rect.bottomLeft(), rect.bottomRight()) painter.setFont(_blue_font()) @@ -870,7 +873,7 @@ class DiagnosisHeader(QHeaderView): painter.save() painter.setPen(Qt.PenStyle.NoPen) primary = QColor(TECH_BLUE["accent"]) if self.tech_blue else PRIMARY - secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor("#606163") + secondary = QColor(TECH_BLUE["muted"]) if self.tech_blue else QColor(PALETTE["muted"]) painter.setBrush(primary if direction == "asc" else secondary) painter.drawPolygon( QPolygon( @@ -953,7 +956,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate): painter, option.rect, "已确认" if _confirmed(record) else "未确认", - QColor("#287B65") if _confirmed(record) else QColor("#A9691D"), + QColor(PALETTE["success"]) if _confirmed(record) else QColor(PALETTE["warning"]), ) elif index.column() == 6: self._paint_followup(painter, option.rect, record) @@ -1023,16 +1026,16 @@ class DiagnosisItemDelegate(QStyledItemDelegate): ) -> None: hovered = model.hover_row == row base = ( - QColor("#EEF1FA") + QColor(PALETTE["accent_soft"]) if selected - else QColor("#F7F7F7" if hovered else "#F7F7F7" if row % 2 else "#FFFFFF") + else QColor(PALETTE["surface_alt"] if hovered or row % 2 else PALETTE["surface"]) ) special = not _confirmed(record) or not _has_appointment(record) painter.fillRect(rect, base) if special and column == 0: - stripe = QColor("#A9691D") if not _confirmed(record) else QColor("#4F63D9") + stripe = QColor(PALETTE["warning"]) if not _confirmed(record) else QColor(PALETTE["accent"]) painter.fillRect(QRect(rect.left(), rect.top(), 3, rect.height()), stripe) - painter.setPen(QPen(QColor("#EDEDEE"), 1)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) painter.drawLine(QLine(rect.bottomLeft(), rect.bottomRight())) @staticmethod @@ -1070,8 +1073,8 @@ class DiagnosisItemDelegate(QStyledItemDelegate): painter, QRect(left, content.center().y() - 10, 31, 20), "NEW", - QColor("#BE4B58"), - QColor("#FFFFFF"), + QColor(PALETTE["danger"]), + QColor(PALETTE["surface"]), 10, ) @@ -1081,17 +1084,17 @@ class DiagnosisItemDelegate(QStyledItemDelegate): self._draw_text(painter, content, "未挂号", PLACEHOLDER, 13) return rows = _appointments(record) - painter.setPen(QPen(QColor("#EDEDEE"), 1)) - painter.setBrush(QColor("#FFFFFF")) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.setBrush(QColor(PALETTE["surface"])) painter.drawRoundedRect(content, 6, 6) y = content.top() + 4 for position, appointment in enumerate(rows or [{}]): status = _as_int(first_value(appointment, "status", "appointment_status"), -1) label, fg, bg = { - 1: ("已预约", QColor("#4F63D9"), QColor("#EEF1FA")), - 3: ("已完成", QColor("#287B65"), QColor("#E8F6F1")), - 4: ("已过号", QColor("#A9691D"), QColor("#FFF4D8")), - }.get(status, ("未知", SECONDARY, QColor("#F7F7F7"))) + 1: ("已预约", QColor(PALETTE["accent"]), QColor(PALETTE["accent_soft"])), + 3: ("已完成", QColor(PALETTE["success"]), QColor(PALETTE["success_soft"])), + 4: ("已过号", QColor(PALETTE["warning"]), QColor(PALETTE["warning_soft"])), + }.get(status, ("未知", SECONDARY, QColor(PALETTE["surface_alt"]))) self._draw_tag(painter, QRect(content.left() + 6, y, 46, 20), label, bg, fg, 12) doctor = display_text(first_value(appointment, "doctor_name"), "-") time_text = display_text(first_value(appointment, "time_text", "appointment_time"), "-") @@ -1106,12 +1109,12 @@ class DiagnosisItemDelegate(QStyledItemDelegate): painter, QRect(content.left() + 6, y + 19, max(20, content.width() - 12), 17), time_text, - QColor("#A9691D") if status == 4 else SECONDARY, + QColor(PALETTE["warning"]) if status == 4 else SECONDARY, 13, ) y += 42 if position < len(rows) - 1: - painter.setPen(QPen(QColor("#EDEDEE"), 1, Qt.PenStyle.DashLine)) + painter.setPen(QPen(QColor(PALETTE["line"]), 1, Qt.PenStyle.DashLine)) painter.drawLine(content.left() + 6, y - 2, content.right() - 6, y - 2) channel = first_value( record, @@ -1153,7 +1156,7 @@ class DiagnosisItemDelegate(QStyledItemDelegate): painter, QRect(content.left(), content.top() + 38, 72, 18), "处方已作废", - QColor("#F7F7F7"), + QColor(PALETTE["surface_alt"]), SECONDARY, 11, outlined=True, @@ -1166,11 +1169,11 @@ class DiagnosisItemDelegate(QStyledItemDelegate): else: days = _as_int(value) color = ( - QColor("#287B65") + QColor(PALETTE["success"]) if days <= 2 - else QColor("#A9691D") + else QColor(PALETTE["warning"]) if days <= 6 - else QColor("#BE4B58") + else QColor(PALETTE["danger"]) ) text, bold = str(days), days > 6 self._draw_text( @@ -1320,6 +1323,8 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate): painter, content, "已确认" if _confirmed(record) else "未确认", pixels=13, color="text" if _confirmed(record) else _BLUE_WARNING.name(), ) + elif column == 6: + self._followup(painter, content, display_text(index.data(), "—")) elif column == 8: prescribed = _as_bool(first_value(record, "has_prescription")) self._text(painter, content, "已开方" if prescribed else "未开方", @@ -1348,6 +1353,28 @@ class _TechBlueDiagnosisDelegate(DiagnosisItemDelegate): medium=column == 2) painter.restore() + @staticmethod + def _followup(painter: QPainter, rect: QRect, text: str) -> None: + """Break at the date/time boundary, never in the middle of a number. + + Keep the established row metrics. Long time ranges or doctor names + elide within their line; the model tooltip retains the complete text. + """ + painter.setFont(_blue_font(13)) + painter.setPen(QColor(TECH_BLUE["muted"])) + metrics = painter.fontMetrics() + lines = text.splitlines() + if lines and metrics.horizontalAdvance(lines[0]) > rect.width(): + lines[:1] = lines[0].split(maxsplit=1) + line_height = metrics.height() + top = rect.top() + max(0, (rect.height() - line_height * len(lines)) // 2) + for offset, line in enumerate(lines): + painter.drawText( + QRect(rect.left(), top + offset * line_height, rect.width(), line_height), + int(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextSingleLine), + metrics.elidedText(line, Qt.TextElideMode.ElideRight, rect.width()), + ) + def _appointments(self, painter: QPainter, rect: QRect, record: Any) -> None: content = rect.adjusted(8, 0, -8, 0) if not _has_appointment(record): @@ -1688,7 +1715,9 @@ class DiagnosisTableHost(QFrame): self.main.horizontalHeader().sectionResized.connect(self._columns_resized) self._fixed_render_signature: tuple[Any, ...] | None = None if tech_blue: - self.setStyleSheet(_TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family())) + self.setStyleSheet(clinical_stylesheet( + _TECH_BLUE_TABLE_QSS.replace("BODY_FAMILY", body_family()) + )) def set_rows(self, rows: Iterable[Any]) -> None: previous_id = DiagnosisTableModel.record_id(self.main.current_data()) @@ -1904,6 +1933,7 @@ class DiagnosisTableHost(QFrame): .replace("#8E8F90", TECH_BLUE["muted"]) + f'QMenu {{ font-family: "{body_family()}"; font-weight: 400; }}' ) + menu.setStyleSheet(clinical_stylesheet(menu.styleSheet())) for label, action, _semantic in demoted_actions: _add_menu_action( menu, @@ -2630,19 +2660,19 @@ DIAGNOSIS_INDEX_QSS += """ #DiagnosisIndex QFrame#DiagnosisFilterCard, #DiagnosisIndex QFrame#DiagnosisListCard { border: 1px solid #EDEDEE; - border-radius: 13px; + border-radius: $ds_radius_panel; } #DiagnosisIndex QLineEdit, #DiagnosisIndex QComboBox, #DiagnosisIndex QDateEdit, #DiagnosisIndex QSpinBox, #DiagnosisIndex QPushButton { - border-radius: 8px; + border-radius: $ds_radius_control; } -#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: 8px; } +#DiagnosisIndex QToolButton[diagnosisChip="true"] { border-radius: $ds_radius_small; } #DiagnosisIndex QFrame#DiagnosisListToolbar { - border-top-left-radius: 13px; - border-top-right-radius: 13px; + border-top-left-radius: $ds_radius_panel; + border-top-right-radius: $ds_radius_panel; } #DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="primary"], #DiagnosisIndex QToolButton[diagnosisChip="true"]:checked[semantic="info"], @@ -2650,7 +2680,27 @@ DIAGNOSIS_INDEX_QSS += """ #DiagnosisIndex QPushButton[variant="success"] { color: #FFFFFF; } +#DiagnosisIndex QLineEdit:focus, +#DiagnosisIndex QComboBox:focus, +#DiagnosisIndex QDateEdit:focus, +#DiagnosisIndex QSpinBox:focus, +#DiagnosisIndex QPushButton:focus { + border-color: $ds_focus; +} +#DiagnosisIndex QPushButton[variant="primary"]:pressed { + color: $ds_surface; + background-color: $ds_accent_pressed; + border-color: $ds_accent_pressed; +} +#DiagnosisIndex QPushButton:disabled, +#DiagnosisIndex QPushButton[variant="primary"]:disabled, +#DiagnosisIndex QPushButton[variant="success"]:disabled { + color: $ds_disabled; + background-color: $ds_disabled_surface; + border-color: $ds_line; +} """ +DIAGNOSIS_INDEX_QSS = clinical_stylesheet(DIAGNOSIS_INDEX_QSS) __all__ = [ diff --git a/app/src/doctor_workstation/ui/diagnosis_media.py b/app/src/doctor_workstation/ui/diagnosis_media.py index d072dd38a..ebbe39ddc 100644 --- a/app/src/doctor_workstation/ui/diagnosis_media.py +++ b/app/src/doctor_workstation/ui/diagnosis_media.py @@ -32,6 +32,8 @@ from PySide6.QtWidgets import ( QWidget, ) +from .design_system import clinical_stylesheet + try: from PySide6.QtMultimedia import QAudioOutput, QMediaPlayer from PySide6.QtMultimediaWidgets import QVideoWidget @@ -223,7 +225,7 @@ class InlineRecordingPlayer(QWidget): self.setMinimumHeight(158) self.setMaximumHeight(180) self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) - self.setStyleSheet(_INLINE_PLAYER_QSS) + self.setStyleSheet(clinical_stylesheet(_INLINE_PLAYER_QSS)) root = QVBoxLayout(self) root.setContentsMargins(1, 1, 1, 5) @@ -466,11 +468,11 @@ class RecordingPlaybackCell(QWidget): separator = QFrame() separator.setObjectName("DiagnosisRecordingAlternateSeparator") separator.setFrameShape(QFrame.Shape.HLine) - separator.setStyleSheet("color:#EDEDEE;") + separator.setStyleSheet(clinical_stylesheet("color:$ds_line;")) layout.addWidget(separator) label = QLabel("备用地址") label.setObjectName("DiagnosisRecordingAlternateLabel") - label.setStyleSheet("color:#606163; font-size:12px;") + label.setStyleSheet(clinical_stylesheet("color:$ds_muted; font-size:12px;")) layout.addWidget(label) links = QHBoxLayout() links.setContentsMargins(0, 0, 0, 0) @@ -490,7 +492,7 @@ class RecordingPlaybackCell(QWidget): layout.addLayout(links) self.link_status = QLabel("") self.link_status.setObjectName("DiagnosisRecordingLinkStatus") - self.link_status.setStyleSheet("color:#BE4B58; font-size:11px;") + self.link_status.setStyleSheet(clinical_stylesheet("color:$ds_danger; font-size:11px;")) self.link_status.setWordWrap(True) self.link_status.hide() layout.addWidget(self.link_status) @@ -807,7 +809,7 @@ class ImagePreviewDialog(QDialog): self.setObjectName("DiagnosisImagePreview") self.setWindowTitle(title) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) - self.setStyleSheet(_IMAGE_PREVIEW_QSS) + self.setStyleSheet(clinical_stylesheet(_IMAGE_PREVIEW_QSS)) self.resize(880, 660) root = QVBoxLayout(self) diff --git a/app/src/doctor_workstation/ui/dialogs/ai_consult.py b/app/src/doctor_workstation/ui/dialogs/ai_consult.py index 9ad112149..3119a475d 100644 --- a/app/src/doctor_workstation/ui/dialogs/ai_consult.py +++ b/app/src/doctor_workstation/ui/dialogs/ai_consult.py @@ -62,6 +62,7 @@ from shiboken6 import isValid from .. import icons from ..chat_items import parse_chat_item as _parse_chat_item +from ..design_system import clinical_stylesheet from ..diagnosis_drawer import CaseGrid, _RemoteImageButton from ..diagnosis_index_widgets import FlowWidget from ..diagnosis_media import ( @@ -94,6 +95,9 @@ from ..widgets import ( show_toast, ) from .ai_consult_charts import GlucoseChartData +from .ai_consult_drug_names import TCM as DRUG_TCM +from .ai_consult_drug_names import WESTERN as DRUG_WESTERN +from .ai_consult_drug_names import summarize_drugs from .ai_consult_metric_state import ( ABNORMAL_COLOR, NORMAL_COLOR, @@ -101,7 +105,6 @@ from .ai_consult_metric_state import ( combined_metric_state, risk_color, ) -from .ai_consult_drug_names import TCM as DRUG_TCM, WESTERN as DRUG_WESTERN, summarize_drugs from .ai_consult_metric_text import MetricTextState, metric_text_context, metric_text_html from .ai_consult_report_visuals import ( ReportVisual, @@ -114,10 +117,10 @@ from .prescription_ai import ( diagnosis_ai_task, ) -AI_CONSULT_QSS = """ +AI_CONSULT_QSS = clinical_stylesheet(""" QDialog#AiConsultDialog { - color: #1A1C1F; - background-color: #F7F7F7; font-size: 14px; + color: $ds_text; + background-color: $ds_canvas; font-size: 14px; } QDialog#AiConsultDialog QScrollArea, QDialog#AiConsultDialog QScrollArea > QWidget, @@ -149,7 +152,7 @@ QDialog#AiConsultDialog QScrollBar::sub-page:vertical { background-color: transparent; } QDialog#AiConsultDialog QFrame#AiConsultShell { - background-color: #F7F7F7; + background-color: $ds_canvas; border: 0; } QDialog#AiConsultDialog QLabel#AiConsultCrumb { @@ -171,7 +174,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultBack { color: #1A1C1F; background-color: #F0F0F0; border: 0; - border-radius: 8px; + border-radius: $ds_radius_control; font-weight: 500; } QDialog#AiConsultDialog QPushButton#AiConsultBack:hover { background-color: #EEF1FA; } @@ -183,7 +186,7 @@ QDialog#AiConsultDialog QFrame#AiConsultHero { QDialog#AiConsultDialog QLabel#AiConsultAvatar { color: #FFFFFF; background-color: #4F63D9; - border-radius: 22px; + border-radius: $ds_radius_control; font-size: 16px; font-weight: 600; } @@ -201,7 +204,7 @@ QDialog#AiConsultDialog QLabel#AiConsultMeta { QDialog#AiConsultDialog QLabel#AiConsultChip { color: #6A6B6D; background-color: #F7F7F7; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 4px 8px; font-size: 13px; } @@ -240,7 +243,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultChatFilter { color: #4F63D9; background-color: #FFFFFF; border: 1px solid #E1E5F4; - border-radius: 8px; + border-radius: $ds_radius_control; font-size: 13px; } QDialog#AiConsultDialog QPushButton#AiConsultChatFilter:hover { @@ -275,7 +278,7 @@ QDialog#AiConsultDialog QLabel#AiConsultRole { max-width: 30px; min-height: 30px; max-height: 30px; - border-radius: 15px; + border-radius: $ds_radius_small; color: #FFFFFF; font-size: 13px; font-weight: 500; @@ -331,7 +334,7 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalMeta { QDialog#AiConsultDialog QLabel#AiConsultClinicalBadge { color: #4F63D9; background-color: #EEF1FA; - border-radius: 7px; + border-radius: $ds_radius_small; padding: 4px 8px; font-size: 13px; font-weight: 500; @@ -346,10 +349,10 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalSectionTitle { color: #1A1C1F; background-color: transparent; font-size: 14px; - font-weight: 500; + font-weight: 600; } QDialog#AiConsultDialog QLabel#AiConsultClinicalSummaryBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; font-weight: 400; @@ -411,7 +414,7 @@ QDialog#AiConsultDialog QLabel#AiConsultHypothesisTag { QDialog#AiConsultDialog QLabel#AiConsultClinicalBody, QDialog#AiConsultDialog QLabel#AiConsultWorkflowBody, QDialog#AiConsultDialog QLabel#AiConsultRiskBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; font-weight: 400; @@ -456,23 +459,23 @@ QDialog#AiConsultDialog QLabel#AiConsultRiskTitle { font-weight: 600; } QDialog#AiConsultDialog QLabel#AiConsultRiskBody { - color: #1A1C1F; font-size: 14px; + color: $ds_text; font-size: 14px; } QDialog#AiConsultDialog QLabel#AiConsultRiskTitle { color: #BE4B58; } QDialog#AiConsultDialog QLabel#AiConsultRiskBody { - color: #1A1C1F; font-size: 14px; + color: $ds_text; font-size: 14px; } /* 结构化报告:正文按阅读节奏排版,不再每句话套一个方框。 */ QDialog#AiConsultDialog QFrame#AiConsultReportIntro { - background-color: #F7F7F7; + background-color: $ds_accent_soft; border: 1px solid #EDEDEE; border-left: 3px solid #4F63D9; - border-radius: 9px; + border-radius: $ds_radius_control; } QDialog#AiConsultDialog QLabel#AiConsultReportIntroBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; font-weight: 400; @@ -497,7 +500,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportSectionTitle { color: #1A1C1F; background-color: transparent; font-size: 15px; - font-weight: 500; + font-weight: 600; } QDialog#AiConsultDialog QFrame#AiConsultReportRule { background-color: #EDEDEE; @@ -518,7 +521,7 @@ QDialog#AiConsultDialog QLabel#AiConsultReportBullet { font-weight: 500; } QDialog#AiConsultDialog QLabel#AiConsultReportBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; font-weight: 400; @@ -541,18 +544,18 @@ QDialog#AiConsultDialog QLabel#AiConsultClinicalDisclaimer { font-weight: 400; } QDialog#AiConsultDialog QFrame#AiConsultReportProvenance { - background-color: #F7F8FC; - border: 1px solid #E4E8F2; - border-radius: 9px; + background-color: $ds_surface_alt; + border: 1px solid $ds_line; + border-radius: $ds_radius_control; } QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceTitle { - color: #27336B; + color: $ds_heading; background-color: transparent; font-size: 12px; font-weight: 600; } QDialog#AiConsultDialog QLabel#AiConsultReportProvenanceLine { - color: #555B68; + color: $ds_muted; background-color: transparent; font-size: 12px; } @@ -647,7 +650,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSection { font-weight: 500; } QDialog#AiConsultDialog QLabel#AiConsultBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; line-height: 1.6; @@ -681,7 +684,7 @@ QDialog#AiConsultDialog QLabel#AiConsultInsightPlaceholder { QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] { color: #BE4B58; background-color: #FFF1F3; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; font-weight: 600; @@ -689,7 +692,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="high"] { QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] { color: #A9691D; background-color: #FFF5E6; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; font-weight: 500; @@ -697,7 +700,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="medium"] { QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] { color: #287B65; background-color: #EAF9F3; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; font-weight: 500; @@ -705,7 +708,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="low"] { QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] { color: #BE4B58; background-color: #FFF1F3; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; font-weight: 600; @@ -713,7 +716,7 @@ QDialog#AiConsultDialog QLabel#AiConsultTag[level="warn"] { QDialog#AiConsultDialog QLabel#AiConsultTag[level="unknown"] { color: #6A6B6D; background-color: #F0F0F0; - border-radius: 8px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; } @@ -739,7 +742,7 @@ QDialog#AiConsultDialog QLineEdit#AiConsultInput { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 12px; + border-radius: $ds_radius_control; font-size: 14px; } QDialog#AiConsultDialog QLineEdit#AiConsultInput:focus { @@ -763,7 +766,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultIconButton { max-height: 36px; padding: 0; border: 0; - border-radius: 18px; + border-radius: $ds_radius_control; background-color: #F7F7F7; } QDialog#AiConsultDialog QPushButton#AiConsultIconButton:hover { background-color: #EEF1FA; } @@ -774,7 +777,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSend { max-height: 40px; padding: 0; border: 0; - border-radius: 20px; + border-radius: $ds_radius_control; background-color: #4F63D9; } QDialog#AiConsultDialog QPushButton#AiConsultSend:hover { background-color: #4156C4; } @@ -783,7 +786,7 @@ QDialog#AiConsultDialog QLabel#AiConsultSideTitle { color: #1A1C1F; background-color: transparent; font-size: 16px; - font-weight: 500; + font-weight: 600; } QDialog#AiConsultDialog QLabel#AiConsultSideSubtitle { color: #6A6B6D; @@ -871,7 +874,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultSideClose { max-height: 28px; padding: 0; border: 0; - border-radius: 8px; + border-radius: $ds_radius_control; color: #606163; background-color: transparent; font-size: 16px; @@ -917,10 +920,10 @@ QDialog#AiConsultDialog QLabel#AiConsultRecordTitle { color: #1A1C1F; background-color: transparent; font-size: 13px; - font-weight: 500; + font-weight: 600; } QDialog#AiConsultDialog QLabel#AiConsultRecordBody { - color: #1A1C1F; + color: $ds_text; background-color: transparent; font-size: 14px; } @@ -951,7 +954,7 @@ QDialog#AiConsultDialog QPushButton#AiConsultMediaOpen { color: #4F63D9; background-color: #EEF1FA; border: 0; - border-radius: 8px; + border-radius: $ds_radius_control; font-weight: 500; } QDialog#AiConsultDialog QPushButton#AiConsultRecordRetry:hover, @@ -1000,10 +1003,11 @@ QDialog#AiConsultDialog QLabel#AiConsultDataLabel { font-size: 13px; } QDialog#AiConsultDialog QLabel#AiConsultDataValue { - color: #1A1C1F; + color: $ds_text; font-size: 13px; } -""" +QDialog#AiConsultDialog QPushButton:focus { border-color: $ds_focus; } +""") QUICK_PROMPTS: tuple[tuple[str, str], ...] = ( ("总结当前病情", "请根据当前病历总结患者病情、证候与风险。"), @@ -1053,8 +1057,8 @@ _DOCTOR_DOCUMENT_CSS = ( # 模型回复几乎都是“分节标题 + 两层要点”的长文。早期样式里标题只比正文大 1px、 # 段落与列表项的间距也几乎相同,整段读起来就是一堵字墙。这里把层级、行距和分节 # 留白拉开:标题明显更大更重,顶层小节之间留出整行空白,嵌套要点单独收紧缩进。 -_AI_DOCUMENT_CSS = ( - "body { color:#1A1C1F; font-size:14px; line-height:200%; } " +_AI_DOCUMENT_CSS = clinical_stylesheet( + "body { color:$ds_text; font-size:14px; line-height:200%; } " "h1,h2 { color:#1A1C1F; font-size:17px; margin:22px 0 10px; line-height:160%; } " "h3,h4 { color:#1A1C1F; font-size:15px; margin:18px 0 8px; line-height:160%; } " "p { margin:10px 0; line-height:200%; } " @@ -2219,15 +2223,12 @@ def _escape_html(value: str) -> str: ) -class _FlowRow(QWidget): +class _FlowRow(FlowWidget): + """Keep patient metadata readable when the details pane is narrow.""" + def __init__(self, parent: QWidget | None = None) -> None: - super().__init__(parent) - self._layout = QHBoxLayout(self) - self._layout.setContentsMargins(0, 0, 0, 0) - self._layout.setSpacing(8) - self._layout.setAlignment( - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter - ) + super().__init__(parent, horizontal_spacing=8, vertical_spacing=6) + self._layout = self.flow def add(self, widget: QWidget) -> None: self._layout.addWidget(widget) @@ -2810,7 +2811,7 @@ class _DrugSummaryStrip(QFrame): layout.addLayout(row) @staticmethod - def for_text(text: str, parent: QWidget | None = None) -> "_DrugSummaryStrip | None": + def for_text(text: str, parent: QWidget | None = None) -> _DrugSummaryStrip | None: summary = summarize_drugs(text) return _DrugSummaryStrip(summary, parent) if any(summary.values()) else None @@ -3454,11 +3455,11 @@ class _ChatBubble(QWidget): avatar.setAlignment(Qt.AlignmentFlag.AlignCenter) _style_surface(avatar) if role == "doctor": - avatar.setStyleSheet("background-color:#4F63D9; color:#FFFFFF; border-radius:15px;") + avatar.setStyleSheet(clinical_stylesheet("background-color:#4F63D9; color:#FFFFFF; border-radius:6px;")) elif role == "ai": - avatar.setStyleSheet("background-color:#EEF1FA; color:#4F63D9; border-radius:15px;") + avatar.setStyleSheet(clinical_stylesheet("background-color:#EEF1FA; color:#4F63D9; border-radius:6px;")) else: - avatar.setStyleSheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:15px;") + avatar.setStyleSheet(clinical_stylesheet("background-color:#6A6B6D; color:#FFFFFF; border-radius:6px;")) bubble = QFrame() _style_surface(bubble) if role == "doctor": @@ -3629,10 +3630,10 @@ class _ChatBubble(QWidget): toggle.setCursor(Qt.CursorShape.PointingHandCursor) toggle.setAccessibleName("展开资料提交回执") toggle.setStyleSheet( - "QPushButton {color:#65718A;font-size:12px;text-align:left;" + clinical_stylesheet("QPushButton {color:$ds_muted;font-size:12px;text-align:left;" "background:transparent;border:0;padding:4px 0;}" "QPushButton:hover {color:#4F63D9;}" - "QPushButton:focus {border-bottom:1px solid #4F63D9;}" + "QPushButton:focus {border-bottom:1px solid #4F63D9;}") ) layout.addWidget(toggle) label = QLabel(receipt) @@ -3643,7 +3644,7 @@ class _ChatBubble(QWidget): Qt.TextInteractionFlag.TextSelectableByMouse | Qt.TextInteractionFlag.TextSelectableByKeyboard ) - label.setStyleSheet("color:#65718A;font-size:12px;") + label.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) label.hide() layout.addWidget(label) self._inner.insertWidget(0, receipt) @@ -3688,7 +3689,7 @@ class _ChatBubble(QWidget): label.setTextFormat(Qt.TextFormat.PlainText) label.setWordWrap(True) label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) - label.setStyleSheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;") + label.setStyleSheet(clinical_stylesheet("color:#BE4B58;background:#FEF3F2;border-radius:6px;padding:8px;")) self._inner.insertWidget(self._inner.indexOf(self.body), label) self._stream_failure_label = label label.setText(f"本次回复未完成\n{text}") @@ -4949,8 +4950,9 @@ class AiConsultDialog(QDialog): button.setObjectName("AiConsultChipButton") button.setCursor(Qt.CursorShape.PointingHandCursor) button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + task_key = QUICK_PROMPT_TASKS.get(label, "") button.clicked.connect( - lambda _checked=False, text=prompt, task=QUICK_PROMPT_TASKS.get(label, ""): + lambda _checked=False, text=prompt, task=task_key: self._ask(text, replace_active=True, task=task) ) chips.addWidget(button, 1) diff --git a/app/src/doctor_workstation/ui/dialogs/app_update.py b/app/src/doctor_workstation/ui/dialogs/app_update.py index 485032d64..4d2fd6a67 100644 --- a/app/src/doctor_workstation/ui/dialogs/app_update.py +++ b/app/src/doctor_workstation/ui/dialogs/app_update.py @@ -43,6 +43,7 @@ from doctor_workstation.services.app_update import ( validate_installer_download_policy, validate_windows_installer, ) +from doctor_workstation.ui.design_system import clinical_stylesheet from doctor_workstation.ui.widgets import friendly_error, show_toast LOGGER = logging.getLogger(__name__) @@ -129,11 +130,11 @@ class AppUpdateDialog(QDialog): self.badge = QLabel("必须更新后才能继续使用" if offer.force else "发现新版本") self.badge.setObjectName("UpdateBadge") - self.badge.setStyleSheet( + self.badge.setStyleSheet(clinical_stylesheet( "color:#A9691D;background:#FFF5E6;border-radius:8px;padding:4px 10px;font-weight:600;" if offer.force else "color:#4F63D9;background:#EEF1FA;border-radius:8px;padding:4px 10px;font-weight:600;" - ) + )) root.addWidget(self.badge, 0, Qt.AlignmentFlag.AlignLeft) self.headline = QLabel(title or "医生工作站有新版本") @@ -146,7 +147,7 @@ class AppUpdateDialog(QDialog): latest = offer.latest_version or "新版本" self.version_label = QLabel(f"当前版本 {current} → 最新版本 {latest}") self.version_label.setObjectName("UpdateVersionLabel") - self.version_label.setStyleSheet("color:#606163;") + self.version_label.setStyleSheet(clinical_stylesheet("color:$ds_muted;")) root.addWidget(self.version_label) self.notes = QTextEdit() @@ -160,7 +161,7 @@ class AppUpdateDialog(QDialog): self.status_label = QLabel("") self.status_label.setObjectName("UpdateStatus") self.status_label.setWordWrap(True) - self.status_label.setStyleSheet("color:#1A1C1F;") + self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;")) self.status_label.hide() root.addWidget(self.status_label) @@ -175,7 +176,7 @@ class AppUpdateDialog(QDialog): self.progress_text = QLabel("") self.progress_text.setObjectName("UpdateProgressText") - self.progress_text.setStyleSheet("color:#606163;font-size:12px;") + self.progress_text.setStyleSheet(clinical_stylesheet("color:$ds_muted;font-size:12px;")) self.progress_text.hide() root.addWidget(self.progress_text) @@ -225,7 +226,7 @@ class AppUpdateDialog(QDialog): def show_download_progress(self, received: int, total: int) -> None: self.progress.show() self.progress_text.show() - self.status_label.setStyleSheet("color:#1A1C1F;") + self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;")) self.status_label.setText("正在下载安装包…") self.status_label.show() if total > 0: @@ -237,7 +238,7 @@ class AppUpdateDialog(QDialog): self.progress_text.setText(_format_bytes(received)) def show_status(self, message: str, *, determinate: bool = False) -> None: - self.status_label.setStyleSheet("color:#1A1C1F;") + self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_heading;")) self.status_label.setText(message) self.status_label.show() self.progress.show() @@ -251,7 +252,7 @@ class AppUpdateDialog(QDialog): def show_error(self, message: str) -> None: self._busy = False self.status_label.setText(message) - self.status_label.setStyleSheet("color:#BE4B58;") + self.status_label.setStyleSheet(clinical_stylesheet("color:$ds_danger;")) self.status_label.show() self.progress.hide() self.progress_text.hide() diff --git a/app/src/doctor_workstation/ui/dialogs/diagnosis.py b/app/src/doctor_workstation/ui/dialogs/diagnosis.py index d5e3f50b9..98b6413d6 100644 --- a/app/src/doctor_workstation/ui/dialogs/diagnosis.py +++ b/app/src/doctor_workstation/ui/dialogs/diagnosis.py @@ -48,6 +48,7 @@ from PySide6.QtWidgets import ( ) from ...core.appointment_modes import appointment_type_description, appointment_type_value +from ..design_system import clinical_stylesheet from ..diagnosis_drawer import ( DIAGNOSIS_QSS, CaseGrid, @@ -97,6 +98,7 @@ from .issued_prescription_ai import can_open_issued_ai, present_issued_prescript from .local_audio_queue import LocalAudioQueueDialog from .prescription_ai import can_open_diagnosis_ai_report, present_diagnosis_ai_report + class _UploadProgressRelay(QObject): """把后台线程中的分片上传进度转回界面线程(信号跨线程自动排队)。""" @@ -1541,16 +1543,16 @@ class DiagnosisDialog(QDialog): """上传本地回放时的进度条:按分片实时更新,医生能看到上传在进行、进行到哪。""" frame = QFrame() frame.setObjectName("DiagnosisVideoUploadProgress") - frame.setStyleSheet( + frame.setStyleSheet(clinical_stylesheet( "QFrame#DiagnosisVideoUploadProgress { background-color: #EEF1FA;" - " border: 1px solid #C9D1F3; border-radius: 8px; }" - "QFrame#DiagnosisVideoUploadProgress QLabel { color: #3347B8; background: transparent;" + " border: 1px solid $ds_line_strong; border-radius: $ds_radius_control; }" + "QFrame#DiagnosisVideoUploadProgress QLabel { color: $ds_accent_hover; background: transparent;" " font-size: 13px; font-weight: 500; }" "QFrame#DiagnosisVideoUploadProgress QProgressBar { background-color: #FFFFFF;" " border: 0; border-radius: 4px; min-height: 8px; max-height: 8px; }" "QFrame#DiagnosisVideoUploadProgress QProgressBar::chunk { background-color: #4F63D9;" " border-radius: 4px; }" - ) + )) row = QVBoxLayout(frame) row.setContentsMargins(12, 8, 12, 10) row.setSpacing(6) diff --git a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py index f003977b1..bbdb46f1e 100644 --- a/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py +++ b/app/src/doctor_workstation/ui/dialogs/issued_prescription_ai_theme.py @@ -21,6 +21,8 @@ from typing import Any from PySide6.QtGui import QFont +from ..design_system import PALETTE + DARK: dict[str, str] = { # ground and cards "canvas": "#080D18", @@ -62,23 +64,23 @@ DARK: dict[str, str] = { } LIGHT: dict[str, str] = { - "canvas": "#F1F5FC", - "canvas_soft": "#E7EEFA", - "surface": "#FFFFFF", - "surface_2": "#F5F8FE", - "raised": "#E8EFFA", - "line": "#D5E1F2", - "line_soft": "#E3EBF8", - "heading": "#0A182E", - "text": "#2A3C56", - "muted": "#54697F", - "faint": "#7A8DA3", - "selected_text": "#0A182E", - "accent": "#1A5FD0", - "accent_text": "#124DAE", - "accent_pressed": "#0E3F90", - "selection": "#E8EFFA", - "selection_line": "#AEC7EE", + "canvas": PALETTE["canvas"], + "canvas_soft": PALETTE["surface_alt"], + "surface": PALETTE["surface"], + "surface_2": PALETTE["surface_alt"], + "raised": PALETTE["sidebar"], + "line": PALETTE["line_strong"], + "line_soft": PALETTE["line"], + "heading": PALETTE["heading"], + "text": PALETTE["text"], + "muted": PALETTE["muted"], + "faint": PALETTE["disabled"], + "selected_text": PALETTE["heading"], + "accent": PALETTE["accent"], + "accent_text": PALETTE["accent_hover"], + "accent_pressed": PALETTE["accent_pressed"], + "selection": PALETTE["accent_soft"], + "selection_line": PALETTE["focus"], "qwen": "#0C89AC", "qwen_text": "#086C88", "qwen_dim": "#E2F5FA", diff --git a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py index 4af364d26..0f21c06ee 100644 --- a/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py +++ b/app/src/doctor_workstation/ui/dialogs/local_audio_queue.py @@ -29,6 +29,7 @@ from ...services.local_audio_queue import ( LocalAudioUploadManager, get_local_audio_upload_manager, ) +from ..design_system import clinical_stylesheet from ..widgets import run_async _STATUS_LABELS = { @@ -174,7 +175,7 @@ class LocalAudioQueueDialog(QDialog): self.setModal(True) self.setMinimumSize(760, 480) self.resize(1160, 620) - self.setStyleSheet(_LOCAL_AUDIO_QSS) + self.setStyleSheet(clinical_stylesheet(_LOCAL_AUDIO_QSS)) self._build_ui() self.poll_timer = QTimer(self) diff --git a/app/src/doctor_workstation/ui/dialogs/prescription.py b/app/src/doctor_workstation/ui/dialogs/prescription.py index 77b5fdad2..bd69d795a 100644 --- a/app/src/doctor_workstation/ui/dialogs/prescription.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription.py @@ -28,8 +28,8 @@ from PySide6.QtCore import ( QDate, QEvent, QIODevice, - QModelIndex, QMarginsF, + QModelIndex, QObject, QPoint, QRectF, @@ -98,6 +98,7 @@ from PySide6.QtWidgets import ( ) from .. import icons +from ..design_system import clinical_stylesheet from ..diagnosis_terms import shared_terms from ..infinite_list import InfiniteList from ..theme import main_window_target_rect @@ -116,9 +117,9 @@ from ..widgets import ( ) from .diagnosis import DiagnosisDialog as _StructuredDiagnosisDialog -PRESCRIPTION_DRAWER_QSS = r""" +PRESCRIPTION_DRAWER_QSS = clinical_stylesheet(r""" QFrame#PrescriptionDrawerSurface { - color: #1A1C1F; + color: $ds_text; background-color: #FFFFFF; border-left: 1px solid #EDEDEE; font-size: 14px; @@ -145,7 +146,7 @@ QLabel#PrescriptionLockTag { color: #BE4B58; background-color: #FEF0F0; border: 1px solid #FDE2E2; - border-radius: 4px; + border-radius: $ds_radius_small; padding: 2px 8px; font-size: 13px; } @@ -175,7 +176,7 @@ QLabel#PrescriptionDrawerMode { color: #4F63D9; background-color: #EEF1FA; border: 1px solid #EDEDEE; - border-radius: 5px; + border-radius: $ds_radius_small; padding: 4px 9px; font-size: 13px; font-weight: 500; @@ -189,7 +190,7 @@ QPushButton#PrescriptionDrawerClose { color: #606163; background-color: transparent; border: 0; - border-radius: 7px; + border-radius: $ds_radius_control; font-size: 22px; font-weight: 400; } @@ -208,12 +209,12 @@ QWidget#PrescriptionDrawerContent { QFrame#PrescriptionFormSection { background-color: #F7F7F7; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: $ds_radius_panel; } QLabel#PrescriptionSectionTitle { color: #1A1C1F; font-size: 15px; - font-weight: 500; + font-weight: 600; } QLabel#PrescriptionSectionHint { color: #6A6B6D; @@ -242,7 +243,7 @@ QLabel#PrescriptionUsageAux { QFrame#PrescriptionRpToolbar { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: $ds_radius_panel; } QFrame#PrescriptionRpMarker { background-color: #4F63D9; @@ -262,12 +263,12 @@ QLabel#PrescriptionRpLock { color: #BE4B58; background-color: #FEF3F2; border: 1px solid #FECDCA; - border-radius: 5px; + border-radius: $ds_radius_small; padding: 5px 8px; font-size: 13px; } QLabel#PrescriptionFormulaTag { - border-radius: 4px; + border-radius: $ds_radius_small; padding: 3px 8px; font-size: 13px; font-weight: 500; @@ -328,7 +329,7 @@ QFrame#PrescriptionDrawerSurface QDoubleSpinBox { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; padding: 0 11px; selection-background-color: #C9D1F3; selection-color: #1A1C1F; font-size: 14px; @@ -338,7 +339,7 @@ QFrame#PrescriptionDrawerSurface QComboBox { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; padding-left: 11px; padding-right: 28px; selection-background-color: #C9D1F3; @@ -379,7 +380,7 @@ QFrame#PrescriptionDatePicker { min-height: 32px; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; } QFrame#PrescriptionDatePicker:hover { border-color: #8B9AD9; @@ -446,7 +447,7 @@ QFrame#PrescriptionDrawerSurface QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; font-weight: 500; } QFrame#PrescriptionDrawerSurface QPushButton:hover { @@ -468,7 +469,7 @@ QFrame#PrescriptionDrawerSurface QPushButton#PrescriptionDrawerClose { color: #606163; background-color: transparent; border: 0; - border-radius: 7px; + border-radius: $ds_radius_control; font-size: 22px; font-weight: 400; } @@ -496,23 +497,23 @@ QFrame#PrescriptionDrawerSurface QPushButton[variant="primary"]:hover { border-color: #4156C4; } QFrame#PrescriptionDrawerSurface QPushButton[variant="success"] { - color: #FFFFFF; - background-color: #287B65; - border-color: #287B65; + color: $ds_accent; + background-color: $ds_accent_soft; + border-color: $ds_line; } QFrame#PrescriptionDrawerSurface QPushButton[variant="success"]:hover { - background-color: #287B65; - border-color: #287B65; + background-color: $ds_accent_soft; + border-color: $ds_focus; } QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"] { - color: #A9691D; + color: $ds_accent; background-color: #FFFFFF; - border-color: #A9691D; + border-color: $ds_accent; } QFrame#PrescriptionDrawerSurface QPushButton[variant="warning"]:hover { - color: #FFFFFF; - background-color: #A9691D; - border-color: #A9691D; + color: $ds_accent_hover; + background-color: $ds_accent_soft; + border-color: $ds_focus; } QFrame#PrescriptionDrawerSurface QPushButton[variant="secondary"] { color: #4F63D9; @@ -615,7 +616,8 @@ QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] { QFrame#PrescriptionDrawerSurface QFrame#MessageBanner[kind="danger"] QLabel { color: #BE4B58; } -""" +QFrame#PrescriptionDrawerSurface QPushButton:focus { border: 1px solid $ds_focus; } +""") _CHEVRON_PATH: Path | None = None @@ -647,7 +649,7 @@ def _prescription_drawer_qss() -> str: def _prescription_calendar_qss() -> str: - return """ + return clinical_stylesheet(""" QCalendarWidget { background-color: #FFFFFF; border: 1px solid #EDEDEE; @@ -672,13 +674,13 @@ QCalendarWidget QAbstractItemView:enabled { selection-color: #1A1C1F; outline: 0; } -""" +""") -PRESCRIPTION_DIALOG_QSS = """ +PRESCRIPTION_DIALOG_QSS = clinical_stylesheet(""" QDialog#PrescriptionDialogSurface { color: #1A1C1F; - background-color: #F7F7F7; + background-color: $ds_canvas; font-size: 14px; } QDialog#PrescriptionDialogSurface QLabel { @@ -740,7 +742,7 @@ QDialog#PrescriptionDialogSurface QTextBrowser { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; selection-background-color: #EEF1FA; selection-color: #1A1C1F; font-size: 14px; } @@ -768,7 +770,7 @@ QDialog#PrescriptionDialogSurface QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; font-weight: 500; } QDialog#PrescriptionDialogSurface QPushButton:hover { @@ -798,7 +800,7 @@ QDialog#PrescriptionDialogSurface QPushButton:disabled { QDialog#PrescriptionDialogSurface QTabWidget::pane { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 9px; + border-radius: $ds_radius_panel; top: -1px; } QDialog#PrescriptionDialogSurface QTabBar::tab { @@ -852,7 +854,8 @@ QDialog#PrescriptionDialogSurface QScrollBar::add-line:vertical, QDialog#PrescriptionDialogSurface QScrollBar::sub-line:vertical { height: 0; } -""" +QDialog#PrescriptionDialogSurface QPushButton:focus { border: 1px solid $ds_focus; } +""") def _apply_prescription_dialog_style(dialog: QDialog) -> None: @@ -1531,9 +1534,9 @@ class RemoteMedicineComboBox(QComboBox): popup = self._completer.popup() popup.setItemDelegate(_MedicineSuggestionDelegate(popup)) popup.setStyleSheet( - "QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;" + clinical_stylesheet("QListView { background-color: #FFFFFF; border: 1px solid #E4E7ED; border-radius: 6px;" " padding: 4px 0; font-size: 14px; outline: 0; }" - "QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }" + "QListView::item:selected, QListView::item:hover { background-color: #F5F7FA; }") ) self.lineEdit().setCompleter(self._completer) self.lineEdit().installEventFilter(self) @@ -5292,8 +5295,8 @@ class PrescriptionDetailDialog(QDialog): self.preview.setObjectName("PrescriptionPaperPreview") self.preview.setOpenExternalLinks(False) self.preview.setStyleSheet( - "QTextBrowser#PrescriptionPaperPreview {" - "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}" + clinical_stylesheet("QTextBrowser#PrescriptionPaperPreview {" + "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}") ) self.preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.preview.setDocument(self.document) @@ -5301,8 +5304,8 @@ class PrescriptionDetailDialog(QDialog): self.user_preview.setObjectName("PrescriptionUserPaperPreview") self.user_preview.setOpenExternalLinks(False) self.user_preview.setStyleSheet( - "QTextBrowser#PrescriptionUserPaperPreview {" - "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}" + clinical_stylesheet("QTextBrowser#PrescriptionUserPaperPreview {" + "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}") ) self.user_preview.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.user_preview.setDocument(self.user_document) @@ -5320,8 +5323,8 @@ class PrescriptionDetailDialog(QDialog): self.case_preview.setObjectName("CaseRecordPaperPreview") self.case_preview.setOpenExternalLinks(False) self.case_preview.setStyleSheet( - "QTextBrowser#CaseRecordPaperPreview {" - "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}" + clinical_stylesheet("QTextBrowser#CaseRecordPaperPreview {" + "background-color:#F7F7F7; border:1px solid #E4E4E5; padding:0;}") ) self.case_preview.setDocument(self.case_document) case_index = self.tabs.addTab(self.case_preview, "详细病历") diff --git a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py index 16201b000..db3d98638 100644 --- a/app/src/doctor_workstation/ui/dialogs/prescription_ai.py +++ b/app/src/doctor_workstation/ui/dialogs/prescription_ai.py @@ -26,6 +26,7 @@ from PySide6.QtWidgets import ( QWidget, ) +from ..design_system import clinical_stylesheet from ..report_provenance import report_provenance_lines from ..theme import apply_reading_rhythm from ..widgets import ( @@ -169,10 +170,10 @@ def diagnosis_ai_task(prompt: str) -> str: return "custom" -PRESCRIPTION_AI_QSS = """ +PRESCRIPTION_AI_QSS = clinical_stylesheet(""" QDialog#PrescriptionAiDialog { - color: #1A1C1F; - background-color: #F7F7F7; + color: $ds_text; + background-color: $ds_canvas; font-size: 13px; } @@ -182,7 +183,7 @@ QDialog#PrescriptionAiDialog QPushButton { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 7px; + border-radius: $ds_radius_control; font-weight: 500; } QDialog#PrescriptionAiDialog QPushButton:hover { @@ -224,7 +225,7 @@ QLabel#PrescriptionAiSubtitle { QFrame#PrescriptionAiSnapshot { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: $ds_radius_panel; } QLabel#PrescriptionAiSnapshotLabel { color: #1A1C1F; @@ -232,20 +233,20 @@ QLabel#PrescriptionAiSnapshotLabel { font-weight: 600; } QLabel#PrescriptionAiSnapshotBody { - color: #1A1C1F; - font-size: 13px; + color: $ds_text; + font-size: 14px; line-height: 1.65; } QFrame#PrescriptionAiSummary { - background-color: #F0F0F0; + background-color: $ds_accent_soft; border: 0; border-left: 3px solid #4F63D9; - border-radius: 0 9px 9px 0; + border-radius: $ds_radius_control; } QFrame#PrescriptionAiCaution { background-color: #FFF9EE; border: 1px solid #F3DFB5; - border-radius: 9px; + border-radius: $ds_radius_control; } QLabel#PrescriptionAiSectionTitle { color: #1A1C1F; @@ -253,17 +254,17 @@ QLabel#PrescriptionAiSectionTitle { font-weight: 600; } QLabel#PrescriptionAiBody { - color: #1A1C1F; - font-size: 13px; + color: $ds_text; + font-size: 14px; line-height: 1.75; } QTextBrowser#PrescriptionAiAnswer { - color: #1A1C1F; + color: $ds_text; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; - padding: 12px 14px; - selection-color: #1A1C1F; + border-radius: $ds_radius_panel; + padding: 16px 18px; + selection-color: $ds_text; selection-background-color: #EEF1FA; } QLabel#PrescriptionAiMuted { @@ -279,7 +280,7 @@ QFrame#PrescriptionAiMeta { QDialog#PrescriptionAiDialog QTabWidget::pane { background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 10px; + border-radius: $ds_radius_panel; top: -1px; } QDialog#PrescriptionAiDialog QTabBar::tab { @@ -309,7 +310,7 @@ QDialog#PrescriptionAiDialog QTextEdit { color: #1A1C1F; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 8px; + border-radius: $ds_radius_control; padding: 10px; selection-background-color: #EEF1FA; } @@ -330,10 +331,12 @@ QDialog#PrescriptionAiDialog QScrollBar::add-line:vertical, QDialog#PrescriptionAiDialog QScrollBar::sub-line:vertical { height: 0; } -""" +QDialog#PrescriptionAiDialog QPushButton:focus { border: 1px solid $ds_focus; } +QDialog#PrescriptionAiDialog QPushButton:disabled { color: $ds_disabled; background-color: $ds_disabled_surface; border-color: $ds_line; } +""") -_AI_ANSWER_DOCUMENT_CSS = ( - "body { color:#1A1C1F; font-size:14px; line-height:1.72; } " +_AI_ANSWER_DOCUMENT_CSS = clinical_stylesheet( + "body { color:$ds_text; font-size:14px; line-height:1.72; } " "h1 { color:#1A1C1F; font-size:20px; margin:14px 0 8px; line-height:1.4; } " "h2 { color:#1A1C1F; font-size:17px; margin:14px 0 7px; line-height:1.42; } " "h3,h4 { color:#1A1C1F; font-size:15px; margin:12px 0 6px; line-height:1.45; } " @@ -801,7 +804,7 @@ class PrescriptionAiReportDialog(QDialog): self.report_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.host = QWidget() self.host_layout = QVBoxLayout(self.host) - self.host_layout.setContentsMargins(4, 4, 12, 8) + self.host_layout.setContentsMargins(18, 14, 20, 16) self.host_layout.setSpacing(12) self.report_scroll.setWidget(self.host) self.tabs.widget(0).layout().addWidget(self.report_scroll) @@ -1455,7 +1458,7 @@ class PrescriptionAiReportDialog(QDialog): label.setTextFormat(Qt.TextFormat.PlainText) label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) label.setWordWrap(True) - label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;") + label.setStyleSheet(clinical_stylesheet("color: $ds_muted; font-size: 12px; padding: 10px 14px; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_control;")) self.host_layout.addWidget(label) def reject(self) -> None: diff --git a/app/src/doctor_workstation/ui/filter_disclosure.py b/app/src/doctor_workstation/ui/filter_disclosure.py index 0346c76ae..753fc4486 100644 --- a/app/src/doctor_workstation/ui/filter_disclosure.py +++ b/app/src/doctor_workstation/ui/filter_disclosure.py @@ -8,6 +8,7 @@ from PySide6.QtCore import QObject, QSize, Qt, Signal from PySide6.QtWidgets import QApplication, QPushButton, QWidget from . import icons +from .design_system import PALETTE, clinical_stylesheet class FilterDisclosure(QObject): @@ -35,17 +36,17 @@ class FilterDisclosure(QObject): self.button.setCursor(Qt.CursorShape.PointingHandCursor) self.button.setFixedHeight(32) self.button.setIconSize(QSize(14, 14)) - self.button.setStyleSheet(""" + self.button.setStyleSheet(clinical_stylesheet(""" QPushButton#FilterDisclosureButton { color: #1769E8; background: #FFFFFF; border: 1px solid #DBE5F2; - border-radius: 6px; padding: 0 11px; min-height: 30px; max-height: 30px; + border-radius: $ds_radius_control; padding: 0 11px; min-height: 30px; max-height: 30px; min-width: 92px; font-size: 13px; font-weight: 400; } - QPushButton#FilterDisclosureButton:hover { background: #F3F7FD; border-color: #ADC8F2; } - QPushButton#FilterDisclosureButton:checked { background: #EAF2FF; border-color: #ADC8F2; } - QPushButton#FilterDisclosureButton:focus { border-color: #1769E8; } - QPushButton#FilterDisclosureButton:disabled { color: #8B97A8; border-color: #E3E9F1; } - """) + QPushButton#FilterDisclosureButton:hover { background: $ds_canvas; border-color: $ds_line_strong; } + QPushButton#FilterDisclosureButton:checked { background: $ds_accent_soft; border-color: $ds_line_strong; } + QPushButton#FilterDisclosureButton:focus { border-color: $ds_focus; } + QPushButton#FilterDisclosureButton:disabled { color: $ds_disabled; border-color: $ds_line; } + """)) self.button.toggled.connect(self.set_expanded) self._apply() @@ -78,4 +79,4 @@ class FilterDisclosure(QObject): self.button.setAccessibleName(label) self.button.setAccessibleDescription("显示或收起检索条件和统计信息;收起保留当前筛选条件") self.button.setToolTip("收起保留当前筛选条件" if self._expanded else "展开检索条件和统计信息,当前筛选条件保持不变") - self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", "#1769E8", 14)) + self.button.setIcon(icons.icon("chevron_up" if self._expanded else "chevron_down", PALETTE["accent"], 14)) diff --git a/app/src/doctor_workstation/ui/infinite_list.py b/app/src/doctor_workstation/ui/infinite_list.py index 2b6082e36..19f9297e2 100644 --- a/app/src/doctor_workstation/ui/infinite_list.py +++ b/app/src/doctor_workstation/ui/infinite_list.py @@ -16,6 +16,7 @@ from PySide6.QtWidgets import ( QWidget, ) +from .design_system import clinical_stylesheet from .widgets import first_value, get_value, page_items, page_total, run_async @@ -54,16 +55,16 @@ class InfiniteList(QWidget): layout = QHBoxLayout(self) layout.setContentsMargins(12, 0, 12, 0) self.summary_label = QLabel("", self) - self.summary_label.setStyleSheet( + self.summary_label.setStyleSheet(clinical_stylesheet( "color: #5D6B80; font-size: 12px; background: transparent;" - ) + )) layout.addWidget(self.summary_label) layout.addStretch(1) self.retry_button = QPushButton("加载失败,点击重试", self) self.retry_button.setFlat(True) - self.retry_button.setStyleSheet( + self.retry_button.setStyleSheet(clinical_stylesheet( "color: #1769E8; font-size: 12px; padding: 0 4px; border: none; background: transparent; min-height: 20px; max-height: 20px; min-width: 0;" - ) + )) self.retry_button.hide() self.retry_button.clicked.connect(self.retry) layout.addWidget(self.retry_button) diff --git a/app/src/doctor_workstation/ui/login.py b/app/src/doctor_workstation/ui/login.py index 24aa407cc..691cc9000 100644 --- a/app/src/doctor_workstation/ui/login.py +++ b/app/src/doctor_workstation/ui/login.py @@ -5,26 +5,21 @@ from __future__ import annotations from contextlib import suppress from typing import Any -from PySide6.QtCore import QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal +from PySide6.QtCore import QEvent, QPoint, QPointF, QRectF, QSettings, Qt, QTimer, Signal from PySide6.QtGui import ( - QBrush, QColor, QFont, QIcon, - QLinearGradient, QPainter, QPainterPath, QPen, QPixmap, - QPolygonF, - QRadialGradient, QResizeEvent, ) from PySide6.QtWidgets import ( QApplication, QCheckBox, QFrame, - QGraphicsDropShadowEffect, QHBoxLayout, QLabel, QLayout, @@ -45,6 +40,7 @@ from doctor_workstation import __version__ from doctor_workstation.resources import app_icon_path, brand_lockup_path from . import icons +from .design_system import PALETTE, clinical_stylesheet from .widgets import BusyOverlay, MessageBanner, friendly_error, invoke, run_async @@ -127,7 +123,7 @@ def _round_pen(color: QColor | str, width: float) -> QPen: class _BrandPanel(QWidget): - """The quiet medical illustration and copy from the supplied login artwork.""" + """A flat, readable introduction to the clinician's daily workflow.""" def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) @@ -137,228 +133,76 @@ class _BrandPanel(QWidget): self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) self._brand_lockup = QPixmap(str(brand_lockup_path())) - @staticmethod - def _draw_cube(painter: QPainter, center: QPointF, size: float, kind: str) -> None: - x, y = center.x(), center.y() - top = QPolygonF( - [ - QPointF(x, y - size * 0.58), - QPointF(x + size * 0.48, y - size * 0.34), - QPointF(x, y - size * 0.10), - QPointF(x - size * 0.48, y - size * 0.34), - ] - ) - left = QPolygonF( - [ - QPointF(x - size * 0.48, y - size * 0.34), - QPointF(x, y - size * 0.10), - QPointF(x, y + size * 0.48), - QPointF(x - size * 0.48, y + size * 0.24), - ] - ) - right = QPolygonF( - [ - QPointF(x, y - size * 0.10), - QPointF(x + size * 0.48, y - size * 0.34), - QPointF(x + size * 0.48, y + size * 0.24), - QPointF(x, y + size * 0.48), - ] - ) - painter.setPen(QPen(QColor(185, 196, 247, 205), 1.2)) - painter.setBrush(QColor(235, 239, 255, 218)) - painter.drawPolygon(top) - painter.setBrush(QColor(210, 218, 255, 205)) - painter.drawPolygon(left) - painter.setBrush(QColor(224, 230, 255, 220)) - painter.drawPolygon(right) - painter.setPen(_round_pen(QColor(137, 154, 248, 135), 2.2)) - if kind == "plus": - painter.drawLine( - QPointF(x - size * 0.12, y + size * 0.05), - QPointF(x + size * 0.15, y - size * 0.02), - ) - painter.drawLine( - QPointF(x + size * 0.02, y - size * 0.13), - QPointF(x + size * 0.02, y + size * 0.17), - ) - else: - shield = QPainterPath(QPointF(x, y - size * 0.16)) - shield.lineTo(x + size * 0.15, y - size * 0.08) - shield.lineTo(x + size * 0.10, y + size * 0.17) - shield.lineTo(x, y + size * 0.26) - shield.lineTo(x - size * 0.10, y + size * 0.17) - shield.lineTo(x - size * 0.15, y - size * 0.08) - shield.closeSubpath() - painter.drawPath(shield) - - def _draw_illustration( - self, painter: QPainter, width: float, height: float - ) -> None: - ox = max(250.0, width - 500.0) - oy = max(365.0, height - 500.0) - - glow = QRadialGradient(QPointF(width - 170, oy + 230), 280) - glow.setColorAt(0.0, QColor(102, 120, 255, 62)) - glow.setColorAt(1.0, QColor(102, 120, 255, 0)) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(glow) - painter.drawEllipse(QPointF(width - 170, oy + 230), 280, 280) - - painter.setPen(QPen(QColor(166, 180, 241, 78), 1)) - for offset in (0, 72, 144): - painter.drawLine( - QPointF(ox - 80, oy + 280 + offset), - QPointF(width + 20, oy + 170 + offset), - ) - painter.drawLine(QPointF(ox + 10, oy + 400), QPointF(ox + 10, oy + 80)) - painter.drawLine(QPointF(ox + 170, oy + 430), QPointF(ox + 170, oy + 35)) - - base = QRectF(ox + 80, oy + 365, 430, 88) - base_gradient = QLinearGradient(base.topLeft(), base.bottomRight()) - base_gradient.setColorAt(0.0, QColor(246, 248, 255, 228)) - base_gradient.setColorAt(1.0, QColor(186, 199, 255, 184)) - painter.setBrush(base_gradient) - painter.setPen(QPen(QColor(166, 181, 248, 158), 1)) - painter.drawEllipse(base) - painter.setBrush(QColor(249, 250, 255, 225)) - painter.drawEllipse(QRectF(base.x() + 42, base.y() - 12, base.width() - 84, 70)) - - painter.save() - painter.translate(35, 40) - screen = QPolygonF( - [ - QPointF(ox + 130, oy + 60), - QPointF(ox + 435, oy + 100), - QPointF(ox + 435, oy + 365), - QPointF(ox + 130, oy + 310), - ] - ) - painter.setBrush(QColor(218, 225, 255, 205)) - painter.setPen(QPen(QColor(145, 163, 242, 170), 1.3)) - painter.drawPolygon(screen) - inner = QPolygonF( - [ - QPointF(ox + 141, oy + 80), - QPointF(ox + 425, oy + 117), - QPointF(ox + 425, oy + 345), - QPointF(ox + 141, oy + 295), - ] - ) - painter.setBrush(QColor(255, 255, 255, 225)) - painter.drawPolygon(inner) - - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor(174, 189, 252, 180)) - painter.drawRoundedRect(QRectF(ox + 148, oy + 89, 270, 15), 7, 7) - for dot_x in (156, 173, 190): - painter.setBrush(QColor(255, 255, 255, 200)) - painter.drawEllipse(QPointF(ox + dot_x, oy + 96.5), 3.5, 3.5) - - cards = ( - QRectF(ox + 150, oy + 135, 82, 80), - QRectF(ox + 241, oy + 142, 72, 73), - QRectF(ox + 322, oy + 151, 95, 72), - QRectF(ox + 151, oy + 232, 264, 50), - QRectF(ox + 151, oy + 291, 264, 42), - ) - painter.setPen(QPen(QColor(188, 199, 246, 160), 1)) - painter.setBrush(QColor(249, 250, 255, 228)) - for card in cards: - painter.drawRoundedRect(card, 7, 7) - painter.setPen(_round_pen(QColor(117, 137, 236, 165), 4)) - for idx, bar_height in enumerate((20, 36, 51)): - x = ox + 164 + idx * 17 - painter.drawLine(QPointF(x, oy + 200), QPointF(x, oy + 200 - bar_height)) - painter.setBrush(QColor(112, 132, 235, 160)) - painter.setPen(Qt.PenStyle.NoPen) - painter.drawEllipse(QPointF(ox + 277, oy + 167), 10, 10) - painter.drawRoundedRect(QRectF(ox + 259, oy + 180, 36, 20), 10, 10) - painter.setPen(_round_pen(QColor(137, 153, 235, 150), 5)) - for y, length in ((170, 54), (186, 42), (249, 89), (307, 72)): - painter.drawLine( - QPointF(ox + 340, oy + y), QPointF(ox + 340 + length, oy + y + 5) - ) - - self._draw_cube(painter, QPointF(ox + 352, oy - 25), 76, "plus") - self._draw_cube(painter, QPointF(ox - 8, oy + 210), 76, "shield") - painter.restore() - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt API del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.setRenderHint(QPainter.RenderHint.TextAntialiasing) - bounds = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) - background = QLinearGradient(bounds.topLeft(), bounds.bottomRight()) - background.setColorAt(0.0, QColor("#FFFFFF")) - background.setColorAt(0.7, QColor("#FFFFFF")) - background.setColorAt(1.0, QColor("#F7F7F7")) - painter.setBrush(background) - painter.setPen(QPen(QColor("#EDEDEE"), 1)) - painter.drawRoundedRect(bounds, 24, 24) - - width, height = float(self.width()), float(self.height()) - self._draw_illustration(painter, width, height) - - left = 64.0 if width >= 620 else 38.0 - if not self._brand_lockup.isNull(): - logo_width = 180.0 - logo_height = logo_width * ( - self._brand_lockup.height() / self._brand_lockup.width() - ) - painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) - painter.drawPixmap( - QRectF(left, 24, logo_width, logo_height), - self._brand_lockup, - QRectF(self._brand_lockup.rect()), - ) - - tag_rect = QRectF(left, 238, 119, 40) + bounds = QRectF(self.rect()).adjusted(1, 1, -1, -1) painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#EEF1FA")) - painter.drawRoundedRect(tag_rect, 11, 11) - painter.setFont(_font(17, QFont.Weight.Medium)) - painter.setPen(QColor("#4F63D9")) - painter.drawText(tag_rect, Qt.AlignmentFlag.AlignCenter, "医生工作站") + painter.setBrush(QColor(PALETTE["sidebar"])) + painter.drawRoundedRect(bounds, 20, 20) + left = 36.0 + width = max(240.0, self.width() - 72.0) + if not self._brand_lockup.isNull(): + brand = self._brand_lockup.scaled( + 226, 58, Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + painter.drawPixmap(QPointF(left, 36), brand) + else: + painter.setFont(_font(22, QFont.Weight.DemiBold)) + painter.setPen(QColor(PALETTE["heading"])) + painter.drawText(QPointF(left, 70), "甄养堂 · 医生工作站") - copy_left = left + 4 - painter.setFont(_font(48, QFont.Weight.Medium)) - painter.setPen(QColor("#1A1C1F")) - painter.drawText(QPointF(copy_left, 354), "把诊间工作,") - painter.drawText(QPointF(copy_left, 424), "留在一个") - prefix_width = painter.fontMetrics().horizontalAdvance("留在一个") - highlight = QLinearGradient( - copy_left + prefix_width, - 0, - copy_left + prefix_width + 264, - 0, - ) - highlight.setColorAt(0.0, QColor("#4F63D9")) - highlight.setColorAt(1.0, QColor("#4F63D9")) - painter.setPen(QPen(QBrush(highlight), 1)) - painter.drawText(QPointF(copy_left + prefix_width, 424), "安静的界面里") - suffix_x = ( - copy_left - + prefix_width - + painter.fontMetrics().horizontalAdvance("安静的界面里") - ) - painter.setPen(QColor("#1A1C1F")) - painter.drawText(QPointF(suffix_x, 424), "。") + heading_y = max(158.0, min(218.0, self.height() * .27)) + painter.setPen(QColor(PALETTE["muted"])) + painter.setFont(_font(13, QFont.Weight.Medium)) + painter.drawText(QPointF(left, heading_y - 36), "医 生 工 作 台") + painter.setPen(QColor(PALETTE["heading"])) + painter.setFont(_font(30, QFont.Weight.DemiBold)) + painter.drawText(QPointF(left, heading_y), "让诊疗有序,") + painter.drawText(QPointF(left, heading_y + 44), "让沟通更专注。") + painter.setFont(_font(14)) + painter.setPen(QColor(PALETTE["muted"])) + painter.drawText(QPointF(left, heading_y + 82), "从接诊、病历到处方,在一个工作台完成。") - body_left = left + 6 - painter.setFont(_font(20)) - painter.setPen(QColor("#606163")) - painter.drawText( - QPointF(body_left, 492), "接诊、问诊、患者与处方信息统一呈现," - ) - painter.drawText(QPointF(body_left, 525), "帮助医生专注于每一次沟通。") + row_y = heading_y + 122 + for index, (title, detail) in enumerate(( + ("今日接诊", "快速找到待接诊患者与预约安排"), + ("诊疗记录", "病历、随访与面诊资料集中查看"), + ("处方协作", "开方与审核流程清晰衔接"), + ), start=1): + row = QRectF(left, row_y, width, 66) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(PALETTE["surface"])) + painter.drawRoundedRect(row, 12, 12) + painter.setFont(_font(13, QFont.Weight.DemiBold)) + painter.setPen(QColor(PALETTE["accent"])) + painter.drawText(QRectF(left + 16, row_y, 28, 66), Qt.AlignmentFlag.AlignCenter, f"0{index}") + painter.setFont(_font(15, QFont.Weight.Medium)) + painter.setPen(QColor(PALETTE["heading"])) + painter.drawText(QPointF(left + 58, row_y + 27), title) + painter.setFont(_font(12)) + painter.setPen(QColor(PALETTE["muted"])) + painter.drawText(QPointF(left + 58, row_y + 47), detail) + row_y += 78 + if self.height() > row_y + 50: + painter.setFont(_font(12)) + painter.setPen(QColor(PALETTE["muted"])) + painter.drawText(QPointF(left, self.height() - 28), "仅供获授权的医疗人员使用") + painter.end() - painter.setFont(_font(16)) - painter.setPen(QColor("#6A6B6D")) - painter.drawText( - QPointF(body_left, height - 85), "本工作站仅供获授权的医疗人员使用" - ) - painter.drawText(QPointF(body_left, height - 59), "请勿在公共设备保存账号信息") + +class _PasswordField(QFrame): + """Keep the grouped password control visibly focused for keyboard users.""" + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 + if event.type() in (QEvent.Type.FocusIn, QEvent.Type.FocusOut): + self.setProperty("focused", event.type() == QEvent.Type.FocusIn) + self.style().unpolish(self) + self.style().polish(self) + self.update() + return super().eventFilter(watched, event) class _RevealButton(QToolButton): @@ -392,8 +236,8 @@ class _ServerButton(QPushButton): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) rect = QRectF(self.rect()).adjusted(0.75, 0.75, -0.75, -0.75) - painter.setBrush(QColor("#FFFFFF") if self.underMouse() else QColor("#FFFFFF")) - painter.setPen(QPen(QColor("#E4E4E5"), 1.5)) + painter.setBrush(QColor(PALETTE["accent_soft"] if self.underMouse() else PALETTE["surface"])) + painter.setPen(QPen(QColor(PALETTE["focus"] if self.hasFocus() else PALETTE["line_strong"]), 1)) painter.drawRoundedRect(rect, 12, 12) color = QColor("#1A1C1F" if self.isEnabled() else "#8E8F90") painter.setPen(_round_pen("#6A6B6D", 1.8)) @@ -536,7 +380,7 @@ class LoginWindow(QMainWindow): border: 1px solid #E4E4E5; border-radius: 12px; } - QFrame#PasswordField:focus-within { border-color: #8B9AD9; } + QFrame#PasswordField[focused="true"] { border-color: #8B9AD9; } QFrame#LoginCard QCheckBox { color: #606163; spacing: 13px; @@ -606,6 +450,9 @@ class LoginWindow(QMainWindow): self.login_root.addWidget(self.brand_panel, 60) self.login_root.addWidget(self._build_login_area(), 40) self._restore_settings() + for widget in (canvas, *canvas.findChildren(QWidget)): + if widget.styleSheet(): + widget.setStyleSheet(clinical_stylesheet(widget.styleSheet())) def resizeEvent(self, event: QResizeEvent) -> None: # noqa: N802 - Qt API """Preserve the reference composition while remaining usable on small screens.""" @@ -625,18 +472,15 @@ class LoginWindow(QMainWindow): # Keep the form fully visible when the 60/40 desktop split would # otherwise crop its fixed-width card. Small windows focus on login. self.brand_panel.setVisible(width >= 1120) + compact_height = event.size().height() < 720 + self.card.setMinimumHeight(580 if compact_height else 620) self.login_area_layout.setContentsMargins( - 0, min(104, max(24, (event.size().height() - 694) // 2)), 0, 12 + 0, 12 if compact_height else min(104, max(24, (event.size().height() - 694) // 2)), 0, 12 ) super().resizeEvent(event) def _build_brand_panel(self) -> QWidget: panel = _BrandPanel() - shadow = QGraphicsDropShadowEffect(panel) - shadow.setBlurRadius(32) - shadow.setOffset(0, 10) - shadow.setColor(QColor(67, 82, 154, 18)) - panel.setGraphicsEffect(shadow) return panel def _build_login_area(self) -> QWidget: @@ -660,11 +504,6 @@ class LoginWindow(QMainWindow): self.card.setFixedWidth(480) self.card.setMinimumHeight(620) self.card.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum) - card_shadow = QGraphicsDropShadowEffect(self.card) - card_shadow.setBlurRadius(38) - card_shadow.setOffset(0, 16) - card_shadow.setColor(QColor(59, 77, 139, 24)) - self.card.setGraphicsEffect(card_shadow) card_layout = QVBoxLayout(self.card) card_layout.setSizeConstraint(QLayout.SizeConstraint.SetDefaultConstraint) card_layout.setContentsMargins(47, 42, 47, 26) @@ -673,13 +512,13 @@ class LoginWindow(QMainWindow): title = QLabel("欢迎回来") title.setObjectName("LoginTitle") - title.setStyleSheet("color:#1A1C1F; font-size:30px; font-weight:500;") + title.setStyleSheet("color:#1A1C1F; font-size:26px; font-weight:600;") title.setContentsMargins(1, -3, 0, 3) title.setFixedHeight(46) card_layout.addWidget(title) subtitle = QLabel("使用医生账号登录工作站") subtitle.setProperty("role", "muted") - subtitle.setStyleSheet("color:#606163; font-size:18px;") + subtitle.setStyleSheet("color:#606163; font-size:15px;") subtitle.setContentsMargins(1, 8, 0, 0) subtitle.setFixedHeight(27) card_layout.addWidget(subtitle) @@ -710,7 +549,7 @@ class LoginWindow(QMainWindow): password_label.setFixedHeight(24) card_layout.addWidget(password_label) card_layout.addSpacing(11) - password_field = QFrame() + password_field = _PasswordField() password_field.setObjectName("PasswordField") password_field.setFixedHeight(54) password_row = QHBoxLayout(password_field) @@ -721,6 +560,7 @@ class LoginWindow(QMainWindow): self.password_edit.setEchoMode(QLineEdit.EchoMode.Password) self.password_edit.setPlaceholderText("请输入密码") self.password_edit.setAccessibleName("登录密码") + self.password_edit.installEventFilter(password_field) self.password_edit.setTextMargins(0, -2, 0, 2) self.password_edit.returnPressed.connect(self.submit) password_row.addWidget(self.password_edit, 1) @@ -730,6 +570,7 @@ class LoginWindow(QMainWindow): self.reveal_button.setCheckable(True) self.reveal_button.setFixedSize(87, 52) self.reveal_button.setToolTip("显示或隐藏密码") + self.reveal_button.installEventFilter(password_field) self.reveal_button.toggled.connect(self._toggle_password) password_row.addWidget(self.reveal_button) card_layout.addWidget(password_field) @@ -758,11 +599,6 @@ class LoginWindow(QMainWindow): self.login_button = QPushButton("登录工作站") self.login_button.setProperty("variant", "primary") self.login_button.setFixedHeight(58) - login_shadow = QGraphicsDropShadowEffect(self.login_button) - login_shadow.setBlurRadius(20) - login_shadow.setOffset(0, 7) - login_shadow.setColor(QColor(82, 101, 246, 45)) - self.login_button.setGraphicsEffect(login_shadow) self.login_button.clicked.connect(self.submit) card_layout.addWidget(self.login_button) self.debug_settings_section = QWidget() diff --git a/app/src/doctor_workstation/ui/motion.py b/app/src/doctor_workstation/ui/motion.py index 6236d8b14..9a4e41ce6 100644 --- a/app/src/doctor_workstation/ui/motion.py +++ b/app/src/doctor_workstation/ui/motion.py @@ -37,8 +37,10 @@ from PySide6.QtCore import ( QTimer, ) from PySide6.QtWidgets import ( + QAbstractItemView, QAbstractScrollArea, QGraphicsOpacityEffect, + QPlainTextEdit, QStackedWidget, QWidget, ) @@ -75,15 +77,35 @@ def reduced_motion() -> bool: return os.getenv("QT_QPA_PLATFORM", "").strip().lower() == "offscreen" -def _own(target: QWidget, key: str, animation: QPropertyAnimation) -> QPropertyAnimation: - """Park an animation on its target so Python does not collect it early.""" +def _stop(target: QObject, key: str) -> None: + """Retire a replaced animation without firing its completion callback.""" - running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", None) or {} - previous = running.get(key) + running = getattr(target, "_doctor_motion", {}) + previous = running.pop(key, None) if previous is not None: previous.stop() + previous.setParent(None) + previous.deleteLater() + + +def _own(target: QObject, key: str, animation: QPropertyAnimation) -> QPropertyAnimation: + """Park an animation on its target so Python does not collect it early.""" + + _stop(target, key) + running: dict[str, QPropertyAnimation] = getattr(target, "_doctor_motion", {}) running[key] = animation target._doctor_motion = running + + def release() -> None: + if running.get(key) is animation: + running.pop(key) + # A callback can hold the last Python reference to the owner. Detach + # first so releasing that callback during deferred deletion cannot + # recursively delete this animation through its former parent. + animation.setParent(None) + animation.deleteLater() + + animation.finished.connect(release) return animation @@ -107,7 +129,10 @@ def animate( from inside its own ``finished`` emission. """ + animation_owner = owner if owner is not None else target + animation_key = key or prop.decode() if reduced_motion(): + _stop(animation_owner, animation_key) target.setProperty(prop.decode() if isinstance(prop, bytes) else prop, end) if on_finished is not None: on_finished() @@ -117,18 +142,24 @@ def animate( animation.setEasingCurve(easing) animation.setStartValue(start) animation.setEndValue(end) + _own(animation_owner, animation_key, animation) if on_finished is not None: animation.finished.connect(on_finished) - _own(owner if owner is not None else target, key or prop.decode(), animation) animation.start(QAbstractAnimation.DeletionPolicy.KeepWhenStopped) return animation -def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect: +def _opacity_effect(widget: QWidget) -> QGraphicsOpacityEffect | None: effect = widget.graphicsEffect() - if not isinstance(effect, QGraphicsOpacityEffect): + # Do not replace a caller's shadow or opacity effect: Qt deletes it when + # another effect is attached. Only effects created here belong to a fade. + if effect is not None and effect is not getattr(widget, "_doctor_opacity_effect", None): + return None + if effect is None: effect = QGraphicsOpacityEffect(widget) + effect.setOpacity(1.0) widget.setGraphicsEffect(effect) + widget._doctor_opacity_effect = effect effect.setEnabled(True) return effect @@ -146,9 +177,17 @@ def _drop_effect(widget: QWidget) -> None: signal that is still being delivered. """ + effect = getattr(widget, "_doctor_opacity_effect", None) + revision = getattr(widget, "_doctor_fade_revision", 0) + def detach() -> None: try: - if isinstance(widget.graphicsEffect(), QGraphicsOpacityEffect): + if ( + effect is not None + and widget.graphicsEffect() is effect + and getattr(widget, "_doctor_fade_revision", 0) == revision + ): + widget._doctor_opacity_effect = None widget.setGraphicsEffect(None) except RuntimeError: # the widget went away while the fade was running pass @@ -156,6 +195,13 @@ def _drop_effect(widget: QWidget) -> None: QTimer.singleShot(0, detach) +def _restart_fade(widget: QWidget) -> None: + _stop(widget, "fade") + # A completed fade may still have deferred cleanup waiting in the queue. + # It must not remove an effect now being used by a subsequent fade. + widget._doctor_fade_revision = getattr(widget, "_doctor_fade_revision", 0) + 1 + + def fade_in( widget: QWidget, *, @@ -165,10 +211,20 @@ def fade_in( ) -> None: """Fade a widget up to full opacity, showing it first if needed.""" + existing = widget.graphicsEffect() + if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None): + start = float(existing.opacity()) + _restart_fade(widget) if reduced_motion(): + if existing is not None and existing is getattr(widget, "_doctor_opacity_effect", None): + existing.setOpacity(1.0) + _drop_effect(widget) widget.show() return effect = _opacity_effect(widget) + if effect is None: + widget.show() + return effect.setOpacity(start) widget.show() animate( @@ -193,9 +249,11 @@ def fade_out( ) -> None: """Fade a widget down, optionally hiding it when the fade completes.""" + _restart_fade(widget) if reduced_motion(): if hide: widget.hide() + _drop_effect(widget) if on_finished is not None: on_finished() return @@ -208,6 +266,9 @@ def fade_out( if on_finished is not None: on_finished() + if effect is None: + done() + return animate( effect, b"opacity", @@ -229,13 +290,17 @@ def enter(widget: QWidget, *, duration: int = BASE, rise: int = RISE) -> None: the user has to wait out. """ + previous = getattr(widget, "_doctor_motion", {}).get("enter") + origin = previous.endValue() if previous is not None else widget.pos() if reduced_motion(): - widget.show() + _stop(widget, "enter") + widget.move(origin) + fade_in(widget, duration=duration) return fade_in(widget, duration=duration) if rise: - origin = widget.pos() - widget.move(origin + QPoint(0, rise)) + if previous is None: + widget.move(origin + QPoint(0, rise)) animate( widget, b"pos", @@ -260,7 +325,7 @@ def switch_stack(stack: QStackedWidget, index: int, *, rise: int = RISE) -> None return stack.setCurrentIndex(index) page = stack.currentWidget() - if page is None or reduced_motion(): + if page is None: return enter(page, rise=rise) @@ -274,50 +339,121 @@ SCROLL_STEP = 120 SCROLL_MS = 190 +class _ScrollAnimation(QPropertyAnimation): + """Identify animation writes so direct scrollbar changes can interrupt us.""" + + writing = False + + def updateCurrentValue(self, value: Any) -> None: # noqa: N802 - Qt API + self.writing = True + try: + super().updateCurrentValue(value) + finally: + self.writing = False + + class _SmoothScroller(QObject): """Animate a scroll area's wheel movement instead of jumping to it.""" + _INTERRUPT_EVENTS = frozenset( + { + QEvent.Type.KeyPress, + QEvent.Type.MouseButtonPress, + QEvent.Type.TouchBegin, + QEvent.Type.Hide, + } + ) + def __init__(self, area: QAbstractScrollArea, *, orientation: Qt.Orientation) -> None: super().__init__(area) + self._area = area + self._orientation = orientation self._bar = ( area.verticalScrollBar() if orientation is Qt.Orientation.Vertical else area.horizontalScrollBar() ) self._target = self._bar.value() - self._animation = QPropertyAnimation(self._bar, b"value", self) + self._animation = _ScrollAnimation(self._bar, b"value", self) self._animation.setEasingCurve(EASE_ENTER) self._animation.setDuration(SCROLL_MS) - # Keyboard, programmatic and drag movements must not be fought over: when - # nothing is animating, the wheel target follows wherever the bar went. self._bar.valueChanged.connect(self._sync_target) + self._bar.sliderPressed.connect(self._cancel) + self._bar.actionTriggered.connect(self._cancel) + self._bar.rangeChanged.connect(self._cancel) + self._bar.installEventFilter(self) + area.installEventFilter(self) area.viewport().installEventFilter(self) + def _cancel(self, *_: Any) -> None: + self._animation.stop() + self._target = self._bar.value() + def _sync_target(self, value: int) -> None: - if self._animation.state() != QAbstractAnimation.State.Running: + if not self._animation.writing: + self._animation.stop() self._target = value + def _uses_pixels(self) -> bool: + if isinstance(self._area, QAbstractItemView): + mode = ( + self._area.verticalScrollMode() + if self._orientation == Qt.Orientation.Vertical + else self._area.horizontalScrollMode() + ) + return mode == QAbstractItemView.ScrollMode.ScrollPerPixel + # QPlainTextEdit's vertical scrollbar counts text blocks, not pixels. + return not ( + isinstance(self._area, QPlainTextEdit) and self._orientation == Qt.Orientation.Vertical + ) + def eventFilter(self, watched: QObject, event: QEvent) -> bool: # noqa: N802 - Qt API - del watched - if event.type() is not QEvent.Type.Wheel or reduced_motion(): + event_type = event.type() + if event_type in self._INTERRUPT_EVENTS: + self._cancel() return False - delta = event.angleDelta().y() or event.angleDelta().x() - if not delta or event.modifiers() & Qt.KeyboardModifier.ControlModifier: + if event_type != QEvent.Type.Wheel: return False + horizontal = self._orientation == Qt.Orientation.Horizontal + shifted = bool(event.modifiers() & Qt.KeyboardModifier.ShiftModifier) + delta = event.angleDelta().x() if horizontal else event.angleDelta().y() + if horizontal and shifted and not delta: + delta = event.angleDelta().y() + if ( + watched is not self._area.viewport() + or reduced_motion() + or not self._uses_pixels() + or not event.pixelDelta().isNull() + or event.phase() != Qt.ScrollPhase.NoScrollPhase + or event.modifiers() + & (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier) + or (shifted and not horizontal) + or not delta + ): + # Trackpads already provide continuous motion and native momentum. + # Mixing another easing curve into it adds lag and fights gestures. + self._cancel() + return False + lower, upper = self._bar.minimum(), self._bar.maximum() # Re-clamp first: the range can shrink underneath a running animation # when the content behind it reloads, which would otherwise leave the # pending target past the end of the new content. self._target = max(lower, min(upper, self._target)) - target = self._target - round(delta / 120.0 * SCROLL_STEP) + current = self._bar.value() + step = -round(delta / 120.0 * SCROLL_STEP) + # Reverse immediately from the visible position, not the end of a + # backlog of wheel notches still travelling in the opposite direction. + origin = current if (self._target - current) * step < 0 else self._target + target = origin + step target = max(lower, min(upper, target)) # At either end, hand the wheel back so an enclosing scroll area still # gets it - swallowing it there is what makes nested panes feel stuck. if target == self._target: - return False + return target != current self._target = target self._animation.stop() - self._animation.setStartValue(self._bar.value()) + self._animation.setStartValue(current) self._animation.setEndValue(target) self._animation.start() return True @@ -328,7 +464,7 @@ def install_smooth_scroll( *, orientation: Qt.Orientation = Qt.Orientation.Vertical, ) -> None: - """Give a scroll area eased wheel scrolling.""" + """Ease discrete wheels on pixel-based areas; preserve native gestures.""" if getattr(area, "_doctor_smooth_scroll", None) is not None: return diff --git a/app/src/doctor_workstation/ui/pages/patients.py b/app/src/doctor_workstation/ui/pages/patients.py index a83e2893f..d56f34338 100644 --- a/app/src/doctor_workstation/ui/pages/patients.py +++ b/app/src/doctor_workstation/ui/pages/patients.py @@ -50,6 +50,7 @@ from ...core.appointment_modes import ( ) from .. import icons from ..appointment_drawer import AppointmentDrawer +from ..design_system import PALETTE, clinical_stylesheet from ..dialogs import DiagnosisDialog, present_ai_consult, present_order_detail from ..dialogs.ai_consult import can_open_ai_consult from ..dialogs.prescription import PrescriptionOrderListDialog @@ -110,97 +111,97 @@ FULFILLMENT_TEXT = { } _SEMANTIC_COLORS = { - "primary": "#4F63D9", - "success": "#287B65", - "warning": "#A9691D", - "danger": "#BE4B58", - "info": "#4F63D9", - "muted": "#606163", + "primary": PALETTE["accent"], + "success": PALETTE["success"], + "warning": PALETTE["warning"], + "danger": PALETTE["danger"], + "info": PALETTE["accent"], + "muted": PALETTE["muted"], } -PATIENTS_LIGHT_QSS = """ +PATIENTS_LIGHT_QSS = clinical_stylesheet(""" #PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] { - color: #1A1C1F; + color: $ds_heading; font-size: 20px; font-weight: 600; } #PatientsPage QWidget#PageHeader QLabel[role="muted"] { - color: #606163; + color: $ds_muted; font-size: 13px; } #PatientsPage QPushButton[patientSearchAction="true"] { min-height: 32px; max-height: 32px; - color: #FFFFFF; - background-color: #4F63D9; - border: 1px solid #4F63D9; + color: $ds_surface; + background-color: $ds_accent; + border: 1px solid $ds_accent; border-radius: 7px; font-weight: 500; } #PatientsPage QPushButton[patientSearchAction="true"]:hover { - background-color: #4156C4; - border-color: #4156C4; + background-color: $ds_accent_hover; + border-color: $ds_accent_hover; } #PatientsPage QFrame[patientListFilter="true"] { min-height: 88px; max-height: 88px; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; + background-color: $ds_surface; + border: 1px solid $ds_line; border-radius: 12px; } #PatientsPage QFrame[patientListFilter="true"] QLineEdit, #PatientsPage QFrame[patientListFilter="true"] QDateEdit { min-height: 32px; max-height: 32px; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; + background-color: $ds_surface; + border: 1px solid $ds_line; border-radius: 7px; font-size: 14px; } #PatientsPage QFrame[patientListFilter="true"] QPushButton { min-height: 32px; max-height: 32px; } #PatientsPage QFrame[patientListFilter="true"] QDateEdit:disabled { - color: #8E8F90; background-color: #F7F7F7; + color: $ds_disabled; background-color: $ds_surface_alt; } #PatientsPage QPushButton[patientStatusChip="true"] { min-height: 32px; max-height: 32px; padding: 0 10px; - color: #606163; - background-color: #F7F7F7; + color: $ds_muted; + background-color: $ds_surface_alt; border: 1px solid transparent; border-radius: 5px; } #PatientsPage QPushButton[patientStatusChip="true"]:hover { - color: #4F63D9; - background-color: #EEF1FA; + color: $ds_accent; + background-color: $ds_accent_soft; } #PatientsPage QPushButton[patientStatusChip="true"]:checked { - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid #8B9AD9; + color: $ds_accent; + background-color: $ds_accent_soft; + border: 1px solid $ds_focus; } #PatientsPage QPushButton[patientQuickDate="true"] { min-height: 32px; max-height: 32px; padding: 0 9px; - color: #1A1C1F; + color: $ds_heading; background-color: transparent; border: 1px solid transparent; border-radius: 7px; } #PatientsPage QPushButton[patientQuickDate="true"]:hover { - color: #4F63D9; - background-color: #EEF1FA; + color: $ds_accent; + background-color: $ds_accent_soft; } #PatientsPage QPushButton[patientQuickDate="true"]:checked { - color: #4F63D9; - background-color: #EEF1FA; - border-color: #8B9AD9; + color: $ds_accent; + background-color: $ds_accent_soft; + border-color: $ds_focus; } #PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; - border-top: 1px solid #EDEDEE; + border-top: 1px solid $ds_line; background-color: transparent; } #PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab { @@ -208,124 +209,124 @@ PATIENTS_LIGHT_QSS = """ min-height: 34px; padding: 0 6px; margin-right: 8px; - color: #606163; + color: $ds_muted; background: transparent; border: 0; border-bottom: 2px solid transparent; font-weight: 400; } #PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected { - color: #4F63D9; - border-bottom-color: #4F63D9; + color: $ds_accent; + border-bottom-color: $ds_accent; font-weight: 500; } #PatientsPage QPushButton[summaryCard="true"] { min-height: 42px; max-height: 42px; padding: 0 11px; - color: #1A1C1F; - background-color: #F7F7F7; - border: 1px solid #EDEDEE; + color: $ds_heading; + background-color: $ds_surface_alt; + border: 1px solid $ds_line; border-radius: 9px; text-align: left; font-weight: 500; } #PatientsPage QPushButton[summaryCard="true"]:hover { - color: #4F63D9; - background-color: #EEF1FA; - border-color: #8B9AD9; + color: $ds_accent; + background-color: $ds_accent_soft; + border-color: $ds_focus; } #PatientsPage QPushButton[rowAction="true"] { min-height: 26px; max-height: 26px; padding: 0 7px; - color: #4F63D9; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; + color: $ds_accent; + background-color: $ds_surface; + border: 1px solid $ds_line; border-radius: 6px; font-size: 13px; font-weight: 400; } #PatientsPage QPushButton[rowAction="true"]:hover { - background-color: #EEF1FA; - border-color: #8B9AD9; + background-color: $ds_accent_soft; + border-color: $ds_focus; } #PatientsPage QPushButton[rowAction="true"][variant="danger"] { - color: #BE4B58; - background-color: #FFF7F8; - border-color: #F4C4CC; + color: $ds_danger; + background-color: $ds_danger_soft; + border-color: $ds_danger_soft; } #PatientsPage QTableWidget#PatientTable QHeaderView::section { min-height: 34px; - background-color: #F7F7F7; font-size: 13px; + background-color: $ds_surface_alt; font-size: 13px; } #PatientsPage QTableWidget#PatientTable::item { padding: 5px 7px; } #PatientsPage QTableWidget#PatientTable { - gridline-color: #EDEDEE; - selection-background-color: #EEF1FA; - selection-color: #1A1C1F; font-size: 14px; + gridline-color: $ds_line; + selection-background-color: $ds_accent_soft; + selection-color: $ds_heading; font-size: 14px; } #PatientsPage QCheckBox[patientSelector="true"]::indicator { width: 13px; height: 13px; - background-color: #FFFFFF; - border: 1px solid #EDEDEE; + background-color: $ds_surface; + border: 1px solid $ds_line; border-radius: 2px; } #PatientsPage QCheckBox[patientSelector="true"]::indicator:checked { - background-color: #4F63D9; - border-color: #4F63D9; + background-color: $ds_accent; + border-color: $ds_accent; } #PatientsPage QPushButton[variant="ghost"]:checked { - color: #4F63D9; - background-color: #EEF1FA; - border: 1px solid #4F63D9; + color: $ds_accent; + background-color: $ds_accent_soft; + border: 1px solid $ds_accent; } -#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: #EEF1FA; } +#PatientsPage QPushButton[variant="ghost"]:checked:hover { background-color: $ds_accent_soft; } #PatientsPage QPushButton[statusKind="info"]:checked { - color: #4F63D9; - border-color: #4F63D9; + color: $ds_accent; + border-color: $ds_accent; } #PatientsPage QPushButton[statusKind="warning"]:checked { - color: #A9691D; - border-color: #A9691D; + color: $ds_warning; + border-color: $ds_warning; } #PatientsPage QPushButton[statusKind="success"]:checked { - color: #287B65; - border-color: #287B65; + color: $ds_success; + border-color: $ds_success; } #PatientsPage QPushButton[statusKind="danger"]:checked { - color: #BE4B58; - border-color: #BE4B58; + color: $ds_danger; + border-color: $ds_danger; } -#PatientsPage QLabel[metricKind="primary"] { color: #4F63D9; } -#PatientsPage QLabel[metricKind="info"] { color: #4F63D9; } -#PatientsPage QLabel[metricKind="success"] { color: #287B65; } -#PatientsPage QLabel[metricKind="warning"] { color: #A9691D; } -#PatientsPage QLabel[metricKind="danger"] { color: #BE4B58; } +#PatientsPage QLabel[metricKind="primary"] { color: $ds_accent; } +#PatientsPage QLabel[metricKind="info"] { color: $ds_accent; } +#PatientsPage QLabel[metricKind="success"] { color: $ds_success; } +#PatientsPage QLabel[metricKind="warning"] { color: $ds_warning; } +#PatientsPage QLabel[metricKind="danger"] { color: $ds_danger; } #PatientsPage QTabWidget#PatientWorkspaceTabs::pane { background-color: transparent; border: 0; top: -1px; } #PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab { - color: #606163; + color: $ds_muted; background-color: transparent; border: 0; border-bottom: 2px solid transparent; font-weight: 400; } #PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:hover { - color: #4F63D9; - background-color: #EEF1FA; + color: $ds_accent; + background-color: $ds_accent_soft; } #PatientsPage QTabWidget#PatientWorkspaceTabs QTabBar::tab:selected { - color: #4F63D9; + color: $ds_accent; background-color: transparent; - border-bottom-color: #4F63D9; + border-bottom-color: $ds_accent; font-weight: 500; } -""" +""") def _style_table_cell(table: SortableTable, row: int, column: int, kind: str) -> None: @@ -1282,7 +1283,7 @@ class _PatientDateEdit(QDateEdit): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 15) + glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 15) painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 15) / 2, 15, 15), glyph, QRectF(glyph.rect())) painter.end() @@ -1300,18 +1301,18 @@ class _PatientSummaryButton(QPushButton): label, _, count = self.text().partition("\n") left = max(18, (self.width() - 204) // 2) icon_rect = QRectF(left, (self.height() - 36) / 2, 36, 36) - glyph = icons.pixmap("calendar", "#1769E8", 36) + glyph = icons.pixmap("calendar", PALETTE["accent"], 36) painter.drawPixmap(icon_rect, glyph, QRectF(glyph.rect())) font = QFont(body_family()) font.setPixelSize(13) painter.setFont(font) - painter.setPen(QColor("#5D6B80")) + painter.setPen(QColor(PALETTE["muted"])) text_rect = self.rect().adjusted(left + 46, 10, -12, -32) painter.drawText(text_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(label, Qt.TextElideMode.ElideRight, text_rect.width())) font.setPixelSize(16) painter.setFont(font) - painter.setPen(QColor("#273244")) + painter.setPen(QColor(PALETTE["text"])) painter.drawText(self.rect().adjusted(left + 46, 31, -12, -9), Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, count) painter.end() @@ -1324,11 +1325,11 @@ class _PatientInfoDelegate(QStyledItemDelegate): painter.save() selected = bool(option.state & QStyle.StateFlag.State_Selected) hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - painter.fillRect(option.rect, QColor("#EAF2FF" if selected else "#F6F9FE" if hovered else "#FFFFFF")) - painter.setPen(QColor("#E6EDF6")) + painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"])) + painter.setPen(QColor(PALETTE["line"])) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) if selected and index.column() == 0: - painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8")) + painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"])) if index.column() in (0, 9): painter.restore() return @@ -1337,9 +1338,9 @@ class _PatientInfoDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(14) painter.setFont(font) - painter.setPen(QColor("#273244")) + painter.setPen(QColor(PALETTE["text"])) - def draw(text: str, target: Any, color: str = "#273244", centered: bool = False) -> None: + def draw(text: str, target: Any, color: str = PALETTE["text"], centered: bool = False) -> None: painter.setPen(QColor(color)) text = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, target.width()) alignment = Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignHCenter if centered else Qt.AlignmentFlag.AlignLeft) @@ -1359,17 +1360,17 @@ class _PatientInfoDelegate(QStyledItemDelegate): doctor = display_text(first_value(row, "appointment_doctor_name"), "") status, _kind = _patient_status(row) if not doctor: - draw(status, rect, "#5D6B80") + draw(status, rect, PALETTE["muted"]) else: draw(doctor, top) font.setPixelSize(13) painter.setFont(font) - color, fill = ("#A9691D", "#FFF7EA") if status == "已过号" else ("#1769E8", "#F0F6FF") + color, fill = (PALETTE["warning"], PALETTE["warning_soft"]) if status == "已过号" else (PALETTE["accent"], PALETTE["accent_soft"]) if status == "已取消": - color, fill = "#5D6B80", "#F5F7FA" + color, fill = PALETTE["muted"], PALETTE["canvas"] badge = QRectF(bottom.x(), bottom.y() + 1, min(bottom.width(), painter.fontMetrics().horizontalAdvance(status) + 10), 20) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - painter.setPen(QColor("#E7CDA8" if status == "已过号" else "#C7DAF7")) + painter.setPen(QColor(PALETTE["warning_soft"] if status == "已过号" else PALETTE["line_strong"])) painter.setBrush(QColor(fill)) painter.drawRoundedRect(badge, 3, 3) draw(status, badge.toRect(), color, True) @@ -1385,7 +1386,7 @@ class _PatientInfoDelegate(QStyledItemDelegate): draw(value, rect) else: text = str(index.data(Qt.ItemDataRole.DisplayRole) or "") - draw(text, rect, "#A9691D" if index.column() == 6 and text == "待确认" else "#273244", index.column() == 5) + draw(text, rect, PALETTE["warning"] if index.column() == 6 and text == "待确认" else PALETTE["text"], index.column() == 5) painter.restore() @@ -1493,7 +1494,7 @@ class PatientListWorkspace(QWidget): self.keyword_edit.setMaximumWidth(360) self.keyword_edit.setPlaceholderText("患者姓名 / 手机号 / 助理 / 医生") self.keyword_edit.setClearButtonEnabled(True) - self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition) + self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition) self.keyword_edit.returnPressed.connect(self.search) search_row.addWidget(self.keyword_edit, 1) self.status_label = QLabel("患者状态:") @@ -1846,7 +1847,7 @@ class PatientListWorkspace(QWidget): ) host = RowActions(row_actions, self.table) if host.more_button is not None: - host.more_button.setIcon(icons.icon("chevron_down", "#5D6B80", 12)) + host.more_button.setIcon(icons.icon("chevron_down", PALETTE["muted"], 12)) host.more_button.setIconSize(QSize(12, 12)) host.more_button.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) host.more_button.setLayoutDirection(Qt.LayoutDirection.RightToLeft) @@ -2079,7 +2080,7 @@ class _OrderComboBox(QComboBox): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("chevron_down", "#5D6B80", 14) + glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14) painter.drawPixmap(QRectF(self.width() - 24, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -2088,7 +2089,7 @@ class _OrderActionButton(QToolButton): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("chevron_down", "#5D6B80" if self.isEnabled() else "#97A4B6", 14) + glyph = icons.pixmap("chevron_down", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14) painter.drawPixmap(QRectF(self.width() - 23, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -2107,18 +2108,18 @@ class _OrderInfoDelegate(QStyledItemDelegate): painter.setClipRect(option.rect) selected = bool(option.state & QStyle.StateFlag.State_Selected) hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - painter.fillRect(option.rect, QColor("#F5F8FF" if selected else "#F8FAFE" if hovered else "#FFFFFF")) - painter.setPen(QColor("#E6EDF6")) + painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"])) + painter.setPen(QColor(PALETTE["line"])) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) if selected and index.column() == 0: - painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8")) + painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"])) rect = option.rect.adjusted(16, 0, -12, -1) font = QFont(body_family()) font.setPixelSize(14) painter.setFont(font) text = str(index.data(Qt.ItemDataRole.DisplayRole) or "—") - def draw(value: str, target: Any, color: str = "#273244", right: bool = False) -> None: + def draw(value: str, target: Any, color: str = PALETTE["text"], right: bool = False) -> None: painter.setPen(QColor(color)) value = painter.fontMetrics().elidedText(value, Qt.TextElideMode.ElideRight, target.width()) painter.drawText(target, Qt.AlignmentFlag.AlignVCenter | (Qt.AlignmentFlag.AlignRight if right else Qt.AlignmentFlag.AlignLeft), value) @@ -2138,7 +2139,7 @@ class _OrderInfoDelegate(QStyledItemDelegate): font.setWeight(QFont.Weight.Normal) font.setPixelSize(13) painter.setFont(font) - draw(secondary, bottom, "#5D6B80") + draw(secondary, bottom, PALETTE["muted"]) else: draw(text, rect) elif column in (9, 11): @@ -2147,7 +2148,7 @@ class _OrderInfoDelegate(QStyledItemDelegate): draw(primary, top) font.setPixelSize(13) painter.setFont(font) - draw(("(" if column == 9 else "") + secondary, bottom, "#5D6B80") + draw(("(" if column == 9 else "") + secondary, bottom, PALETTE["muted"]) else: draw(text, rect) elif column in (4, 5, 6): @@ -2158,10 +2159,10 @@ class _OrderInfoDelegate(QStyledItemDelegate): else: kind = "blue" if raw in {3, 5, 6, 7, 8, 11} else "danger" if raw in {4, 9, 10} else "warning" if raw in {1, 2, 12} else "neutral" foreground, background, border = { - "blue": ("#1769E8", "#F2F7FF", "#CEE0FA"), - "warning": ("#AD640C", "#FFFAF2", "#F2DABD"), - "danger": ("#BE4657", "#FFF5F6", "#F0D0D7"), - "neutral": ("#5D6B80", "#F6F8FC", "#E2E9F2"), + "blue": (PALETTE["accent"], PALETTE["accent_soft"], PALETTE["line_strong"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"], PALETTE["danger_soft"]), + "neutral": (PALETTE["muted"], PALETTE["disabled_surface"], PALETTE["line"]), }[kind] font.setPixelSize(13) painter.setFont(font) @@ -2275,7 +2276,7 @@ class PatientOrdersWorkspace(QWidget): self.keyword_edit.setMinimumWidth(240) self.keyword_edit.setPlaceholderText("订单号 / 患者 / 手机号 / 处方ID / 诊单ID") self.keyword_edit.setClearButtonEnabled(True) - self.keyword_edit.addAction(icons.icon("search", "#5D6B80", 16), QLineEdit.ActionPosition.LeadingPosition) + self.keyword_edit.addAction(icons.icon("search", PALETTE["muted"], 16), QLineEdit.ActionPosition.LeadingPosition) self.keyword_edit.returnPressed.connect(self.search) self.filter_top_row.addWidget(self.keyword_edit, 1) self.audit_host = QWidget() @@ -2747,11 +2748,11 @@ class _ProgressInfoDelegate(QStyledItemDelegate): painter.setClipRect(option.rect) selected = bool(option.state & QStyle.StateFlag.State_Selected) hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF")) - painter.setPen(QColor("#E6EDF6")) + painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"])) + painter.setPen(QColor(PALETTE["line"])) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) if selected and index.column() == 0: - painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8")) + painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"])) rect = option.rect.adjusted(16, 0, -16, -1) font = QFont(body_family()) font.setPixelSize(14) @@ -2762,20 +2763,20 @@ class _ProgressInfoDelegate(QStyledItemDelegate): painter.setFont(font) raw_text = index.data(Qt.ItemDataRole.DisplayRole) text = "" if raw_text is None else str(raw_text) - color = "#273244" + color = PALETTE["text"] if not self.schedule and index.column() == 5 and text and text != "—": row = index.data(Qt.ItemDataRole.UserRole) status = str(first_value(row, "queue_status", default="") or "").lower() color = { - "consulting": "#1769E8", "next": "#1555B6", - "waiting": "#AD640C", "missed": "#BE4657", - }.get(status, "#5D6B80") + "consulting": PALETTE["accent"], "next": PALETTE["accent_hover"], + "waiting": PALETTE["warning"], "missed": PALETTE["danger"], + }.get(status, PALETTE["muted"]) painter.setPen(QColor(color)) alignment = Qt.AlignmentFlag.AlignVCenter alignment |= Qt.AlignmentFlag.AlignHCenter if self.schedule and 1 <= index.column() <= 5 else Qt.AlignmentFlag.AlignLeft painter.drawText(rect, alignment, painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, rect.width())) if option.state & QStyle.StateFlag.State_HasFocus: - painter.setPen(QColor("#75A5F0")) + painter.setPen(QColor(PALETTE["focus"])) painter.setBrush(Qt.BrushStyle.NoBrush) painter.drawRect(option.rect.adjusted(1, 1, -2, -2)) painter.restore() @@ -2875,7 +2876,7 @@ class PatientProgressWorkspace(QWidget): row = QHBoxLayout(frame) row.setContentsMargins(0, 0, 0, 0) row.setSpacing(0) - divider = QFrame() + divider = QFrame(frame) divider.setObjectName("ProgressMetricDivider") divider.setFixedSize(1, 60) divider.setVisible(key != "total") diff --git a/app/src/doctor_workstation/ui/pages/prescription_library.py b/app/src/doctor_workstation/ui/pages/prescription_library.py index e555800ab..3a6480cdb 100644 --- a/app/src/doctor_workstation/ui/pages/prescription_library.py +++ b/app/src/doctor_workstation/ui/pages/prescription_library.py @@ -24,6 +24,7 @@ from PySide6.QtWidgets import ( ) from .. import motion +from ..design_system import PALETTE from ..dialogs.prescription import PrescriptionTemplateDialog from ..dialogs.prescription_ai import PrescriptionAiReportDialog, can_open_ai_explain from ..filter_disclosure import FilterDisclosure @@ -119,7 +120,7 @@ def _metric_card(title: str, kind: str = "accent", glyph: str = "layers") -> Met icon.setProperty("metricIcon", True) icon.setAlignment(Qt.AlignmentFlag.AlignCenter) icon.setFixedSize(32, 32) - color = "#1769E8" if kind == "accent" else "#60789F" + color = PALETTE["accent"] if kind == "accent" else PALETTE["muted"] icon.setPixmap(_painted_icon(glyph, color, 25).pixmap(25, 25)) card.layout().addWidget(icon) return card @@ -543,7 +544,7 @@ class PrescriptionLibraryPage(QWidget): name_item = self.table.item(row_index, 1) if name_item is not None: - name_item.setForeground(QColor("#1A1C1F")) + name_item.setForeground(QColor(PALETTE["heading"])) font = name_item.font() font.setWeight(QFont.Weight.Medium) name_item.setFont(font) diff --git a/app/src/doctor_workstation/ui/pages/prescriptions.py b/app/src/doctor_workstation/ui/pages/prescriptions.py index 4bf9ba9dd..5a0a65f83 100644 --- a/app/src/doctor_workstation/ui/pages/prescriptions.py +++ b/app/src/doctor_workstation/ui/pages/prescriptions.py @@ -50,6 +50,7 @@ from PySide6.QtWidgets import ( ) from .. import icons, motion +from ..design_system import PALETTE, clinical_stylesheet from ..dialogs.issued_prescription_ai import ( PrescriptionAiStatisticsDialog, agreement_safe_batch, @@ -229,11 +230,11 @@ _ROLE_AVATAR = Qt.ItemDataRole.UserRole + 11 _ROLE_LEAD_ICON = Qt.ItemDataRole.UserRole + 12 _TAG_PALETTE = { - "accent": ("#4F63D9", "#EEF1FA"), - "success": ("#287B65", "#E7F8F1"), - "warning": ("#A9691D", "#FFF5DF"), - "danger": ("#BE4B58", "#FFF0F2"), - "neutral": ("#606163", "#F7F7F7"), + "accent": (PALETTE["accent"], PALETTE["accent_soft"]), + "success": (PALETTE["success"], PALETTE["success_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), + "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + "neutral": (PALETTE["muted"], PALETTE["surface_alt"]), } @@ -293,7 +294,7 @@ class _RowDecorationDelegate(QStyledItemDelegate): glyph, QRectF(glyph.rect()), ) - painter.setPen(QColor("#1A1C1F")) + painter.setPen(QColor(PALETTE["heading"])) painter.setFont(style_option.font) text_rect = rect.adjusted(28, 0, -8, 0) painter.drawText( @@ -306,17 +307,17 @@ class _RowDecorationDelegate(QStyledItemDelegate): else: initial = str(avatar)[:1] or "医" circle = QRectF(rect.left() + 8, rect.center().y() - 10, 20, 20) - painter.setPen(QPen(QColor("#EDEDEE"), 1.0)) - painter.setBrush(QColor("#F7F7F7")) + painter.setPen(QPen(QColor(PALETTE["line"]), 1.0)) + painter.setBrush(QColor(PALETTE["surface_alt"])) painter.drawEllipse(circle.adjusted(0.5, 0.5, -0.5, -0.5)) initial_font = QFont(style_option.font) initial_font.setPixelSize(10) initial_font.setWeight(QFont.Weight.Medium) painter.setFont(initial_font) - painter.setPen(QColor("#6A6B6D")) + painter.setPen(QColor(PALETTE["muted"])) painter.drawText(circle, Qt.AlignmentFlag.AlignCenter, initial) painter.setFont(style_option.font) - painter.setPen(QColor("#1A1C1F")) + painter.setPen(QColor(PALETTE["heading"])) name_rect = rect.adjusted(35, 0, -8, 0) painter.drawText( name_rect, @@ -509,11 +510,11 @@ class _PrescriptionNumberDelegate(QStyledItemDelegate): text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere) document.setDefaultTextOption(text_option) paragraphs = [ - f'

{escape(number)}

', - f'

ID: {escape(record_id)}

', + f'

{escape(number)}

', + f'

ID: {escape(record_id)}

', ] paragraphs.extend( - '

' + f'

' + escape(warning) + "

" for warning in _order_warnings(row) @@ -603,14 +604,14 @@ class _DoctorOptionDelegate(QStyledItemDelegate): rect = option.rect.adjusted(2, 1, -2, -1) hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#EAF2FF" if checked else "#F3F7FD" if hovered else "#FFFFFF")) + painter.setBrush(QColor(PALETTE["accent_soft"] if checked else PALETTE["canvas"] if hovered else PALETTE["surface"])) painter.drawRoundedRect(rect, 5, 5) box = QRectF(rect.left() + 10, rect.center().y() - 8, 16, 16) - painter.setPen(QPen(QColor("#1769E8" if checked else "#B8C7DA"), 1)) - painter.setBrush(QColor("#1769E8" if checked else "#FFFFFF")) + painter.setPen(QPen(QColor(PALETTE["accent"] if checked else PALETTE["line_strong"]), 1)) + painter.setBrush(QColor(PALETTE["accent"] if checked else PALETTE["surface"])) painter.drawRoundedRect(box, 3, 3) if checked: - pen = QPen(QColor("#FFFFFF"), 2) + pen = QPen(QColor(PALETTE["surface"]), 2) pen.setCapStyle(Qt.PenCapStyle.RoundCap) painter.setPen(pen) x, y = int(box.x()), int(box.y()) @@ -619,16 +620,16 @@ class _DoctorOptionDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(13) painter.setFont(font) - painter.setPen(QColor("#273244")) + painter.setPen(QColor(PALETTE["text"])) text_rect = rect.adjusted(38, 0, -54, 0) label = painter.fontMetrics().elidedText(str(index.data() or ""), Qt.TextElideMode.ElideRight, text_rect.width()) painter.drawText(text_rect, Qt.AlignmentFlag.AlignVCenter, label) if checked: - painter.setPen(QColor("#1769E8")) + painter.setPen(QColor(PALETTE["accent"])) painter.drawText(rect.adjusted(0, 0, -12, 0), Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, "已选") if option.state & QStyle.StateFlag.State_HasFocus: painter.setBrush(Qt.BrushStyle.NoBrush) - painter.setPen(QPen(QColor("#ADC8F2"), 1)) + painter.setPen(QPen(QColor(PALETTE["line_strong"]), 1)) painter.drawRoundedRect(rect, 5, 5) painter.restore() @@ -674,18 +675,18 @@ class _DoctorSelectionDialog(QDialog): self.setObjectName("DoctorSelectionDialog") self.setWindowTitle("选择医生") self.resize(420, 500) - self.setStyleSheet(""" - QDialog#DoctorSelectionDialog { background: #FFFFFF; color: #273244; } - QListWidget#DoctorOptionsList { background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 6px; padding: 3px; } - QLabel#DoctorSelectionCount { color: #1769E8; font-size: 13px; } - QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid #DBE5F2; border-radius: 6px; } - QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: #1769E8; } - QDialog#DoctorSelectionDialog QPushButton { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; border-radius: 6px; } - QDialog#DoctorSelectionDialog QPushButton:hover { background: #F3F7FD; border-color: #ADC8F2; } - QDialog#DoctorSelectionDialog QPushButton:disabled { color: #8A97A9; } - QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: #1769E8; color: #FFFFFF; border-color: #1769E8; } - QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: #125DCE; border-color: #125DCE; } - """) + self.setStyleSheet(clinical_stylesheet(""" + QDialog#DoctorSelectionDialog { background: $ds_surface; color: $ds_text; } + QListWidget#DoctorOptionsList { background: $ds_surface; border: 1px solid $ds_line; border-radius: 6px; padding: 3px; } + QLabel#DoctorSelectionCount { color: $ds_accent; font-size: 13px; } + QDialog#DoctorSelectionDialog QLineEdit { border: 1px solid $ds_line; border-radius: 6px; } + QDialog#DoctorSelectionDialog QLineEdit:focus { border-color: $ds_accent; } + QDialog#DoctorSelectionDialog QPushButton { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; border-radius: 6px; } + QDialog#DoctorSelectionDialog QPushButton:hover { background: $ds_canvas; border-color: $ds_line_strong; } + QDialog#DoctorSelectionDialog QPushButton:disabled { color: $ds_disabled; } + QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection { background: $ds_accent; color: $ds_surface; border-color: $ds_accent; } + QDialog#DoctorSelectionDialog QPushButton#ConfirmDoctorSelection:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; } + """)) layout = QVBoxLayout(self) layout.setContentsMargins(16, 16, 16, 16) layout.setSpacing(10) @@ -793,9 +794,9 @@ class DoctorMultiSelect(QWidget): self.button.setText("、".join(names[:2]) + (f" 等{len(names)}人" if len(names) > 2 else "")) -def _blue_prescription_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon: +def _blue_prescription_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon: result = QIcon(icons.icon(kind, color, size)) - result.addPixmap(icons.pixmap(kind, "#A4ADBA", size), QIcon.Mode.Disabled) + result.addPixmap(icons.pixmap(kind, PALETTE["disabled"], size), QIcon.Mode.Disabled) return result @@ -803,7 +804,7 @@ class _PrescriptionCombo(QComboBox): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("chevron_down", "#5D6B80", 14) + glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14) painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -812,7 +813,7 @@ class _PrescriptionDateTime(QDateTimeEdit): def paintEvent(self, event: Any) -> None: super().paintEvent(event) painter = QPainter(self) - glyph = icons.pixmap("calendar", "#5D6B80" if self.isEnabled() else "#8A97A9", 14) + glyph = icons.pixmap("calendar", PALETTE["muted"] if self.isEnabled() else PALETTE["disabled"], 14) painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -825,7 +826,7 @@ class _PrescriptionDoctorButton(QPushButton): option.text = self.fontMetrics().elidedText(self.text(), Qt.TextElideMode.ElideRight, max(1, self.width() - 48)) painter = QPainter(self) self.style().drawControl(QStyle.ControlElement.CE_PushButton, option, painter, self) - glyph = icons.pixmap("chevron_down", "#5D6B80", 14) + glyph = icons.pixmap("chevron_down", PALETTE["muted"], 14) painter.drawPixmap(QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14), glyph, QRectF(glyph.rect())) painter.end() @@ -837,13 +838,13 @@ class _PrescriptionDoctorButton(QPushButton): def _prescription_cell_background(painter: QPainter, option: Any, index: QModelIndex) -> None: selected = bool(option.state & QStyle.StateFlag.State_Selected) hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - painter.fillRect(option.rect, QColor("#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF")) - painter.setPen(QColor("#E6EDF6")) + painter.fillRect(option.rect, QColor(PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"])) + painter.setPen(QColor(PALETTE["line"])) painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) if selected and index.column() == 0: - painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor("#1769E8")) + painter.fillRect(option.rect.adjusted(0, 0, -option.rect.width() + 3, 0), QColor(PALETTE["accent"])) if option.state & QStyle.StateFlag.State_HasFocus: - painter.setPen(QColor("#75A5F0")) + painter.setPen(QColor(PALETTE["focus"])) painter.setBrush(Qt.BrushStyle.NoBrush) painter.drawRect(option.rect.adjusted(1, 1, -2, -2)) @@ -875,7 +876,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(14) painter.setFont(font) - painter.setPen(QColor("#273244")) + painter.setPen(QColor(PALETTE["text"])) text = str(index.data(Qt.ItemDataRole.DisplayRole) or "") column = index.column() if column == 0: @@ -888,9 +889,9 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): elif column in (3, 6): kind = index.data(_ROLE_TAG_KIND) foreground, background = { - "accent": ("#1769E8", "#EDF4FF"), "success": ("#1769E8", "#EDF4FF"), - "warning": ("#AD640C", "#FFF5E5"), "danger": ("#BE4657", "#FFF0F2"), - }.get(kind, ("#5D6B80", "#F5F8FD")) + "accent": (PALETTE["accent"], PALETTE["accent_soft"]), "success": (PALETTE["accent"], PALETTE["accent_soft"]), + "warning": (PALETTE["warning"], PALETTE["warning_soft"]), "danger": (PALETTE["danger"], PALETTE["danger_soft"]), + }.get(kind, (PALETTE["muted"], PALETTE["surface_alt"])) font.setPixelSize(13) painter.setFont(font) label = painter.fontMetrics().elidedText(text, Qt.TextElideMode.ElideRight, max(1, rect.width() - 12)) @@ -918,7 +919,7 @@ class _PrescriptionInfoDelegate(QStyledItemDelegate): font = QFont(body_family()) font.setPixelSize(13) painter.setFont(font) - painter.setPen(QColor("#5D6B80")) + painter.setPen(QColor(PALETTE["muted"])) second_rect = first_rect.translated(0, 26) painter.drawText(second_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, painter.fontMetrics().elidedText(secondary, Qt.TextElideMode.ElideRight, rect.width())) else: @@ -942,11 +943,11 @@ class _PrescriptionNumberBlueDelegate(_PrescriptionNumberDelegate): text_option.setWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere) document.setDefaultTextOption(text_option) paragraphs = [ - f'

{escape(number)}

', - f'

ID: {escape(record_id)}

', + f'

{escape(number)}

', + f'

ID: {escape(record_id)}

', ] paragraphs.extend( - '

' + escape(warning) + "

" + f'

' + escape(warning) + "

" for warning in _order_warnings(row) ) document.setHtml("".join(paragraphs)) @@ -976,7 +977,7 @@ class _PrescriptionBlueTable(SortableTable): for button in widget.findChildren(QPushButton): kind = {"查看处方": "eye", "编辑处方": "pencil", "删除处方": "trash"}.get(button.accessibleName()) if kind: - button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8")) + button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) class PrescriptionsPage(QWidget): @@ -1060,7 +1061,7 @@ class PrescriptionsPage(QWidget): self.add_button.setObjectName("PrescriptionAddButton") self.add_button.setMinimumWidth(122) self.add_button.setProperty("variant", "primary") - self.add_button.setIcon(_blue_prescription_icon("plus", "#FFFFFF")) + self.add_button.setIcon(_blue_prescription_icon("plus", PALETTE["surface"])) self.add_button.setIconSize(QSize(15, 15)) self.add_button.setCursor(Qt.CursorShape.PointingHandCursor) self.add_button.setVisible(has_permission(permissions, "cf.prescription/add")) @@ -1079,7 +1080,7 @@ class PrescriptionsPage(QWidget): self.table_card = table_card root.addWidget(table_card, 1) for button, kind in ((self.view_button, "eye"), (self.edit_button, "pencil"), (self.delete_button, "trash")): - button.setIcon(_blue_prescription_icon(kind, "#BE4657" if kind == "trash" else "#1769E8")) + button.setIcon(_blue_prescription_icon(kind, PALETTE["danger"] if kind == "trash" else PALETTE["accent"])) self._load_doctor_options() def _build_filters(self) -> QWidget: @@ -1226,7 +1227,7 @@ class PrescriptionsPage(QWidget): refresh = QPushButton("刷新") refresh.setProperty("variant", "ghost") refresh.setCursor(Qt.CursorShape.PointingHandCursor) - refresh.setIcon(_blue_prescription_icon("refresh", "#5D6B80")) + refresh.setIcon(_blue_prescription_icon("refresh", PALETTE["muted"])) refresh.setIconSize(QSize(15, 15)) refresh.clicked.connect(self.refresh) toolbar.addWidget(refresh) @@ -1287,7 +1288,7 @@ class PrescriptionsPage(QWidget): self.table.setItemDelegate(_PrescriptionInfoDelegate(self.table)) self.table.setItemDelegateForColumn(1, _PrescriptionNumberBlueDelegate(self.table)) self.table.horizontalHeader().sectionResized.connect(self._number_column_resized) - self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", "#8A97A9", 14)) + self.table.horizontalHeaderItem(0).setIcon(_blue_prescription_icon("checkbox", PALETTE["disabled"], 14)) self.table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignmentFlag.AlignCenter) self.table.itemSelectionChanged.connect(self._selection_changed) self.table.itemDoubleClicked.connect(lambda _item: self._view_selected()) @@ -1537,7 +1538,7 @@ class PrescriptionsPage(QWidget): sn_item = self.table.item(row_index, 1) if sn_item is not None: - sn_item.setForeground(QColor("#1A1C1F")) + sn_item.setForeground(QColor(PALETTE["heading"])) font = sn_item.font() font.setWeight(QFont.Weight.Normal) sn_item.setFont(font) diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index cb13eaae5..ea58bc6c2 100644 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -75,6 +75,7 @@ from PySide6.QtWidgets import ( from ...core.appointment_modes import appointment_type_description, appointment_type_value from .. import icons +from ..design_system import PALETTE, clinical_stylesheet from ..diagnosis_drawer import DailyRecordPanel from ..diagnosis_editors import FlowLayout from ..dialogs import DiagnosisDialog @@ -2020,7 +2021,7 @@ def _painted_reception_tab_icon(kind: str, size: int = 16) -> QIcon: outline (bubble / chart page / capsule / clipboard / calendar-clock). """ - return icons.icon(kind, "#5D6B80", size) + return icons.icon(kind, PALETTE["muted"], size) def _painted_reception_action_icon(kind: str, color: str, size: int = 14) -> QIcon: @@ -2882,7 +2883,7 @@ class _ReceptionSparkIcon(QWidget): del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - glyph = icons.pixmap("ai", "#1769E8", 18) + glyph = icons.pixmap("ai", PALETTE["accent"], 18) painter.drawPixmap(QRectF(0, 0, 18, 18), glyph, QRectF(glyph.rect())) painter.end() @@ -2896,9 +2897,9 @@ class _ReceptionAiSectionIcon(QWidget): #: Section tone -> (plate, glyph tint, shared glyph name). _TONES = { - "diagnosis": ("#EAF2FF", "#1769E8", "report"), - "risk": ("#EAF2FF", "#1769E8", "alert"), - "treatment": ("#EAF2FF", "#1769E8", "meds"), + "diagnosis": (PALETTE["accent_soft"], PALETTE["accent"], "report"), + "risk": (PALETTE["accent_soft"], PALETTE["accent"], "alert"), + "treatment": (PALETTE["accent_soft"], PALETTE["accent"], "meds"), } def __init__(self, tone: str, parent: QWidget | None = None) -> None: @@ -2949,9 +2950,9 @@ class _ReceptionAssistantIcon(QWidget): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#1769E8")) + painter.setBrush(QColor(PALETTE["accent"])) painter.drawRoundedRect(QRectF(1, 1, 22, 22), 4, 4) - painter.setPen(QColor("#FFFFFF")) + painter.setPen(QColor(PALETTE["surface"])) font = painter.font() font.setPixelSize(11) font.setBold(True) @@ -2975,7 +2976,7 @@ class _ReceptionSendButton(QPushButton): painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setPen( QPen( - QColor("#FFFFFF"), + QColor(PALETTE["surface"]), 1.8, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap, @@ -3053,7 +3054,7 @@ class _ReceptionDateButton(QPushButton): super().paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - color = QColor("#5D6B80") + color = QColor(PALETTE["muted"]) painter.setPen( QPen( color, @@ -3087,7 +3088,7 @@ class _ReceptionAiExpandButton(QPushButton): del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - color = QColor("#1769E8" if self.isEnabled() else "#8E8F90") + color = QColor(PALETTE["accent"] if self.isEnabled() else PALETTE["disabled"]) painter.setPen( QPen( color, @@ -3120,7 +3121,7 @@ class _ReceptionAiModelCombo(QComboBox): super().paintEvent(event) painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - color = QColor("#273244" if self.isEnabled() else "#8E8F90") + color = QColor(PALETTE["text"] if self.isEnabled() else PALETTE["disabled"]) painter.setPen( QPen( color, @@ -3162,7 +3163,7 @@ class _ReceptionAiAnalysisDialog(QDialog): self.resize(920, 760) self.setMinimumSize(720, 560) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) - self.setStyleSheet(RECEPTION_AI_DIALOG_QSS) + self.setStyleSheet(clinical_stylesheet(RECEPTION_AI_DIALOG_QSS)) root = QVBoxLayout(self) root.setContentsMargins(18, 18, 18, 18) @@ -3365,7 +3366,11 @@ class _ReceptionAiAnalysisDialog(QDialog): source_label.setTextFormat(Qt.TextFormat.PlainText) source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) source_label.setWordWrap(True) - source_label.setStyleSheet("color: #555B68; font-size: 12px; padding: 10px 14px; background: #F7F8FC; border: 1px solid #E4E8F2; border-radius: 8px;") + source_label.setStyleSheet(clinical_stylesheet( + "color: $ds_muted; font-size: 12px; padding: 10px 14px; " + "background: $ds_surface_alt; border: 1px solid $ds_line; " + "border-radius: $ds_radius_control;" + )) body_layout.addWidget(source_label) self.source_label = source_label body_layout.addStretch(1) @@ -3614,9 +3619,9 @@ class _VitalMetricIcon(QWidget): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#EAF2FF")) + painter.setBrush(QColor(PALETTE["accent_soft"])) painter.drawRoundedRect(QRectF(0, 0, 22, 22), 6, 6) - glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), "#1769E8", 15) + glyph = icons.pixmap(self._GLYPHS.get(self._kind, "pulse"), PALETTE["accent"], 15) painter.drawPixmap(QRectF(3.5, 3.5, 15, 15), glyph, QRectF(glyph.rect())) painter.end() @@ -3636,7 +3641,7 @@ class _LifestyleIcon(QWidget): del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), "#5D6B80", 16) + glyph = icons.pixmap(self._GLYPHS.get(self._kind, "exercise"), PALETTE["muted"], 16) painter.drawPixmap(QRectF(0, 0, 16, 16), glyph, QRectF(glyph.rect())) painter.end() @@ -3672,7 +3677,7 @@ class _GenderMark(QWidget): return painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - pen = QPen(QColor("#5D6B80"), 1.35) + pen = QPen(QColor(PALETTE["muted"]), 1.35) pen.setCapStyle(Qt.PenCapStyle.RoundCap) pen.setJoinStyle(Qt.PenJoinStyle.RoundJoin) painter.setPen(pen) @@ -3737,7 +3742,7 @@ class _ReceptionQueueSpinner(QWidget): del event painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) - pen = QPen(QColor("#1769E8"), 2.2) + pen = QPen(QColor(PALETTE["accent"]), 2.2) pen.setCapStyle(Qt.PenCapStyle.RoundCap) painter.setPen(pen) painter.drawArc(QRectF(2, 2, 14, 14), self._angle * 16, 250 * 16) @@ -3873,15 +3878,15 @@ class QueueRow(QWidget): painter.setRenderHint(QPainter.RenderHint.Antialiasing) rect = QRectF(self.rect()).adjusted(0.5, 0.5, -0.5, -0.5) if self._selected: - painter.setBrush(QColor("#EAF2FF")) - painter.setPen(QPen(QColor("#E5ECF6"), 1)) + painter.setBrush(QColor(PALETTE["accent_soft"])) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) else: - painter.setBrush(QColor("#FFFFFF")) - painter.setPen(QPen(QColor("#E5ECF6"), 1)) - painter.drawRoundedRect(rect, 6, 6) + painter.setBrush(QColor(PALETTE["surface"])) + painter.setPen(QPen(QColor(PALETTE["line"]), 1)) + painter.drawRoundedRect(rect, 10, 10) if self._selected: painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#1769E8")) + painter.setBrush(QColor(PALETTE["accent"])) painter.drawRoundedRect(QRectF(1.2, 1, 3.2, self.height() - 2), 1.6, 1.6) @@ -4074,7 +4079,7 @@ class ReceptionDailyRecordsPanel(DailyRecordPanel): font = item.font() font.setWeight(QFont.Weight.DemiBold if high else QFont.Weight.Normal) item.setFont(font) - item.setForeground(QBrush(QColor("#BE4B58" if high else "#273244"))) + item.setForeground(QBrush(QColor(PALETTE["danger"] if high else PALETTE["text"]))) item.setBackground( QBrush( QColor( @@ -4103,9 +4108,11 @@ class ReceptionPage(QWidget): super().__init__(parent) self.setObjectName("ReceptionPage") self.setStyleSheet( - (RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family()) - .replace("$heading_family", heading_family()) - .replace("$number_family", number_family()) + clinical_stylesheet( + (RECEPTION_QSS + RECEPTION_WORKSPACE_QSS).replace("$body_family", body_family()) + .replace("$heading_family", heading_family()) + .replace("$number_family", number_family()) + ) ) self.repository = repository self.permissions = permissions @@ -4262,7 +4269,7 @@ class ReceptionPage(QWidget): header_layout.addWidget(title) header_layout.addStretch(1) self.refresh_button = QPushButton("", header) - self.refresh_button.setIcon(icons.icon("refresh", "#5D6B80", 18)) + self.refresh_button.setIcon(icons.icon("refresh", PALETTE["muted"], 18)) self.refresh_button.setObjectName("ReceptionRefreshButton") self.refresh_button.setFixedSize(34, 32) self.refresh_button.setAccessibleName("刷新接诊台") @@ -4454,7 +4461,7 @@ class ReceptionPage(QWidget): self.video_button.clicked.connect(self._request_video) actions.addWidget(self.video_button) self.more_button = QPushButton(hero) - self.more_button.setIcon(icons.icon("more", "#5D6B80", 16)) + self.more_button.setIcon(icons.icon("more", PALETTE["muted"], 16)) self.more_button.setIconSize(QSize(16, 16)) self.more_button.setToolTip("更多操作") self.more_button.setAccessibleName("更多操作") @@ -5286,7 +5293,9 @@ class ReceptionPage(QWidget): self.ai_source_label.setTextFormat(Qt.TextFormat.PlainText) self.ai_source_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) self.ai_source_label.setWordWrap(True) - self.ai_source_label.setStyleSheet("color: #5B6474; font-size: 11px;") + self.ai_source_label.setStyleSheet(clinical_stylesheet( + "color: $ds_muted; font-size: 12px;" + )) analysis_layout.addWidget(self.ai_source_label) self.ai_detail_actions_host = QWidget(analysis_card) diff --git a/app/src/doctor_workstation/ui/patient_orders_style.py b/app/src/doctor_workstation/ui/patient_orders_style.py index 925e55d43..89d11ce25 100644 --- a/app/src/doctor_workstation/ui/patient_orders_style.py +++ b/app/src/doctor_workstation/ui/patient_orders_style.py @@ -1,119 +1,126 @@ -"""Scoped surfaces for the approved patient order-management workspace.""" - -from string import Template - -from .reception_style import body_family - - -def patient_orders_stylesheet() -> str: - return Template(_ORDERS).substitute(body=body_family()) - - -_ORDERS = """ -#PatientOrdersWorkspace { background: transparent; color: #273244; } -#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; } -#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton, -#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit, -#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit, -#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; -} -#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; } -#PatientOrdersWorkspace QFrame#OrderFilterCard, -#PatientOrdersWorkspace QFrame#OrderSummaryStrip, -#PatientOrdersWorkspace QFrame#OrderTableCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; -} -#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid #DBE5F2; - border-radius: 5px; background: #FFFFFF; color: #273244; -} -#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover { - background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; -} -#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: #DCEAFF; } -#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: #75A5F0; } -#PatientOrdersWorkspace QPushButton#OrderSearchButton, -#PatientOrdersWorkspace QPushButton#OrderDetailButton { - color: #FFFFFF; background: #1769E8; border-color: #1769E8; -} -#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover, -#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: #155BCC; border-color: #155BCC; } -#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled { - color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2; -} -#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox, -#PatientOrdersWorkspace QDateEdit { - min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px; - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px; - selection-background-color: #DCEAFF; selection-color: #273244; -} -#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus, -#PatientOrdersWorkspace QDateEdit:focus { border-color: #75A5F0; } -#PatientOrdersWorkspace QLineEdit QToolButton { - min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent; -} -#PatientOrdersWorkspace QComboBox { padding-right: 30px; } -#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; } -#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; } -#PatientOrdersWorkspace QComboBox QAbstractItemView { - font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6; -} -#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } -#PatientOrdersWorkspace QDateEdit { padding-right: 26px; } -#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; } -#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; } -#PatientOrdersWorkspace QDateEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; } -#PatientOrdersWorkspace QCalendarWidget { - font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244; -} -#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; } -#PatientOrdersWorkspace QCalendarWidget QToolButton { - min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent; - font-family: "$body"; font-size: 13px; color: #273244; -} -#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: #EAF2FF; } -#PatientOrdersWorkspace QCalendarWidget QAbstractItemView { - font-family: "$body"; font-size: 13px; background: #FFFFFF; alternate-background-color: #FFFFFF; - color: #273244; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0; -} -#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; } -#PatientOrdersWorkspace QCheckBox::indicator { - width: 15px; height: 15px; border: 1px solid #C5D5EB; border-radius: 3px; background: #FFFFFF; -} -#PatientOrdersWorkspace QCheckBox::indicator:checked { background: #1769E8; border-color: #1769E8; } -#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: #75A5F0; } -#PatientOrdersWorkspace QCheckBox:focus { color: #1555B6; } -#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; } -#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: #DBE5F2; } -#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: #5D6B80; font-size: 13px; } -#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: #273244; font-size: 18px; font-weight: 500; } -#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: #1769E8; } -#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; } -#PatientOrdersWorkspace QTableWidget#OrderTable { - border: 1px solid #E6EDF6; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF; - selection-background-color: #F5F8FF; selection-color: #273244; gridline-color: #E6EDF6; -} -#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; } -#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section { - min-height: 44px; padding: 0 16px; background: #F8FAFD; color: #5D6B80; - border: 0; border-bottom: 1px solid #E1E9F4; - font-family: "$body"; font-size: 13px; font-weight: 400; -} -#PatientOrdersWorkspace QWidget#OrderActionBar { background: #FFFFFF; } -#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; } -#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; } -#PatientOrdersWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; } -#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu { - font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; padding: 5px; -} -#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; } -#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: #1555B6; background: #EAF2FF; } -#PatientOrdersWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#PatientOrdersWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#PatientOrdersWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } -#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; } -#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; } -""" +"""Scoped surfaces for the approved patient order-management workspace.""" + +from string import Template + +from .design_system import clinical_stylesheet +from .reception_style import body_family + + +def patient_orders_stylesheet() -> str: + return clinical_stylesheet(Template(_ORDERS).safe_substitute(body=body_family())) + + +_ORDERS = """ +#PatientOrdersWorkspace { background: transparent; color: $ds_text; } +#OrderWorkspaceContent, #OrderWorkspaceScroll { background: transparent; border: 0; } +#PatientOrdersWorkspace QLabel, #PatientOrdersWorkspace QPushButton, +#PatientOrdersWorkspace QToolButton, #PatientOrdersWorkspace QLineEdit, +#PatientOrdersWorkspace QComboBox, #PatientOrdersWorkspace QDateEdit, +#PatientOrdersWorkspace QCheckBox, #PatientOrdersWorkspace QTableWidget { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; +} +#PatientOrdersWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; } +#PatientOrdersWorkspace QFrame#OrderFilterCard, +#PatientOrdersWorkspace QFrame#OrderTableCard { + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PatientOrdersWorkspace QFrame#OrderSummaryStrip { background: transparent; border: 0; } +#PatientOrdersWorkspace QPushButton, #PatientOrdersWorkspace QToolButton { + min-height: 38px; max-height: 38px; padding: 0 16px; border: 1px solid transparent; + border-radius: $ds_radius_control; background: $ds_surface_alt; color: $ds_text; +} +#PatientOrdersWorkspace QPushButton:hover, #PatientOrdersWorkspace QToolButton:hover { + background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; +} +#PatientOrdersWorkspace QPushButton:pressed, #PatientOrdersWorkspace QToolButton:pressed { background: $ds_accent_soft; } +#PatientOrdersWorkspace QPushButton:focus, #PatientOrdersWorkspace QToolButton:focus { border-color: $ds_focus; } +#PatientOrdersWorkspace QPushButton#OrderSearchButton, +#PatientOrdersWorkspace QPushButton#OrderDetailButton { + color: $ds_surface; background: $ds_accent; border-color: $ds_accent; +} +#PatientOrdersWorkspace QPushButton#OrderSearchButton:hover, +#PatientOrdersWorkspace QPushButton#OrderDetailButton:hover { background: $ds_accent_hover; border-color: $ds_accent_hover; } +#PatientOrdersWorkspace QPushButton#OrderSearchButton:pressed, +#PatientOrdersWorkspace QPushButton#OrderDetailButton:pressed { background: $ds_accent_pressed; border-color: $ds_accent_pressed; } +#PatientOrdersWorkspace QPushButton#OrderSearchButton:focus, +#PatientOrdersWorkspace QPushButton#OrderDetailButton:focus { border-color: $ds_focus; } +#PatientOrdersWorkspace QPushButton:disabled, #PatientOrdersWorkspace QToolButton:disabled, +#PatientOrdersWorkspace QPushButton#OrderSearchButton:disabled, +#PatientOrdersWorkspace QPushButton#OrderDetailButton:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; +} +#PatientOrdersWorkspace QLineEdit, #PatientOrdersWorkspace QComboBox, +#PatientOrdersWorkspace QDateEdit { + min-height: 38px; max-height: 38px; padding: 0 10px; font-size: 13px; + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; +} +#PatientOrdersWorkspace QLineEdit:focus, #PatientOrdersWorkspace QComboBox:focus, +#PatientOrdersWorkspace QDateEdit:focus { border-color: $ds_focus; } +#PatientOrdersWorkspace QLineEdit QToolButton { + min-height: 0; max-height: 24px; min-width: 0; border: 0; padding: 0; background: transparent; +} +#PatientOrdersWorkspace QComboBox { padding-right: 30px; } +#PatientOrdersWorkspace QComboBox::drop-down { border: 0; width: 28px; background: transparent; } +#PatientOrdersWorkspace QComboBox::down-arrow { image: none; width: 0; height: 0; } +#PatientOrdersWorkspace QComboBox QAbstractItemView { + font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent; +} +#PatientOrdersWorkspace QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } +#PatientOrdersWorkspace QDateEdit { padding-right: 26px; } +#PatientOrdersWorkspace QDateEdit::drop-down { border: 0; width: 24px; background: transparent; } +#PatientOrdersWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; } +#PatientOrdersWorkspace QDateEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; } +#PatientOrdersWorkspace QCalendarWidget { + font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text; +} +#PatientOrdersWorkspace QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; } +#PatientOrdersWorkspace QCalendarWidget QToolButton { + min-height: 28px; max-height: 28px; padding: 0 8px; border: 0; background: transparent; + font-family: "$body"; font-size: 13px; color: $ds_text; +} +#PatientOrdersWorkspace QCalendarWidget QToolButton:hover { background: $ds_accent_soft; } +#PatientOrdersWorkspace QCalendarWidget QAbstractItemView { + font-family: "$body"; font-size: 13px; background: $ds_surface; alternate-background-color: $ds_surface; + color: $ds_text; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0; +} +#PatientOrdersWorkspace QCheckBox { spacing: 9px; font-size: 13px; } +#PatientOrdersWorkspace QCheckBox::indicator { + width: 15px; height: 15px; border: 1px solid $ds_line_strong; border-radius: 3px; background: $ds_surface; +} +#PatientOrdersWorkspace QCheckBox::indicator:checked { background: $ds_accent; border-color: $ds_accent; } +#PatientOrdersWorkspace QCheckBox::indicator:hover { border-color: $ds_focus; } +#PatientOrdersWorkspace QCheckBox:focus { color: $ds_accent; } +#PatientOrdersWorkspace QFrame#OrderMetricCell { background: transparent; border: 0; } +#PatientOrdersWorkspace QFrame#OrderMetricDivider { border: 0; background: $ds_line; } +#PatientOrdersWorkspace QLabel[orderMetricCaption="true"] { color: $ds_muted; font-size: 13px; } +#PatientOrdersWorkspace QLabel[orderMetricValue="true"] { color: $ds_text; font-size: 18px; font-weight: 500; } +#PatientOrdersWorkspace QLabel#OrderAmountMetric { color: $ds_accent; } +#PatientOrdersWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; } +#PatientOrdersWorkspace QTableWidget#OrderTable { + border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line; +} +#PatientOrdersWorkspace QTableWidget#OrderTable::item { padding: 0; border: 0; } +#PatientOrdersWorkspace QTableWidget#OrderTable QHeaderView::section { + min-height: 44px; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-bottom: 1px solid $ds_line; + font-family: "$body"; font-size: 13px; font-weight: 400; +} +#PatientOrdersWorkspace QWidget#OrderActionBar { background: $ds_surface; } +#PatientOrdersWorkspace QToolButton#OrderActionButton { padding-right: 28px; } +#PatientOrdersWorkspace QToolButton#OrderActionButton::menu-indicator { image: none; width: 0; height: 0; } +#PatientOrdersWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; } +#PatientOrdersWorkspace QMenu, QMenu#OrderActionMenu { + font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; padding: 5px; +} +#PatientOrdersWorkspace QMenu::item, QMenu#OrderActionMenu::item { padding: 8px 24px; } +#PatientOrdersWorkspace QMenu::item:selected, QMenu#OrderActionMenu::item:selected { color: $ds_accent; background: $ds_accent_soft; } +#PatientOrdersWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#PatientOrdersWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#PatientOrdersWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } +#PatientOrdersWorkspace QScrollBar::add-line, #PatientOrdersWorkspace QScrollBar::sub-line { width: 0; height: 0; } +#PatientOrdersWorkspace QScrollBar::add-page, #PatientOrdersWorkspace QScrollBar::sub-page { background: transparent; } +""" diff --git a/app/src/doctor_workstation/ui/patient_progress_style.py b/app/src/doctor_workstation/ui/patient_progress_style.py index b9ba83397..906f34f9d 100644 --- a/app/src/doctor_workstation/ui/patient_progress_style.py +++ b/app/src/doctor_workstation/ui/patient_progress_style.py @@ -1,54 +1,55 @@ -"""Local typography and surfaces for the approved consultation-progress page.""" - -from string import Template - -from .reception_style import body_family - - -def patient_progress_stylesheet() -> str: - return Template(_PROGRESS).substitute(body=body_family()) - - -_PROGRESS = """ -#PatientProgressWorkspace { background: transparent; color: #273244; } -#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; } -#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton, -#PatientProgressWorkspace QTableWidget { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; -} -#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: #5D6B80; } -#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; } -#PatientProgressWorkspace QLabel#EmptyStateGlyph { - font-size: 24px; color: #1769E8; background: #F2F7FF; - border: 1px solid #DBE5F2; border-radius: 22px; -} -#PatientProgressWorkspace QFrame#ProgressOverviewCard, -#PatientProgressWorkspace QFrame#ProgressScheduleCard, -#PatientProgressWorkspace QFrame#ProgressQueueCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; -} -#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; } -#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: #DBE5F2; border: 0; } -#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: #273244; } -#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: #1769E8; } -#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; } -#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; } -#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: #EAF2FF; } -#PatientProgressWorkspace QTableWidget#ProgressScheduleTable, -#PatientProgressWorkspace QTableWidget#ProgressQueueTable { - border: 0; border-radius: 0; background: #FFFFFF; alternate-background-color: #FFFFFF; - selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6; -} -#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; } -#PatientProgressWorkspace QHeaderView::section { - min-height: 0; padding: 0 16px; background: #F5F8FD; color: #5D6B80; - border: 0; border-bottom: 1px solid #E1E9F4; - font-family: "$body"; font-size: 13px; font-weight: 400; -} -#PatientProgressWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; } -#PatientProgressWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#PatientProgressWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#PatientProgressWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } -#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; } -#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; } -""" +"""Local typography and surfaces for the approved consultation-progress page.""" + +from string import Template + +from .design_system import clinical_stylesheet +from .reception_style import body_family + + +def patient_progress_stylesheet() -> str: + return clinical_stylesheet(Template(_PROGRESS).safe_substitute(body=body_family())) + + +_PROGRESS = """ +#PatientProgressWorkspace { background: transparent; color: $ds_text; } +#ProgressWorkspaceContent, #ProgressWorkspaceScroll { background: transparent; border: 0; } +#PatientProgressWorkspace QLabel, #PatientProgressWorkspace QPushButton, +#PatientProgressWorkspace QTableWidget { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; +} +#PatientProgressWorkspace QLabel[role="muted"] { font-size: 13px; color: $ds_muted; } +#PatientProgressWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; } +#PatientProgressWorkspace QLabel#EmptyStateGlyph { + font-size: 24px; color: $ds_accent; background: $ds_surface_alt; + border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PatientProgressWorkspace QFrame#ProgressScheduleCard, +#PatientProgressWorkspace QFrame#ProgressQueueCard { + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PatientProgressWorkspace QFrame#ProgressOverviewCard { background: transparent; border: 0; } +#PatientProgressWorkspace QFrame#ProgressMetricCell { background: transparent; border: 0; } +#PatientProgressWorkspace QFrame#ProgressMetricDivider { background: $ds_line; border: 0; } +#PatientProgressWorkspace QLabel[progressMetricValue="true"] { font-size: 18px; font-weight: 500; color: $ds_text; } +#PatientProgressWorkspace QLabel#ProgressTotalMetric { color: $ds_accent; } +#PatientProgressWorkspace QSplitter#ProgressSplitter { background: transparent; } +#PatientProgressWorkspace QSplitter#ProgressSplitter::handle { background: transparent; } +#PatientProgressWorkspace QSplitter#ProgressSplitter::handle:hover { background: $ds_accent_soft; } +#PatientProgressWorkspace QTableWidget#ProgressScheduleTable, +#PatientProgressWorkspace QTableWidget#ProgressQueueTable { + border: 0; border-radius: 0; background: $ds_surface; alternate-background-color: $ds_surface; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line; +} +#PatientProgressWorkspace QTableWidget::item { border: 0; padding: 0; } +#PatientProgressWorkspace QHeaderView::section { + min-height: 0; padding: 0 16px; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-bottom: 1px solid $ds_line; + font-family: "$body"; font-size: 13px; font-weight: 400; +} +#PatientProgressWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; } +#PatientProgressWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#PatientProgressWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#PatientProgressWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } +#PatientProgressWorkspace QScrollBar::add-line, #PatientProgressWorkspace QScrollBar::sub-line { width: 0; height: 0; } +#PatientProgressWorkspace QScrollBar::add-page, #PatientProgressWorkspace QScrollBar::sub-page { background: transparent; } +""" diff --git a/app/src/doctor_workstation/ui/patients_style.py b/app/src/doctor_workstation/ui/patients_style.py index 8273fb598..545c4e680 100644 --- a/app/src/doctor_workstation/ui/patients_style.py +++ b/app/src/doctor_workstation/ui/patients_style.py @@ -1,141 +1,154 @@ -"""Scoped technology-blue surfaces for the approved patient-list workspace.""" - -from string import Template - -from .reception_style import body_family, heading_family - - -def patients_chrome_stylesheet() -> str: - return Template(_CHROME).substitute(body=body_family(), heading=heading_family()) - - -def patient_list_stylesheet() -> str: - return Template(_LIST).substitute(body=body_family()) - - -_CHROME = """ -#PatientsPage { background: #F3F7FD; } -#PatientsPage QWidget#PageHeader QLabel { - font-family: "$body"; font-size: 13px; font-weight: 400; color: #5D6B80; -} -#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] { - font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F; -} -#PatientsPage QPushButton#PatientRefreshButton { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; - min-height: 38px; max-height: 38px; padding: 0 20px; - border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF; -} -#PatientsPage QPushButton#PatientRefreshButton:hover { background: #F2F7FF; border-color: #B6CDEE; } -#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; } -#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; - min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px; - border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; -} -#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected { - color: #1769E8; border-bottom-color: #1769E8; background: transparent; -} -#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: #1769E8; background: #EAF2FF; } -""" - -_LIST = """ -#PatientListWorkspace { background: transparent; color: #273244; } -#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; } -#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton, -#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit, -#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit, -#PatientSearchToolbar QPushButton { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; -} -#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] { - color: #5D6B80; font-size: 13px; -} -#PatientListWorkspace QFrame#PatientFilterCard, -#PatientListWorkspace QFrame#PatientSummaryStrip, -#PatientListWorkspace QFrame#PatientListCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; -} -#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; - border: 1px solid #DBE5F2; border-radius: 5px; background: #FFFFFF; -} -#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover { - color: #1555B6; background: #F2F7FF; border-color: #B6CDEE; -} -#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: #DCEAFF; } -#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: #75A5F0; } -#PatientSearchToolbar QPushButton#PatientSearchButton { - min-height: 38px; max-height: 38px; color: #FFFFFF; background: #1769E8; border-color: #1769E8; -} -#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: #155BCC; } -#PatientSearchToolbar QLineEdit { - min-height: 38px; max-height: 38px; padding: 0 8px; background: #FFFFFF; - border: 1px solid #DBE5F2; border-radius: 5px; selection-background-color: #DCEAFF; -} -#PatientSearchToolbar QLineEdit:focus { border-color: #75A5F0; } -#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; } -#PatientListWorkspace QPushButton[patientStatusChip="true"] { - min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px; - color: #273244; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; -} -#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked { - color: #1769E8; border-bottom-color: #1769E8; background: transparent; -} -#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: #1769E8; background: #F2F7FF; } -#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; } -#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked, -#PatientListWorkspace QPushButton#PatientCustomDateButton:checked { - color: #FFFFFF; background: #1769E8; border: 1px solid #1769E8; -} -#PatientListWorkspace QDateEdit { - min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px; - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 5px; - selection-background-color: #DCEAFF; -} -#PatientListWorkspace QDateEdit:focus { border-color: #75A5F0; } -#PatientListWorkspace QDateEdit:disabled { - color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; -} -#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; } -#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; } -#PatientListWorkspace QPushButton[summaryCard="true"] { - min-height: 64px; max-height: 64px; padding: 0; background: transparent; border: 0; border-radius: 5px; -} -#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: #F2F7FF; } -#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: #E1E9F4; } -#PatientListWorkspace QWidget#PatientListHeading { background: transparent; } -#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: #273244; } -#PatientListWorkspace QTableWidget#PatientTable { - background: #FFFFFF; alternate-background-color: #FFFFFF; border: 0; border-radius: 0; - selection-background-color: #EAF2FF; selection-color: #273244; gridline-color: #E6EDF6; -} -#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; } -#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section { - min-height: 41px; padding: 0 10px; background: #F5F8FD; color: #5D6B80; - border: 0; border-top: 1px solid #E6EDF6; border-bottom: 1px solid #E1E9F4; - font-family: "$body"; font-size: 13px; font-weight: 400; -} -#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; } -#PatientListWorkspace QPushButton[rowAction="true"], -#PatientListWorkspace QToolButton#RowActionsMore { - min-height: 28px; max-height: 28px; padding: 0 5px; border: 0; - border-radius: 4px; background: transparent; color: #1769E8; font-size: 13px; -} -#PatientListWorkspace QToolButton#RowActionsMore { color: #273244; padding-right: 16px; } -#PatientListWorkspace QPushButton[rowAction="true"]:hover, -#PatientListWorkspace QToolButton#RowActionsMore:hover { background: #DCEAFF; } -#PatientListWorkspace QMenu { background: #FFFFFF; color: #273244; border: 1px solid #DBE5F2; padding: 4px; } -#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; } -#PatientListWorkspace QMenu::item:selected { background: #EAF2FF; color: #1555B6; } -#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator { - width: 13px; height: 13px; background: #FFFFFF; border: 1px solid #CBDAED; border-radius: 3px; -} -#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: #1769E8; border-color: #1769E8; } -#PatientListWorkspace QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; } -#PatientListWorkspace QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#PatientListWorkspace QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#PatientListWorkspace QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } -#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; } -#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; } -""" +"""Quiet clinical surfaces for the patient-list workspace.""" + +from string import Template + +from .design_system import clinical_stylesheet +from .reception_style import body_family, heading_family + + +def patients_chrome_stylesheet() -> str: + return clinical_stylesheet(Template(_CHROME).safe_substitute(body=body_family(), heading=heading_family())) + + +def patient_list_stylesheet() -> str: + return clinical_stylesheet(Template(_LIST).safe_substitute(body=body_family())) + + +_CHROME = """ +#PatientsPage { background: $ds_canvas; } +#PatientsPage QWidget#PageHeader QLabel { + font-family: "$body"; font-size: 13px; font-weight: 400; color: $ds_muted; +} +#PatientsPage QWidget#PageHeader QLabel[role="pageTitle"] { + font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading; +} +#PatientsPage QPushButton#PatientRefreshButton { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; + min-height: 38px; max-height: 38px; padding: 0 20px; + border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt; +} +#PatientsPage QPushButton#PatientRefreshButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; } +#PatientsPage QPushButton#PatientRefreshButton:pressed { background: $ds_accent_soft; } +#PatientsPage QPushButton#PatientRefreshButton:focus { border-color: $ds_focus; } +#PatientsPage QPushButton#PatientRefreshButton:disabled { color: $ds_disabled; background: $ds_disabled_surface; } +#PatientsPage QTabWidget#PatientWorkspaceTabs::pane { border: 0; background: transparent; top: 0; } +#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; + min-width: 84px; min-height: 42px; padding: 0 10px; margin-right: 22px; + border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; +} +#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:selected { + color: $ds_accent; border-bottom-color: $ds_accent; background: transparent; +} +#PatientsPage QTabWidget#PatientWorkspaceTabs > QTabBar::tab:hover { color: $ds_accent; background: $ds_accent_soft; } +""" + +_LIST = """ +#PatientListWorkspace { background: transparent; color: $ds_text; } +#PatientWorkspaceContent, #PatientWorkspaceScroll { background: transparent; border: 0; } +#PatientListWorkspace QLabel, #PatientListWorkspace QPushButton, +#PatientListWorkspace QToolButton, #PatientListWorkspace QDateEdit, +#PatientListWorkspace QTableWidget, #PatientSearchToolbar QLineEdit, +#PatientSearchToolbar QPushButton { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; +} +#PatientListWorkspace QLabel[role="muted"], #PatientListWorkspace QLabel[filterLabel="true"] { + color: $ds_muted; font-size: 13px; +} +#PatientListWorkspace QFrame#PatientFilterCard, +#PatientListWorkspace QFrame#PatientListCard { + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PatientListWorkspace QFrame#PatientSummaryStrip { background: transparent; border: 0; } +#PatientListWorkspace QPushButton, #PatientSearchToolbar QPushButton { + min-height: 38px; max-height: 38px; padding: 0 16px; + border: 1px solid transparent; border-radius: $ds_radius_control; background: $ds_surface_alt; +} +#PatientListWorkspace QPushButton:hover, #PatientSearchToolbar QPushButton:hover { + color: $ds_accent; background: $ds_surface_alt; border-color: $ds_line_strong; +} +#PatientListWorkspace QPushButton:pressed, #PatientSearchToolbar QPushButton:pressed { background: $ds_accent_soft; } +#PatientListWorkspace QPushButton:focus, #PatientSearchToolbar QPushButton:focus { border-color: $ds_focus; } +#PatientSearchToolbar QPushButton#PatientSearchButton { + min-height: 38px; max-height: 38px; color: $ds_surface; background: $ds_accent; border-color: $ds_accent; +} +#PatientSearchToolbar QPushButton#PatientSearchButton:hover { background: $ds_accent_hover; } +#PatientSearchToolbar QPushButton#PatientSearchButton:pressed { background: $ds_accent_pressed; } +#PatientSearchToolbar QPushButton#PatientSearchButton:focus { border-color: $ds_focus; } +#PatientSearchToolbar QLineEdit { + min-height: 38px; max-height: 38px; padding: 0 8px; background: $ds_surface; + border: 1px solid $ds_line; border-radius: $ds_radius_control; selection-background-color: $ds_accent_soft; +} +#PatientSearchToolbar QLineEdit:focus { border-color: $ds_focus; } +#PatientSearchToolbar QLineEdit QToolButton { border: 0; padding: 0; background: transparent; } +#PatientListWorkspace QPushButton[patientStatusChip="true"] { + min-height: 44px; max-height: 44px; padding: 0 16px; font-size: 13px; + color: $ds_text; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: transparent; +} +#PatientListWorkspace QPushButton[patientStatusChip="true"]:checked { + color: $ds_accent; border-bottom-color: $ds_accent; background: transparent; +} +#PatientListWorkspace QPushButton[patientStatusChip="true"]:hover { color: $ds_accent; background: $ds_surface_alt; } +#PatientListWorkspace QPushButton[patientStatusChip="true"]:focus { background: $ds_accent_soft; } +#PatientListWorkspace QPushButton[patientQuickDate="true"] { padding: 0 12px; font-size: 13px; } +#PatientListWorkspace QPushButton[patientQuickDate="true"]:checked, +#PatientListWorkspace QPushButton#PatientCustomDateButton:checked { + color: $ds_accent; background: $ds_accent_soft; border: 1px solid transparent; font-weight: 600; +} +#PatientListWorkspace QPushButton[patientQuickDate="true"]:focus, +#PatientListWorkspace QPushButton#PatientCustomDateButton:focus { border-color: $ds_focus; } +#PatientListWorkspace QDateEdit { + min-height: 38px; max-height: 38px; padding: 0 8px; font-size: 13px; + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_control; + selection-background-color: $ds_accent_soft; +} +#PatientListWorkspace QDateEdit:focus { border-color: $ds_focus; } +#PatientListWorkspace QDateEdit:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; +} +#PatientListWorkspace QDateEdit::drop-down { border: 0; width: 20px; background: transparent; } +#PatientListWorkspace QDateEdit::down-arrow { image: none; width: 0; height: 0; } +#PatientListWorkspace QPushButton[summaryCard="true"] { + min-height: 64px; max-height: 64px; padding: 0; background: transparent; + border: 1px solid transparent; border-radius: $ds_radius_control; +} +#PatientListWorkspace QPushButton[summaryCard="true"]:hover { background: $ds_surface_alt; } +#PatientListWorkspace QPushButton[summaryCard="true"]:focus { border-color: $ds_focus; } +#PatientListWorkspace QFrame#PatientSummaryDivider { border: 0; background: $ds_line; } +#PatientListWorkspace QWidget#PatientListHeading { background: transparent; } +#PatientListWorkspace QLabel[role="sectionTitle"] { font-size: 14px; font-weight: 600; color: $ds_text; } +#PatientListWorkspace QTableWidget#PatientTable { + background: $ds_surface; alternate-background-color: $ds_surface; border: 0; border-radius: 0; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line; +} +#PatientListWorkspace QTableWidget#PatientTable::item { padding: 0; border: 0; } +#PatientListWorkspace QTableWidget#PatientTable QHeaderView::section { + min-height: 41px; padding: 0 10px; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-top: 1px solid $ds_line; border-bottom: 1px solid $ds_line; + font-family: "$body"; font-size: 13px; font-weight: 400; +} +#PatientListWorkspace QWidget#RowActions, #PatientListWorkspace QWidget#PatientSelectorHost { background: transparent; } +#PatientListWorkspace QPushButton[rowAction="true"], +#PatientListWorkspace QToolButton#RowActionsMore { + min-height: 28px; max-height: 28px; padding: 0 5px; border: 1px solid transparent; + border-radius: $ds_radius_small; background: transparent; color: $ds_accent; font-size: 13px; +} +#PatientListWorkspace QToolButton#RowActionsMore { color: $ds_text; padding-right: 16px; } +#PatientListWorkspace QPushButton[rowAction="true"]:hover, +#PatientListWorkspace QToolButton#RowActionsMore:hover { background: $ds_accent_soft; } +#PatientListWorkspace QPushButton[rowAction="true"]:focus, +#PatientListWorkspace QToolButton#RowActionsMore:focus { border-color: $ds_focus; } +#PatientListWorkspace QMenu { background: $ds_surface; color: $ds_text; border: 1px solid $ds_line; padding: 4px; } +#PatientListWorkspace QMenu::item { padding: 7px 22px; font-size: 13px; } +#PatientListWorkspace QMenu::item:selected { background: $ds_accent_soft; color: $ds_accent; } +#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator { + width: 13px; height: 13px; background: $ds_surface; border: 1px solid $ds_line_strong; border-radius: 3px; +} +#PatientListWorkspace QCheckBox[patientSelector="true"]::indicator:checked { background: $ds_accent; border-color: $ds_accent; } +#PatientListWorkspace QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; } +#PatientListWorkspace QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#PatientListWorkspace QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#PatientListWorkspace QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } +#PatientListWorkspace QScrollBar::add-line, #PatientListWorkspace QScrollBar::sub-line { width: 0; height: 0; } +#PatientListWorkspace QScrollBar::add-page, #PatientListWorkspace QScrollBar::sub-page { background: transparent; } +""" diff --git a/app/src/doctor_workstation/ui/prescription_library_style.py b/app/src/doctor_workstation/ui/prescription_library_style.py index 33255224b..3d018330e 100644 --- a/app/src/doctor_workstation/ui/prescription_library_style.py +++ b/app/src/doctor_workstation/ui/prescription_library_style.py @@ -1,410 +1,419 @@ -"""Local technology-blue rendering for the approved prescription library.""" - -from __future__ import annotations - -from collections.abc import Iterable, Sequence -from string import Template -from typing import Any - -from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer -from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter -from PySide6.QtWidgets import ( - QComboBox, - QPushButton, - QStyle, - QStyledItemDelegate, - QToolTip, - QWidget, -) - -from .reception_style import body_family, heading_family -from .widgets import SortableTable, TableColumn, first_value - - -def library_stylesheet() -> str: - return Template(_LIBRARY).substitute(body=body_family(), heading=heading_family()) - - -def _library_icon(kind: str, color: str = "#1769E8", size: int = 15) -> QIcon: - # Defer the page helper lookup so importing this module alone does not - # recurse through pages.__init__ and the library page's own style import. - from .pages.prescriptions import _painted_icon - - result = QIcon() - for mode, tint in ( - (QIcon.Mode.Normal, color), - (QIcon.Mode.Active, color), - (QIcon.Mode.Selected, color), - (QIcon.Mode.Disabled, "#A4ADBA"), - ): - pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size)) - for state in (QIcon.State.Off, QIcon.State.On): - result.addPixmap(pixmap, mode, state) - return result - - -class LibraryComboBox(QComboBox): - """Keep native combo interaction while painting the local caret.""" - - def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual - super().paintEvent(event) - painter = QPainter(self) - try: - rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14) - mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled - _library_icon("chevron_down", "#5D6B80", 14).paint(painter, rect.toRect(), mode=mode) - finally: - painter.end() - - -class LibraryTable(SortableTable): - """Fit readable columns while preserving actions and selected template IDs.""" - - _FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2)) - - def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None: - super().__init__(columns, parent) - self.horizontalHeader().setStretchLastSection(False) - self._minimum_widths = tuple(column.width for column in self.columns) - self._manual_widths: dict[int, int] = {} - self._fitting_columns = False - self._fit_timer = QTimer(self) - self._fit_timer.setSingleShot(True) - self._fit_timer.timeout.connect(self._fit_columns) - self.horizontalHeader().sectionResized.connect(self._column_resized) - self.viewport().installEventFilter(self) - - def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 - if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}: - self._schedule_column_fit() - return super().eventFilter(watched, event) - - def _schedule_column_fit(self) -> None: - if not self._fit_timer.isActive(): - self._fit_timer.start(0) - - def _column_resized(self, column: int, _old_size: int, size: int) -> None: - if self._fitting_columns: - return - self._manual_widths[column] = max(self._minimum_widths[column], size) - self._schedule_column_fit() - - def _fit_columns(self) -> None: - widths = [self._manual_widths.get(column, minimum) - for column, minimum in enumerate(self._minimum_widths)] - extra = max(0, self.viewport().width() - sum(widths)) - flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS - if column not in self._manual_widths] - # If every text column was manually sized, keep those preferences as - # minimums and let the herb preview absorb any remaining wide-screen space. - flexible = flexible or [(4, 1)] - total_weight = sum(weight for _column, weight in flexible) - for column, weight in flexible: - widths[column] += extra * weight // total_weight - widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths)) - if widths == [self.columnWidth(column) for column in range(self.columnCount())]: - return - self._fitting_columns = True - try: - for column, width in enumerate(widths): - self.setColumnWidth(column, width) - finally: - self._fitting_columns = False - - def set_rows(self, rows: Iterable[Any]) -> None: - selected_id = first_value(self.current_data(), "id", "template_id", default=None) - super().set_rows(rows) - # The shared table restores an unsorted row index after enabling sort. - # Locate the same source object in the finished visual order instead. - if selected_id is not None: - for row_index in range(self.rowCount()): - item = self.item(row_index, 0) - row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None - row_id = first_value(row, "id", "template_id", default=None) - if row_id is not None and str(row_id) == str(selected_id): - self.selectRow(row_index) - return - self.clearSelection() - self.setCurrentCell(-1, -1) - - def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802 - super().setCellWidget(row, column, widget) - if widget is None or column != 9: - return - widget.setObjectName("PrescriptionLibraryTableCellHost") - widget.setAutoFillBackground(False) - glyphs = { - "查看处方模板": "eye", - "AI 解释": "spark", - "编辑处方模板": "pencil", - "删除处方模板": "trash", - } - for button in widget.findChildren(QPushButton): - if not button.property("rowAction"): - continue - glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip()) - if glyph is not None: - color = "#BE4657" if button.property("danger") else "#1769E8" - button.setIcon(_library_icon(glyph, color, button.iconSize().width())) - - -def _library_font(size: int = 14, *, medium: bool = False) -> QFont: - font = QFont(heading_family() if medium else body_family()) - font.setPixelSize(size) - font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal) - return font - - -def _elide(text: str, metrics: QFontMetrics, width: int) -> str: - return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width)) - - -def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]: - """Wrap between complete herb entries; elide only the displayed lines.""" - entries = text.split("、") - first = entries[0] - next_index = 1 - while next_index < min(2, len(entries)): - candidate = first + "、" + entries[next_index] - if metrics.horizontalAdvance(candidate) > width: - break - first = candidate - next_index += 1 - lines = [_elide(first, metrics, width)] - if next_index < len(entries): - lines.append(_elide("、".join(entries[next_index:]), metrics, width)) - return lines - - -def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]: - if metrics.horizontalAdvance(text) <= width: - return [text] - split = 1 - while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width: - split += 1 - return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)] - - -class LibraryItemDelegate(QStyledItemDelegate): - """Paint the ten existing columns without changing display or source roles.""" - - def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802 - size = super().sizeHint(option, index) - size.setHeight(78) - return size - - def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802 - if event is not None and index.isValid() and index.column() != 9: - text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole) - if text: - QToolTip.showText(event.globalPos(), str(text), view) - return True - return super().helpEvent(event, view, option, index) - - @staticmethod - def _paint_lines( - painter: QPainter, - rect: QRectF, - lines: list[str], - *, - secondary_muted: bool = False, - ) -> None: - line_height = 26 - top = rect.center().y() - len(lines) * line_height / 2 - for line_index, line in enumerate(lines): - if secondary_muted and line_index: - painter.setFont(_library_font(13)) - painter.setPen(QColor("#5D6B80")) - line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height) - painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line) - - def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None: - painter.save() - try: - painter.setClipRect(option.rect) - selected = bool(option.state & QStyle.StateFlag.State_Selected) - hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) - background = "#F2F7FF" if selected else "#F8FAFE" if hovered else "#FFFFFF" - painter.fillRect(option.rect, QColor(background)) - painter.setPen(QColor("#E6EDF6")) - painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) - if selected and index.column() == 0: - stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1) - painter.fillRect(stripe, QColor("#1769E8")) - if option.state & QStyle.StateFlag.State_HasFocus: - painter.setPen(QColor("#75A5F0")) - painter.setBrush(Qt.BrushStyle.NoBrush) - painter.drawRect(option.rect.adjusted(1, 1, -2, -2)) - - column = index.column() - if column == 9: - return - rect = QRectF(option.rect.adjusted(12, 0, -12, -1)) - if rect.width() <= 0: - return - value = index.data(Qt.ItemDataRole.DisplayRole) - text = "" if value is None else str(value) - font = _library_font(medium=column == 1) - painter.setFont(font) - painter.setPen(QColor("#273244")) - metrics = QFontMetrics(font) - width = int(rect.width()) - - if column == 2: - painter.setFont(_library_font(13)) - metrics = painter.fontMetrics() - label = _elide(text, metrics, width - 12) - pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14) - pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24) - painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) - painter.setPen(Qt.PenStyle.NoPen) - painter.setBrush(QColor("#EAF2FF")) - painter.drawRoundedRect(pill, 4, 4) - painter.setPen(QColor("#1769E8")) - painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label) - elif column == 6: - glyph = "users" if text == "所有人可见" else "lock" - icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14) - _library_icon(glyph, "#5D6B80", 14).paint(painter, icon_rect.toRect()) - label_rect = rect.adjusted(22, 0, 0, 0) - painter.drawText( - label_rect, - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, - _elide(text, metrics, int(label_rect.width())), - ) - elif column == 4: - self._paint_lines(painter, rect, _herb_lines(text, metrics, width)) - elif column == 8: - parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1) - lines = [_elide(parts[0], metrics, width)] - if len(parts) > 1: - lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width)) - self._paint_lines(painter, rect, lines, secondary_muted=True) - elif column == 1: - self._paint_lines(painter, rect, _name_lines(text, metrics, width)) - else: - alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else ( - Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter - ) - painter.drawText(rect, alignment, _elide(text, metrics, width)) - finally: - painter.restore() - - -_LIBRARY = """ -#PrescriptionLibraryPage { background: #F3F7FD; color: #273244; } -#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent, -#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll, -#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll { - background: transparent; border: 0; -} -#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton, -#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox, -#PrescriptionLibraryPage QTableWidget { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; -} -#PrescriptionLibraryPage QLabel[role="pageTitle"] { - font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F; -} -#PrescriptionLibraryPage QLabel[role="muted"] { color: #5D6B80; font-size: 13px; } -#PrescriptionLibraryPage QFrame#MetricCard, -#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar, -#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; -} -#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] { - font-family: "$body"; color: #5D6B80; font-size: 13px; font-weight: 400; -} -#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] { - font-family: "$heading"; color: #273244; font-size: 18px; font-weight: 600; -} -#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] { - border: 0; border-radius: 0; background: transparent; -} -#PrescriptionLibraryPage QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px; - border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244; -} -#PrescriptionLibraryPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; } -#PrescriptionLibraryPage QPushButton:pressed { background: #DCEAFF; } -#PrescriptionLibraryPage QPushButton:focus { border-color: #75A5F0; } -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton, -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton { - background: #1769E8; border-color: #1769E8; color: #FFFFFF; -} -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover, -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover { - background: #155BCC; border-color: #155BCC; -} -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed, -#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed { - background: #124EA9; border-color: #124EA9; -} -#PrescriptionLibraryPage QPushButton[variant="danger"] { color: #BE4657; border-color: #E9D8DE; } -#PrescriptionLibraryPage QPushButton:disabled, -#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled { - color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2; -} -#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox { - min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2; - border-radius: 5px; background: #FFFFFF; color: #273244; - selection-background-color: #DCEAFF; selection-color: #273244; -} -#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: #75A5F0; } -#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; } -#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; } -#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; } -#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; } -#PrescriptionLibraryPage QComboBox:disabled { color: #97A4B6; background: #F6F8FC; } -#PrescriptionLibraryPage QComboBox QAbstractItemView { - font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6; -} -#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } -#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; } -#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; } -#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] { - min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px; - background: transparent; border: 0; border-bottom: 2px solid transparent; - border-radius: 0; color: #273244; font-size: 14px; -} -#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked { - color: #1769E8; border-bottom-color: #1769E8; -} -#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover { - color: #1555B6; background: #F2F7FF; -} -#PrescriptionLibraryPage QTableWidget { - border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF; - selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6; -} -#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; } -#PrescriptionLibraryPage QHeaderView::section { - min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80; - border: 0; border-bottom: 1px solid #DBE5F2; - font-family: "$body"; font-size: 13px; font-weight: 400; -} -#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; } -#PrescriptionLibraryPage QPushButton[rowAction="true"] { - min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px; - padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent; -} -#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; } -#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; } -#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; } -#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: #A4ADBA; } -#PrescriptionLibraryPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; } -#PrescriptionLibraryPage QLabel#EmptyStateGlyph { - font-size: 24px; color: #1769E8; background: #F2F7FF; - border: 1px solid #DBE5F2; border-radius: 22px; -} -#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; } -#PrescriptionLibraryPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#PrescriptionLibraryPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#PrescriptionLibraryPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } -#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; } -#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; } -""" - - -__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"] +"""Shared clinical tokens for the prescription library and its native delegates.""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from string import Template +from typing import Any + +from PySide6.QtCore import QEvent, QModelIndex, QRectF, QSize, Qt, QTimer +from PySide6.QtGui import QColor, QFont, QFontMetrics, QIcon, QPainter +from PySide6.QtWidgets import ( + QComboBox, + QPushButton, + QStyle, + QStyledItemDelegate, + QToolTip, + QWidget, +) + +from .design_system import PALETTE, RADII, clinical_stylesheet +from .reception_style import body_family, heading_family +from .widgets import SortableTable, TableColumn, first_value + + +def library_stylesheet() -> str: + return clinical_stylesheet(Template(_LIBRARY).safe_substitute(body=body_family(), heading=heading_family())) + + +def _library_icon(kind: str, color: str = PALETTE["accent"], size: int = 15) -> QIcon: + # Defer the page helper lookup so importing this module alone does not + # recurse through pages.__init__ and the library page's own style import. + from .pages.prescriptions import _painted_icon + + result = QIcon() + for mode, tint in ( + (QIcon.Mode.Normal, color), + (QIcon.Mode.Active, color), + (QIcon.Mode.Selected, color), + (QIcon.Mode.Disabled, PALETTE["disabled"]), + ): + pixmap = _painted_icon(kind, tint, size).pixmap(QSize(size, size)) + for state in (QIcon.State.Off, QIcon.State.On): + result.addPixmap(pixmap, mode, state) + return result + + +class LibraryComboBox(QComboBox): + """Keep native combo interaction while painting the local caret.""" + + def paintEvent(self, event: Any) -> None: # noqa: N802 - Qt virtual + super().paintEvent(event) + painter = QPainter(self) + try: + rect = QRectF(self.width() - 25, (self.height() - 14) / 2, 14, 14) + mode = QIcon.Mode.Normal if self.isEnabled() else QIcon.Mode.Disabled + _library_icon("chevron_down", PALETTE["muted"], 14).paint(painter, rect.toRect(), mode=mode) + finally: + painter.end() + + +class LibraryTable(SortableTable): + """Fit readable columns while preserving actions and selected template IDs.""" + + _FLEX_COLUMNS = ((1, 2), (4, 5), (5, 2)) + + def __init__(self, columns: Sequence[TableColumn], parent: QWidget | None = None) -> None: + super().__init__(columns, parent) + self.horizontalHeader().setStretchLastSection(False) + self._minimum_widths = tuple(column.width for column in self.columns) + self._manual_widths: dict[int, int] = {} + self._fitting_columns = False + self._fit_timer = QTimer(self) + self._fit_timer.setSingleShot(True) + self._fit_timer.timeout.connect(self._fit_columns) + self.horizontalHeader().sectionResized.connect(self._column_resized) + self.viewport().installEventFilter(self) + + def eventFilter(self, watched: Any, event: QEvent) -> bool: # noqa: N802 + if watched is self.viewport() and event.type() in {QEvent.Type.Resize, QEvent.Type.Show}: + self._schedule_column_fit() + return super().eventFilter(watched, event) + + def _schedule_column_fit(self) -> None: + if not self._fit_timer.isActive(): + self._fit_timer.start(0) + + def _column_resized(self, column: int, _old_size: int, size: int) -> None: + if self._fitting_columns: + return + self._manual_widths[column] = max(self._minimum_widths[column], size) + self._schedule_column_fit() + + def _fit_columns(self) -> None: + widths = [self._manual_widths.get(column, minimum) + for column, minimum in enumerate(self._minimum_widths)] + extra = max(0, self.viewport().width() - sum(widths)) + flexible = [(column, weight) for column, weight in self._FLEX_COLUMNS + if column not in self._manual_widths] + # If every text column was manually sized, keep those preferences as + # minimums and let the herb preview absorb any remaining wide-screen space. + flexible = flexible or [(4, 1)] + total_weight = sum(weight for _column, weight in flexible) + for column, weight in flexible: + widths[column] += extra * weight // total_weight + widths[flexible[0][0]] += max(0, self.viewport().width() - sum(widths)) + if widths == [self.columnWidth(column) for column in range(self.columnCount())]: + return + self._fitting_columns = True + try: + for column, width in enumerate(widths): + self.setColumnWidth(column, width) + finally: + self._fitting_columns = False + + def set_rows(self, rows: Iterable[Any]) -> None: + selected_id = first_value(self.current_data(), "id", "template_id", default=None) + super().set_rows(rows) + # The shared table restores an unsorted row index after enabling sort. + # Locate the same source object in the finished visual order instead. + if selected_id is not None: + for row_index in range(self.rowCount()): + item = self.item(row_index, 0) + row = item.data(Qt.ItemDataRole.UserRole) if item is not None else None + row_id = first_value(row, "id", "template_id", default=None) + if row_id is not None and str(row_id) == str(selected_id): + self.selectRow(row_index) + return + self.clearSelection() + self.setCurrentCell(-1, -1) + + def setCellWidget(self, row: int, column: int, widget: QWidget | None) -> None: # noqa: N802 + super().setCellWidget(row, column, widget) + if widget is None or column != 9: + return + widget.setObjectName("PrescriptionLibraryTableCellHost") + widget.setAutoFillBackground(False) + glyphs = { + "查看处方模板": "eye", + "AI 解释": "spark", + "编辑处方模板": "pencil", + "删除处方模板": "trash", + } + for button in widget.findChildren(QPushButton): + if not button.property("rowAction"): + continue + glyph = glyphs.get(button.accessibleName()) or glyphs.get(button.toolTip()) + if glyph is not None: + color = PALETTE["danger"] if button.property("danger") else PALETTE["accent"] + button.setIcon(_library_icon(glyph, color, button.iconSize().width())) + + +def _library_font(size: int = 14, *, medium: bool = False) -> QFont: + font = QFont(heading_family() if medium else body_family()) + font.setPixelSize(size) + font.setWeight(QFont.Weight.Medium if medium else QFont.Weight.Normal) + return font + + +def _elide(text: str, metrics: QFontMetrics, width: int) -> str: + return metrics.elidedText(text, Qt.TextElideMode.ElideRight, max(1, width)) + + +def _herb_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]: + """Wrap between complete herb entries; elide only the displayed lines.""" + entries = text.split("、") + first = entries[0] + next_index = 1 + while next_index < min(2, len(entries)): + candidate = first + "、" + entries[next_index] + if metrics.horizontalAdvance(candidate) > width: + break + first = candidate + next_index += 1 + lines = [_elide(first, metrics, width)] + if next_index < len(entries): + lines.append(_elide("、".join(entries[next_index:]), metrics, width)) + return lines + + +def _name_lines(text: str, metrics: QFontMetrics, width: int) -> list[str]: + if metrics.horizontalAdvance(text) <= width: + return [text] + split = 1 + while split < len(text) and metrics.horizontalAdvance(text[: split + 1]) <= width: + split += 1 + return [_elide(text[:split], metrics, width), _elide(text[split:], metrics, width)] + + +class LibraryItemDelegate(QStyledItemDelegate): + """Paint the ten existing columns without changing display or source roles.""" + + def sizeHint(self, option: Any, index: QModelIndex) -> QSize: # noqa: N802 + size = super().sizeHint(option, index) + size.setHeight(78) + return size + + def helpEvent(self, event: Any, view: Any, option: Any, index: QModelIndex) -> bool: # noqa: N802 + if event is not None and index.isValid() and index.column() != 9: + text = index.data(Qt.ItemDataRole.ToolTipRole) or index.data(Qt.ItemDataRole.DisplayRole) + if text: + QToolTip.showText(event.globalPos(), str(text), view) + return True + return super().helpEvent(event, view, option, index) + + @staticmethod + def _paint_lines( + painter: QPainter, + rect: QRectF, + lines: list[str], + *, + secondary_muted: bool = False, + ) -> None: + line_height = 26 + top = rect.center().y() - len(lines) * line_height / 2 + for line_index, line in enumerate(lines): + if secondary_muted and line_index: + painter.setFont(_library_font(13)) + painter.setPen(QColor(PALETTE["muted"])) + line_rect = QRectF(rect.left(), top + line_index * line_height, rect.width(), line_height) + painter.drawText(line_rect, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, line) + + def paint(self, painter: QPainter, option: Any, index: QModelIndex) -> None: + painter.save() + try: + painter.setClipRect(option.rect) + selected = bool(option.state & QStyle.StateFlag.State_Selected) + hovered = bool(option.state & QStyle.StateFlag.State_MouseOver) + background = PALETTE["accent_soft"] if selected else PALETTE["surface_alt"] if hovered else PALETTE["surface"] + painter.fillRect(option.rect, QColor(background)) + painter.setPen(QColor(PALETTE["line"])) + painter.drawLine(option.rect.bottomLeft(), option.rect.bottomRight()) + if selected and index.column() == 0: + stripe = QRectF(option.rect.left(), option.rect.top(), 3, option.rect.height() - 1) + painter.fillRect(stripe, QColor(PALETTE["accent"])) + if option.state & QStyle.StateFlag.State_HasFocus: + painter.setPen(QColor(PALETTE["focus"])) + painter.setBrush(Qt.BrushStyle.NoBrush) + painter.drawRect(option.rect.adjusted(1, 1, -2, -2)) + + column = index.column() + if column == 9: + return + rect = QRectF(option.rect.adjusted(12, 0, -12, -1)) + if rect.width() <= 0: + return + value = index.data(Qt.ItemDataRole.DisplayRole) + text = "" if value is None else str(value) + font = _library_font(medium=column == 1) + painter.setFont(font) + painter.setPen(QColor(PALETTE["text"])) + metrics = QFontMetrics(font) + width = int(rect.width()) + + if column == 2: + painter.setFont(_library_font(13)) + metrics = painter.fontMetrics() + label = _elide(text, metrics, width - 12) + pill_width = min(rect.width(), metrics.horizontalAdvance(label) + 14) + pill = QRectF(rect.center().x() - pill_width / 2, rect.center().y() - 12, pill_width, 24) + painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) + painter.setPen(Qt.PenStyle.NoPen) + painter.setBrush(QColor(PALETTE["accent_soft"])) + painter.drawRoundedRect(pill, RADII["small"], RADII["small"]) + painter.setPen(QColor(PALETTE["accent"])) + painter.drawText(pill, Qt.AlignmentFlag.AlignCenter, label) + elif column == 6: + glyph = "users" if text == "所有人可见" else "lock" + icon_rect = QRectF(rect.left(), rect.center().y() - 7, 14, 14) + _library_icon(glyph, PALETTE["muted"], 14).paint(painter, icon_rect.toRect()) + label_rect = rect.adjusted(22, 0, 0, 0) + painter.drawText( + label_rect, + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter, + _elide(text, metrics, int(label_rect.width())), + ) + elif column == 4: + self._paint_lines(painter, rect, _herb_lines(text, metrics, width)) + elif column == 8: + parts = text.splitlines() if "\n" in text else text.rsplit(" ", 1) + lines = [_elide(parts[0], metrics, width)] + if len(parts) > 1: + lines.append(_elide(" ".join(parts[1:]), QFontMetrics(_library_font(13)), width)) + self._paint_lines(painter, rect, lines, secondary_muted=True) + elif column == 1: + self._paint_lines(painter, rect, _name_lines(text, metrics, width)) + else: + alignment = Qt.AlignmentFlag.AlignCenter if column in (0, 3, 5) else ( + Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter + ) + painter.drawText(rect, alignment, _elide(text, metrics, width)) + finally: + painter.restore() + + +_LIBRARY = """ +#PrescriptionLibraryPage { background: $ds_canvas; color: $ds_text; } +#PrescriptionLibraryPage QWidget#PrescriptionLibraryContent, +#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryScroll, +#PrescriptionLibraryPage QScrollArea#PrescriptionLibraryToolbarScroll { + background: transparent; border: 0; +} +#PrescriptionLibraryPage QLabel, #PrescriptionLibraryPage QPushButton, +#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox, +#PrescriptionLibraryPage QTableWidget { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; +} +#PrescriptionLibraryPage QLabel[role="pageTitle"] { + font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading; +} +#PrescriptionLibraryPage QLabel[role="muted"] { color: $ds_muted; font-size: 13px; } +#PrescriptionLibraryPage QFrame#PrescriptionLibraryFilterBar, +#PrescriptionLibraryPage QFrame#PrescriptionLibraryTableCard { + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PrescriptionLibraryPage QFrame#MetricCard { background: $ds_surface; border: 0; border-radius: $ds_radius_panel; } +#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricTitle"] { + font-family: "$body"; color: $ds_muted; font-size: 13px; font-weight: 400; +} +#PrescriptionLibraryPage QFrame#MetricCard QLabel[role="metricValue"] { + font-family: "$heading"; color: $ds_text; font-size: 18px; font-weight: 600; +} +#PrescriptionLibraryPage QFrame#MetricCard QLabel[metricIcon="true"] { + border: 0; border-radius: 0; background: transparent; +} +#PrescriptionLibraryPage QPushButton { + min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control; + border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text; +} +#PrescriptionLibraryPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; } +#PrescriptionLibraryPage QPushButton:pressed { background: $ds_accent_soft; } +#PrescriptionLibraryPage QPushButton:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton { + background: $ds_accent; border-color: $ds_accent; color: $ds_surface; +} +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:hover, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:hover { + background: $ds_accent_hover; border-color: $ds_accent_hover; +} +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:pressed, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:pressed { + background: $ds_accent_pressed; border-color: $ds_accent_pressed; +} +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:focus, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#PrescriptionLibraryPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; } +#PrescriptionLibraryPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QPushButton:disabled, +#PrescriptionLibraryPage QPushButton[variant="danger"]:disabled, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryAddButton:disabled, +#PrescriptionLibraryPage QPushButton#PrescriptionLibraryQueryButton:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; +} +#PrescriptionLibraryPage QLineEdit, #PrescriptionLibraryPage QComboBox { + min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line; + border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; +} +#PrescriptionLibraryPage QLineEdit:focus, #PrescriptionLibraryPage QComboBox:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QLineEdit QToolButton { border: 0; background: transparent; padding: 0; } +#PrescriptionLibraryPage QComboBox { padding-right: 30px; font-size: 13px; } +#PrescriptionLibraryPage QComboBox::drop-down { width: 28px; border: 0; background: transparent; } +#PrescriptionLibraryPage QComboBox::down-arrow { image: none; width: 0; height: 0; } +#PrescriptionLibraryPage QComboBox:disabled { color: $ds_disabled; background: $ds_disabled_surface; } +#PrescriptionLibraryPage QComboBox QAbstractItemView { + font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent; +} +#PrescriptionLibraryPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar { background: transparent; border: 0; } +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton { padding: 0 12px; font-size: 13px; } +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"] { + min-width: 80px; min-height: 40px; max-height: 40px; padding: 0 10px; margin-right: 8px; + background: transparent; border: 0; border-bottom: 2px solid transparent; + border-radius: 0; color: $ds_text; font-size: 14px; +} +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:checked { + color: $ds_accent; border-bottom-color: $ds_accent; +} +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:hover { + color: $ds_accent; background: $ds_surface_alt; +} +#PrescriptionLibraryPage QFrame#PrescriptionLibraryToolbar QPushButton[toolbarTab="true"]:focus { background: $ds_accent_soft; } +#PrescriptionLibraryPage QTableWidget { + border: 0; background: $ds_surface; alternate-background-color: $ds_surface; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line; +} +#PrescriptionLibraryPage QTableWidget::item { padding: 0; border: 0; } +#PrescriptionLibraryPage QHeaderView::section { + min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-bottom: 1px solid $ds_line; + font-family: "$body"; font-size: 13px; font-weight: 400; +} +#PrescriptionLibraryPage QWidget#PrescriptionLibraryTableCellHost { background: transparent; border: 0; } +#PrescriptionLibraryPage QPushButton[rowAction="true"] { + min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px; + padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent; +} +#PrescriptionLibraryPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; } +#PrescriptionLibraryPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; } +#PrescriptionLibraryPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; } +#PrescriptionLibraryPage QPushButton[rowAction="true"]:disabled { background: transparent; border-color: transparent; color: $ds_disabled; } +#PrescriptionLibraryPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; } +#PrescriptionLibraryPage QLabel#EmptyStateGlyph { + font-size: 24px; color: $ds_accent; background: $ds_surface_alt; + border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PrescriptionLibraryPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; } +#PrescriptionLibraryPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#PrescriptionLibraryPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#PrescriptionLibraryPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } +#PrescriptionLibraryPage QScrollBar::add-line, #PrescriptionLibraryPage QScrollBar::sub-line { width: 0; height: 0; } +#PrescriptionLibraryPage QScrollBar::add-page, #PrescriptionLibraryPage QScrollBar::sub-page { background: transparent; } +""" + + +__all__ = ["library_stylesheet", "LibraryComboBox", "LibraryTable", "LibraryItemDelegate"] diff --git a/app/src/doctor_workstation/ui/prescriptions_style.py b/app/src/doctor_workstation/ui/prescriptions_style.py index bf1554418..9d452dfcf 100644 --- a/app/src/doctor_workstation/ui/prescriptions_style.py +++ b/app/src/doctor_workstation/ui/prescriptions_style.py @@ -1,107 +1,115 @@ -"""Scoped surfaces and real fonts for the approved issued-prescription page.""" - -from string import Template - -from .reception_style import body_family, heading_family - - -def prescriptions_stylesheet() -> str: - return Template(_PRESCRIPTIONS).substitute(body=body_family(), heading=heading_family()) - - -_PRESCRIPTIONS = """ -#PrescriptionsPage { background: #F3F7FD; color: #273244; } -#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; } -#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit, -#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget { - font-family: "$body"; font-size: 14px; font-weight: 400; color: #273244; -} -#PrescriptionsPage QLabel[role="pageTitle"] { - font-family: "$heading"; font-size: 20px; font-weight: 600; color: #202C3F; -} -#PrescriptionsPage QLabel[role="sectionTitle"] { - font-family: "$heading"; font-size: 14px; font-weight: 600; -} -#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge { - color: #5D6B80; font-size: 13px; background: transparent; border: 0; padding: 0; -} -#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard { - background: #FFFFFF; border: 1px solid #DBE5F2; border-radius: 8px; -} -#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; } -#PrescriptionsPage QPushButton { - min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: 5px; - border: 1px solid #DBE5F2; background: #FFFFFF; color: #273244; -} -#PrescriptionsPage QPushButton:hover { background: #F2F7FF; border-color: #B6CDEE; color: #1555B6; } -#PrescriptionsPage QPushButton:pressed { background: #DCEAFF; } -#PrescriptionsPage QPushButton:focus { border-color: #75A5F0; } -#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton { - background: #1769E8; color: #FFFFFF; border-color: #1769E8; -} -#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover { - background: #155BCC; border-color: #155BCC; -} -#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed { - background: #124EA9; border-color: #124EA9; -} -#PrescriptionsPage QPushButton[variant="danger"] { color: #BE4657; background: #FFFFFF; border-color: #E9D8DE; } -#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled { - color: #97A4B6; background: #F6F8FC; border-color: #E2E9F2; -} -#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { - min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid #DBE5F2; - border-radius: 5px; background: #FFFFFF; color: #273244; - selection-background-color: #DCEAFF; selection-color: #273244; -} -#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: #75A5F0; } -#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; } -#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; } -#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; } -#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; } -#PrescriptionsPage QDateTimeEdit:disabled { color: #8A97A9; background: #F6F8FC; border-color: #E2E9F2; } -#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; } -#PrescriptionsPage QComboBox QAbstractItemView { - font-family: "$body"; font-size: 13px; color: #273244; background: #FFFFFF; - border: 1px solid #DBE5F2; outline: 0; selection-background-color: #EAF2FF; selection-color: #1555B6; -} -#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } -#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: #FFFFFF; color: #273244; } -#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: #F5F8FD; } -#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: #273244; background: transparent; } -#PrescriptionsPage QCalendarWidget QAbstractItemView { color: #273244; background: #FFFFFF; selection-background-color: #1769E8; selection-color: #FFFFFF; outline: 0; } -#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; } -#PrescriptionsPage QTableWidget#PrescriptionTable { - border: 0; background: #FFFFFF; alternate-background-color: #FFFFFF; - selection-background-color: #F2F7FF; selection-color: #273244; gridline-color: #E6EDF6; -} -#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; } -#PrescriptionsPage QHeaderView::section { - min-height: 0; padding: 0 12px; background: #F5F8FD; color: #5D6B80; - border: 0; border-bottom: 1px solid #DBE5F2; - font-family: "$body"; font-size: 13px; font-weight: 400; -} -#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; } -#PrescriptionsPage QPushButton[rowAction="true"] { - min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px; - padding: 0; border: 1px solid transparent; border-radius: 4px; background: transparent; -} -#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] { - min-width: 64px; max-width: 64px; color: #1769E8; font-size: 13px; padding: 0; -} -#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: #EAF2FF; border-color: #B6CDEE; } -#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: #75A5F0; } -#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: #FFF0F2; border-color: #EAC8D0; } -#PrescriptionsPage QPushButton[rowAction="true"]:disabled, -#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled { - background: transparent; border-color: transparent; color: #A4ADBA; -} -#PrescriptionsPage QWidget#InfiniteList { background: #FFFFFF; border-top: 1px solid #E6EDF6; } -#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: #1769E8; background: #F2F7FF; border: 1px solid #DBE5F2; border-radius: 22px; } -#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; } -#PrescriptionsPage QScrollBar:vertical { background: #F4F7FC; width: 7px; margin: 0; } -#PrescriptionsPage QScrollBar:horizontal { background: #F4F7FC; height: 7px; margin: 0; } -#PrescriptionsPage QScrollBar::handle { background: #C8D5E6; border-radius: 3px; min-width: 24px; min-height: 24px; } -#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; } -#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; } -""" +"""Scoped surfaces and real fonts for the approved issued-prescription page.""" + +from string import Template + +from .design_system import clinical_stylesheet +from .reception_style import body_family, heading_family + + +def prescriptions_stylesheet() -> str: + return clinical_stylesheet(Template(_PRESCRIPTIONS).safe_substitute(body=body_family(), heading=heading_family())) + + +_PRESCRIPTIONS = """ +#PrescriptionsPage { background: $ds_canvas; color: $ds_text; } +#PrescriptionWorkspaceContent, #PrescriptionWorkspaceScroll { background: transparent; border: 0; } +#PrescriptionsPage QLabel, #PrescriptionsPage QPushButton, #PrescriptionsPage QLineEdit, +#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit, #PrescriptionsPage QTableWidget { + font-family: "$body"; font-size: 14px; font-weight: 400; color: $ds_text; +} +#PrescriptionsPage QLabel[role="pageTitle"] { + font-family: "$heading"; font-size: 20px; font-weight: 600; color: $ds_heading; +} +#PrescriptionsPage QLabel[role="sectionTitle"] { + font-family: "$heading"; font-size: 14px; font-weight: 600; +} +#PrescriptionsPage QLabel[role="muted"], #PrescriptionsPage QLabel#PrescriptionCountBadge { + color: $ds_muted; font-size: 13px; background: transparent; border: 0; padding: 0; +} +#PrescriptionsPage QFrame#PrescriptionFilterBar, #PrescriptionsPage QFrame#PrescriptionTableCard { + background: $ds_surface; border: 1px solid $ds_line; border-radius: $ds_radius_panel; +} +#PrescriptionsPage QFrame#PrescriptionToolbar { background: transparent; border: 0; } +#PrescriptionsPage QPushButton { + min-height: 38px; max-height: 38px; padding: 0 16px; border-radius: $ds_radius_control; + border: 1px solid transparent; background: $ds_surface_alt; color: $ds_text; +} +#PrescriptionsPage QPushButton:hover { background: $ds_surface_alt; border-color: $ds_line_strong; color: $ds_accent; } +#PrescriptionsPage QPushButton:pressed { background: $ds_accent_soft; } +#PrescriptionsPage QPushButton:focus { border-color: $ds_focus; } +#PrescriptionsPage QPushButton#PrescriptionAddButton, #PrescriptionsPage QPushButton#PrescriptionQueryButton { + background: $ds_accent; color: $ds_surface; border-color: $ds_accent; +} +#PrescriptionsPage QPushButton#PrescriptionAddButton:hover, #PrescriptionsPage QPushButton#PrescriptionQueryButton:hover { + background: $ds_accent_hover; border-color: $ds_accent_hover; +} +#PrescriptionsPage QPushButton#PrescriptionAddButton:pressed, #PrescriptionsPage QPushButton#PrescriptionQueryButton:pressed { + background: $ds_accent_pressed; border-color: $ds_accent_pressed; +} +#PrescriptionsPage QPushButton#PrescriptionAddButton:focus, +#PrescriptionsPage QPushButton#PrescriptionQueryButton:focus { border-color: $ds_focus; } +#PrescriptionsPage QPushButton[variant="danger"] { color: $ds_danger; background: $ds_danger_soft; border-color: transparent; } +#PrescriptionsPage QPushButton[variant="danger"]:hover { border-color: $ds_danger; } +#PrescriptionsPage QPushButton[variant="danger"]:focus { border-color: $ds_focus; } +#PrescriptionsPage QPushButton:disabled, #PrescriptionsPage QPushButton[variant="danger"]:disabled, +#PrescriptionsPage QPushButton#PrescriptionAddButton:disabled, +#PrescriptionsPage QPushButton#PrescriptionQueryButton:disabled { + color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; +} +#PrescriptionsPage QLineEdit, #PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { + min-height: 38px; max-height: 38px; padding: 0 12px; border: 1px solid $ds_line; + border-radius: $ds_radius_control; background: $ds_surface; color: $ds_text; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; +} +#PrescriptionsPage QLineEdit:focus, #PrescriptionsPage QComboBox:focus, #PrescriptionsPage QDateTimeEdit:focus { border-color: $ds_focus; } +#PrescriptionsPage QLineEdit QToolButton { min-width: 0; min-height: 0; border: 0; background: transparent; padding: 0; } +#PrescriptionsPage QComboBox, #PrescriptionsPage QDateTimeEdit { padding-right: 30px; font-size: 13px; } +#PrescriptionsPage QComboBox::drop-down, #PrescriptionsPage QDateTimeEdit::drop-down { width: 28px; border: 0; background: transparent; } +#PrescriptionsPage QComboBox::down-arrow, #PrescriptionsPage QDateTimeEdit::down-arrow { image: none; width: 0; height: 0; } +#PrescriptionsPage QDateTimeEdit:disabled { color: $ds_disabled; background: $ds_disabled_surface; border-color: $ds_line; } +#PrescriptionsPage QPushButton#PrescriptionDoctorButton { text-align: left; padding-right: 30px; font-size: 13px; } +#PrescriptionsPage QComboBox QAbstractItemView { + font-family: "$body"; font-size: 13px; color: $ds_text; background: $ds_surface; + border: 1px solid $ds_line; outline: 0; selection-background-color: $ds_accent_soft; selection-color: $ds_accent; +} +#PrescriptionsPage QComboBox QAbstractItemView::item { min-height: 30px; padding: 3px 10px; } +#PrescriptionsPage QCalendarWidget { font-family: "$body"; font-size: 13px; background: $ds_surface; color: $ds_text; } +#PrescriptionsPage QCalendarWidget QWidget#qt_calendar_navigationbar { background: $ds_surface_alt; } +#PrescriptionsPage QCalendarWidget QToolButton { min-height: 28px; border: 0; padding: 0 8px; color: $ds_text; background: transparent; } +#PrescriptionsPage QCalendarWidget QAbstractItemView { color: $ds_text; background: $ds_surface; selection-background-color: $ds_accent; selection-color: $ds_surface; outline: 0; } +#PrescriptionsPage QFrame#PrescriptionToolbar QPushButton { padding: 0 12px; font-size: 13px; } +#PrescriptionsPage QTableWidget#PrescriptionTable { + border: 0; background: $ds_surface; alternate-background-color: $ds_surface; + selection-background-color: $ds_accent_soft; selection-color: $ds_text; gridline-color: $ds_line; +} +#PrescriptionsPage QTableWidget#PrescriptionTable::item { border: 0; padding: 0; } +#PrescriptionsPage QHeaderView::section { + min-height: 0; padding: 0 12px; background: $ds_surface_alt; color: $ds_muted; + border: 0; border-bottom: 1px solid $ds_line; + font-family: "$body"; font-size: 13px; font-weight: 400; +} +#PrescriptionsPage QWidget#PrescriptionTableCellHost { border: 0; background: transparent; } +#PrescriptionsPage QPushButton[rowAction="true"] { + min-width: 28px; max-width: 28px; min-height: 28px; max-height: 28px; + padding: 0; border: 1px solid transparent; border-radius: $ds_radius_small; background: transparent; +} +#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"] { + min-width: 64px; max-width: 64px; color: $ds_accent; font-size: 13px; padding: 0; +} +#PrescriptionsPage QPushButton[rowAction="true"]:hover { background: $ds_accent_soft; border-color: $ds_line_strong; } +#PrescriptionsPage QPushButton[rowAction="true"]:focus { border-color: $ds_focus; } +#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:hover { background: $ds_danger_soft; border-color: $ds_danger_soft; } +#PrescriptionsPage QPushButton[rowAction="true"][danger="true"]:focus { border-color: $ds_focus; } +#PrescriptionsPage QPushButton[rowAction="true"]:disabled, +#PrescriptionsPage QPushButton[rowAction="true"][labeled="true"]:disabled { + background: transparent; border-color: transparent; color: $ds_disabled; +} +#PrescriptionsPage QWidget#InfiniteList { background: $ds_surface; border-top: 1px solid $ds_line; } +#PrescriptionsPage QLabel#EmptyStateGlyph { font-size: 24px; color: $ds_accent; background: $ds_surface_alt; border: 1px solid $ds_line; border-radius: $ds_radius_panel; } +#PrescriptionsPage QWidget#EmptyState QLabel[role="muted"] { min-width: 300px; } +#PrescriptionsPage QScrollBar:vertical { background: $ds_canvas; width: 7px; margin: 0; } +#PrescriptionsPage QScrollBar:horizontal { background: $ds_canvas; height: 7px; margin: 0; } +#PrescriptionsPage QScrollBar::handle { background: $ds_line_strong; border-radius: 3px; min-width: 24px; min-height: 24px; } +#PrescriptionsPage QScrollBar::add-line, #PrescriptionsPage QScrollBar::sub-line { width: 0; height: 0; } +#PrescriptionsPage QScrollBar::add-page, #PrescriptionsPage QScrollBar::sub-page { background: transparent; } +""" diff --git a/app/src/doctor_workstation/ui/reception_style.py b/app/src/doctor_workstation/ui/reception_style.py index 23524d058..c19e1b737 100644 --- a/app/src/doctor_workstation/ui/reception_style.py +++ b/app/src/doctor_workstation/ui/reception_style.py @@ -4,23 +4,24 @@ from __future__ import annotations from PySide6.QtWidgets import QApplication +from .design_system import PALETTE from .theme import _register_preferred_cjk_fonts TECH_BLUE = { - "accent": "#1769E8", - "accent_hover": "#155BCC", - "accent_pressed": "#124EA9", - "selection": "#EAF2FF", - "selected_text": "#1555B6", - "canvas": "#F3F7FD", - "sidebar": "#EDF4FF", - "surface": "#FFFFFF", - "raised": "#F7FAFE", - "line": "#DBE5F2", - "text": "#273244", - "heading": "#202C3F", - "muted": "#5D6B80", - "focus": "#75A5F0", + "accent": PALETTE["accent"], + "accent_hover": PALETTE["accent_hover"], + "accent_pressed": PALETTE["accent_pressed"], + "selection": PALETTE["accent_soft"], + "selected_text": PALETTE["accent_hover"], + "canvas": PALETTE["canvas"], + "sidebar": PALETTE["sidebar"], + "surface": PALETTE["surface"], + "raised": PALETTE["surface_alt"], + "line": PALETTE["line"], + "text": PALETTE["text"], + "heading": PALETTE["heading"], + "muted": PALETTE["muted"], + "focus": PALETTE["focus"], } diff --git a/app/src/doctor_workstation/ui/reception_workspace.py b/app/src/doctor_workstation/ui/reception_workspace.py index 0cb853d7f..6357fd1d3 100644 --- a/app/src/doctor_workstation/ui/reception_workspace.py +++ b/app/src/doctor_workstation/ui/reception_workspace.py @@ -170,8 +170,8 @@ QWidget#ReceptionPage QStackedWidget#ReceptionNarrowWorkspace { } QWidget#ReceptionPage QFrame#ReceptionQueuePanel { background-color: #FFFFFF; - border: 1px solid #E5ECF6; - border-radius: 8px; + border: 1px solid #EDF0F5; + border-radius: 16px; } QWidget#ReceptionPage QLabel#ReceptionQueueTitle { font-size: 18px; @@ -200,8 +200,8 @@ QWidget#ReceptionPage QFrame#ReceptionHero, QWidget#ReceptionPage QFrame#ReceptionClinicalCard { min-height: 0; background-color: #FFFFFF; - border: 1px solid #E5ECF6; - border-radius: 8px; + border: 1px solid #EDF0F5; + border-radius: 16px; } QWidget#ReceptionPage QLabel#ReceptionPatientName { font-size: 20px; @@ -223,8 +223,8 @@ QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs { background-color: #FFFFFF; border: 0; border-bottom: 1px solid #E5ECF6; - border-top-left-radius: 8px; - border-top-right-radius: 8px; + border-top-left-radius: 16px; + border-top-right-radius: 16px; } QWidget#ReceptionPage QTabBar#ReceptionDetailTabs::tab, QWidget#ReceptionPage QTabBar#ReceptionWorkspaceTabs::tab { @@ -295,8 +295,8 @@ QWidget#ReceptionPage QFrame#ReceptionPatientSummaryCard, QWidget#ReceptionPage QFrame#ReceptionVitalsCard, QWidget#ReceptionPage QFrame#ReceptionLabsCard { background-color: #FFFFFF; - border: 1px solid #E5ECF6; - border-radius: 8px; + border: 1px solid #EDF0F5; + border-radius: 16px; } QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue { color: #24334A; @@ -367,8 +367,8 @@ QWidget#ReceptionPage QLabel[receptionMetricState="true"][alert="true"][warning= QWidget#ReceptionPage QFrame#ReceptionAiAnalysisCard, QWidget#ReceptionPage QFrame#ReceptionAiAssistantCard { background-color: #FFFFFF; - border: 1px solid #DCE5F0; - border-radius: 8px; + border: 1px solid $ds_line; + border-radius: $ds_radius_panel; } QWidget#ReceptionPage QLabel#ReceptionAiTitle, QWidget#ReceptionPage QPushButton#ReceptionAiTitle { @@ -405,4 +405,37 @@ QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::add-line:v QWidget#ReceptionPage QScrollArea#ReceptionInsightsScroll QScrollBar::sub-line:vertical { height: 0; } +QWidget#ReceptionPage QLineEdit#ReceptionQueueSearch, +QWidget#ReceptionPage QPushButton#ReceptionDateButton, +QWidget#ReceptionPage QPushButton#ReceptionQueueFilterToggle, +QWidget#ReceptionPage QPushButton#ReceptionVideoButton, +QWidget#ReceptionPage QPushButton#ReceptionNotifyButton, +QWidget#ReceptionPage QPushButton#ReceptionHistoryButton, +QWidget#ReceptionPage QPushButton#ReceptionImButton, +QWidget#ReceptionPage QPushButton#ReceptionMoreButton, +QWidget#ReceptionPage QPushButton#ReceptionCompleteButton, +QWidget#ReceptionPage QPushButton[receptionAiPrompt="true"] { + border-radius: $ds_radius_control; +} +QWidget#ReceptionPage QPushButton:focus, +QWidget#ReceptionPage QLineEdit:focus, +QWidget#ReceptionPage QComboBox:focus, +QWidget#ReceptionPage QTextEdit:focus { + border-color: $ds_focus; +} +QWidget#ReceptionPage QPushButton#ReceptionVideoButton:pressed { + color: $ds_surface; + background-color: $ds_accent_pressed; + border-color: $ds_accent_pressed; +} +QWidget#ReceptionPage QLabel[receptionMetricState="true"] { + border-radius: $ds_radius_small; +} +QWidget#ReceptionPage QFrame#ReceptionLabCell, +QWidget#ReceptionPage QWidget#ReceptionCaseField { + border-bottom-color: $ds_line; +} +QWidget#ReceptionPage QLabel#ReceptionPatientSummaryValue[missing="true"] { + color: $ds_muted; +} """ diff --git a/app/src/doctor_workstation/ui/shell.py b/app/src/doctor_workstation/ui/shell.py index 5abad6e8a..628f6573e 100644 --- a/app/src/doctor_workstation/ui/shell.py +++ b/app/src/doctor_workstation/ui/shell.py @@ -59,6 +59,7 @@ from .chat_notifications import ( ChatNotification, ChatNotificationCenter, ) +from .design_system import PALETTE, clinical_stylesheet from .dialogs.ai_consult import can_open_ai_consult from .dialogs.ai_consult_picker import select_and_present_ai_consult from .dialogs.diagnosis import DiagnosisDialog @@ -72,7 +73,7 @@ from .pages import ( ReceptionPage, ) from .reception_style import TECH_BLUE, body_family, heading_family, number_family -from .theme import COLORS, TYPE, crisp_pixmap +from .theme import COLORS, METRICS, TYPE, crisp_pixmap from .widgets import ( EmptyState, StatusBadge, @@ -93,8 +94,8 @@ _SHELL_DESIGN_SIZE = QSize(1710, 920) _SHELL_MINIMUM_SIZE = QSize(1024, 640) _RECEPTION_SIDEBAR_WIDTH = 208 _RECEPTION_TOPBAR_HEIGHT = 76 -_RECEPTION_SIDEBAR_COLOR = "#F3F7FD" -_RECEPTION_CHROME_LINE = "#E7EDF7" +_RECEPTION_SIDEBAR_COLOR = PALETTE["sidebar"] +_RECEPTION_CHROME_LINE = PALETTE["line"] # Approved pages share one chrome state, so navigation among them keeps it intact. _TECH_BLUE_PAGES = frozenset({"appointments", "consultations", "patients", "prescriptions", "prescription_library", "reception"}) @@ -1005,7 +1006,7 @@ class ShellWindow(QMainWindow): chrome_widgets.extend(self.topbar.findChildren(_PaintedIconButton)) chrome_widgets.append(self.tabs_menu_button) self._legacy_chrome_styles = { - widget: widget.styleSheet() for widget in chrome_widgets + widget: clinical_stylesheet(widget.styleSheet()) for widget in chrome_widgets } self._register_pages() self.search_shortcut = QShortcut(QKeySequence("Ctrl+K"), self) @@ -1268,7 +1269,7 @@ class ShellWindow(QMainWindow): color: #606163; background-color: #FFFFFF; border: 1px solid #EDEDEE; - border-radius: 999px; + border-radius: 10px; padding: 4px 10px; font-size: 13px; font-weight: 500; @@ -1693,7 +1694,7 @@ class ShellWindow(QMainWindow): font-family: "{body_family()}"; font-weight: 400; min-height: 44px; max-height: 44px; border: 0; border-left: 5px solid transparent; - border-radius: 6px; + border-radius: {METRICS["r_md"]}; padding: 0 16px; font-size: {TYPE['fs_body']}; color: {TECH_BLUE['text']}; }} @@ -1711,7 +1712,7 @@ class ShellWindow(QMainWindow): }} QPushButton#ShellNavButton[collapsed="true"] {{ padding: 0; }} QFrame#ShellAssistantCard {{ - background-color: {TECH_BLUE['surface']}; border-radius: 8px; + background-color: {TECH_BLUE['surface']}; border-radius: {METRICS["r_lg"]}; border: 1px solid {_RECEPTION_CHROME_LINE}; }} QLabel#ShellAssistantName {{ @@ -1723,7 +1724,7 @@ class ShellWindow(QMainWindow): QPushButton#ShellAssistantButton, QPushButton#ShellSettingsButton {{ font-family: "{body_family()}"; font-weight: 400; font-size: {TYPE['fs_body']}; }} - QPushButton#ShellAssistantButton {{ border-radius: 6px; }} + QPushButton#ShellAssistantButton {{ border-radius: {METRICS["r_md"]}; }} QPushButton#ShellSettingsButton {{ min-height: 50px; max-height: 50px; text-align: left; padding: 0 32px; @@ -1738,7 +1739,7 @@ class ShellWindow(QMainWindow): border-radius: 0; border-bottom: 1px solid {_RECEPTION_CHROME_LINE}; }} - QFrame#ShellGlobalSearch {{ border: 1px solid {_RECEPTION_CHROME_LINE}; border-radius: 5px; }} + QFrame#ShellGlobalSearch {{ background-color: {PALETTE["surface_alt"]}; border: 1px solid transparent; border-radius: {METRICS["r_md"]}; }} QFrame#ShellUserSeparator {{ background: {_RECEPTION_CHROME_LINE}; border: 0; }} QLabel#ShellShortcutHint {{ font-family: "{number_family()}"; font-size: {TYPE['fs_small']}; @@ -1767,7 +1768,7 @@ class ShellWindow(QMainWindow): if isinstance(widget, _PaintedIconButton): side = 50 if widget in (self.refresh_button, self.notification_button, self.settings_button) else 34 stylesheet += f"QToolButton#ShellPaintedIconButton {{ min-width: {side - 2}px; max-width: {side - 2}px; min-height: {side - 2}px; max-height: {side - 2}px; }}" - widget.setStyleSheet(stylesheet) + widget.setStyleSheet(clinical_stylesheet(stylesheet)) self._set_reception_geometry(active) for widget in ( diff --git a/app/src/doctor_workstation/ui/theme.py b/app/src/doctor_workstation/ui/theme.py index c8b4e9d41..e62654238 100644 --- a/app/src/doctor_workstation/ui/theme.py +++ b/app/src/doctor_workstation/ui/theme.py @@ -41,46 +41,46 @@ from doctor_workstation.resources import resource_path # ``motion`` deliberately imports nothing from this module, so this stays a # one-way dependency: tokens here, animation there. from . import motion +from .design_system import PALETTE, RADII, SPACING, clinical_stylesheet -# Neutral reading colors follow the installed Codex light chrome defaults. +# Shared reading colors keep native pages and dialog chrome consistent. # Brand accents are independent of reading ink; use opaque text for stable contrast. # The legacy teal/ink aliases remain for existing callers. COLORS = { - "canvas": "#F4F6FA", - "canvas_mid": "#FFFFFF", - "canvas_glow": "#EEF1FA", - "surface": "#FFFFFF", - "surface_alt": "#F7F7F7", - "raised": "#F7F7F7", - "glass": "#FFFFFF", - "glass_alt": "#F7F7F7", - "line": "#EDEDEE", - "line_soft": "#E4E4E5", - "text": "#1A1C1F", - "text_soft": "#606163", - "muted": "#6A6B6D", - "disabled_surface": "#F2F2F2", - "disabled_text": "#8E8F90", - "indigo": "#4F63D9", - "indigo_hover": "#4156C4", - "indigo_pressed": "#354BB4", - "indigo_pale": "#EEF1FA", - "focus": "#8B9AD9", - "selection": "#EEF1FA", - "success": "#287B65", - "success_pale": "#EEF7F3", - "warning": "#A9691D", - "warning_pale": "#FCF5E9", - "danger": "#BE4B58", - "danger_pale": "#FCF0F2", - "info": "#4F63D9", - "info_pale": "#EEF1FA", - # Backward-compatible names used by older UI code and integrations. - "ink": "#1A1C1F", - "ink_soft": "#606163", - "teal": "#4F63D9", - "teal_dark": "#354BB4", - "teal_pale": "#EEF1FA", + "canvas": PALETTE["canvas"], + "canvas_mid": PALETTE["surface"], + "canvas_glow": PALETTE["accent_soft"], + "surface": PALETTE["surface"], + "surface_alt": PALETTE["surface_alt"], + "raised": PALETTE["surface_alt"], + "glass": PALETTE["surface"], + "glass_alt": PALETTE["surface_alt"], + "line": PALETTE["line"], + "line_soft": PALETTE["line_strong"], + "text": PALETTE["heading"], + "text_soft": PALETTE["text"], + "muted": PALETTE["muted"], + "disabled_surface": PALETTE["disabled_surface"], + "disabled_text": PALETTE["disabled"], + "indigo": PALETTE["accent"], + "indigo_hover": PALETTE["accent_hover"], + "indigo_pressed": PALETTE["accent_pressed"], + "indigo_pale": PALETTE["accent_soft"], + "focus": PALETTE["focus"], + "selection": PALETTE["accent_soft"], + "success": PALETTE["success"], + "success_pale": PALETTE["success_soft"], + "warning": PALETTE["warning"], + "warning_pale": PALETTE["warning_soft"], + "danger": PALETTE["danger"], + "danger_pale": PALETTE["danger_soft"], + "info": PALETTE["accent"], + "info_pale": PALETTE["accent_soft"], + "ink": PALETTE["heading"], + "ink_soft": PALETTE["text"], + "teal": PALETTE["accent"], + "teal_dark": PALETTE["accent_pressed"], + "teal_pale": PALETTE["accent_soft"], } @@ -122,11 +122,11 @@ METRICS = { # ``outer - gap``. Where the gap is bigger than the outer radius the inner # element is far enough from the corner that its own radius is free. "r_xs": "4px", # chips, badges, tiny status pills - "r_sm": "6px", # inline row actions, tags - "r_md": "8px", # buttons, inputs, combo boxes - "r_lg": "12px", # cards, filter bars, panels - "r_xl": "16px", # the shell surfaces the cards sit on - "pad_control": "12px", # horizontal padding inside default controls + "r_sm": f"{RADII['small']}px", # inline row actions, tags + "r_md": f"{RADII['control']}px", # buttons, inputs, combo boxes + "r_lg": f"{RADII['panel']}px", # cards, filter bars, panels + "r_xl": f"{RADII['window']}px", # the shell surfaces the cards sit on + "pad_control": f"{SPACING['control']}px", # horizontal padding inside default controls "pad_compact": "9px", } @@ -176,7 +176,7 @@ QDialog[businessDialog="true"] QFrame#DialogSurface, QDialog[businessDialog="true"] QFrame[dialogSurface="true"] { background-color: $surface; border: 1px solid $line; - border-radius: 14px; + border-radius: $r_lg; } QDialog[businessDialog="true"] QFrame#DialogHeader, QDialog[businessDialog="true"] QFrame[dialogRole="header"] { @@ -275,18 +275,18 @@ QFrame#Card, QFrame#Panel, QFrame#FilterBar, QFrame#DetailPanel, QFrame[glass="true"] { background-color: $glass; border: 1px solid $line; - border-radius: 12px; + border-radius: $r_lg; } QFrame#FilterBar { background-color: $surface; } QFrame#SubtleCard { background-color: $glass_alt; border: 1px solid $line; - border-radius: 12px; + border-radius: $r_lg; } QFrame#MetricCard { background-color: $surface; border: 1px solid $line; - border-radius: 11px; + border-radius: $r_md; } QFrame#MetricCard:hover { border-color: $line_soft; background-color: $surface_alt; } QFrame#MetricCard QLabel[role="metricTitle"] { color: $muted; font-size: $fs_caption; } @@ -297,7 +297,7 @@ QFrame#ReceptionAiCard { min-height: 132px; background-color: #FFFFFF; border: 1px solid $line_soft; - border-radius: 13px; + border-radius: $r_lg; } QLabel#ReceptionAiTitle { color: $indigo_pressed; @@ -313,7 +313,7 @@ QLabel#MetricGlyph { color: $indigo; background-color: $indigo_pale; border: 1px solid $line_soft; - border-radius: 11px; + border-radius: $r_md; font-size: $fs_section; font-weight: $fw_heading; } @@ -329,7 +329,7 @@ QGroupBox { margin-top: 12px; padding-top: 12px; border: 1px solid $line; - border-radius: 12px; + border-radius: $r_lg; background-color: $glass; font-weight: $fw_control; } @@ -351,7 +351,7 @@ QPushButton { } QPushButton:hover { background-color: $raised; - border-color: $indigo_hover; + border-color: $line_soft; } QPushButton:pressed { background-color: $indigo_pale; @@ -401,7 +401,7 @@ QPushButton[variant="primary"]:disabled { QPushButton[variant="secondary"] { color: $indigo_hover; background-color: $indigo_pale; - border-color: $line_soft; + border-color: $indigo_pale; } QPushButton[variant="secondary"]:hover { color: $indigo_pressed; @@ -462,7 +462,7 @@ QToolButton#RowActionsMore::menu-indicator { width: 0; height: 0; image: none; } QFrame#NoteAttachmentTile { background-color: $surface; border: 1px solid $line; - border-radius: 10px; + border-radius: $r_md; } QPushButton#NoteAttachmentPreview { min-height: 132px; @@ -470,7 +470,7 @@ QPushButton#NoteAttachmentPreview { color: $muted; background-color: $surface_alt; border: 1px solid $line; - border-radius: 8px; + border-radius: $r_md; font-weight: $fw_control; } QPushButton#NoteAttachmentPreview:hover { @@ -558,7 +558,7 @@ QPushButton[variant="chip"] { color: $text_soft; background-color: $surface_alt; border-color: $line; - border-radius: 8px; + border-radius: $r_md; } QPushButton[variant="chip"]:hover { color: $text; @@ -653,7 +653,7 @@ QComboBox QAbstractItemView { background-color: $raised; alternate-background-color: $surface_alt; border: 1px solid $line; - border-radius: 10px; + border-radius: $r_md; padding: 5px; outline: 0; selection-background-color: $indigo_pressed; @@ -692,7 +692,7 @@ QAbstractItemView, QTableWidget, QTableView, QListWidget, QListView, QTreeWidget background-color: $surface; alternate-background-color: $surface_alt; border: 0; - border-radius: 12px; + border-radius: $r_lg; gridline-color: $line; selection-background-color: $selection; selection-color: $text; @@ -729,17 +729,17 @@ QListWidget::item:selected, QListView::item:selected, QTreeWidget::item:selected, QTreeView::item:selected { background-color: $indigo_pale; color: $indigo_pressed; - border-radius: 8px; + border-radius: $r_md; } QListWidget::item:hover, QListView::item:hover, QTreeWidget::item:hover, QTreeView::item:hover { background-color: $surface_alt; - border-radius: 8px; + border-radius: $r_md; } QTabWidget::pane { border: 1px solid $line; - border-radius: 12px; + border-radius: $r_lg; background-color: $glass; } QTabBar::tab { @@ -749,7 +749,7 @@ QTabBar::tab { color: $muted; background-color: transparent; border: 1px solid transparent; - border-radius: 9px; + border-radius: $r_md; font-weight: $fw_control; } QTabBar::tab:hover { color: $text; background-color: $surface_alt; } @@ -792,7 +792,7 @@ QMenu { color: $text; background-color: $raised; border: 1px solid $line_soft; - border-radius: 10px; + border-radius: $r_md; padding: 6px; } QMenu::item { @@ -815,7 +815,7 @@ QCalendarWidget { color: $text; background-color: $surface; border: 1px solid $line; - border-radius: 12px; + border-radius: $r_lg; } QCalendarWidget QWidget#qt_calendar_navigationbar { background-color: $raised; @@ -914,7 +914,7 @@ QWidget#Pager QLabel#PagerActive { color: #FFFFFF; background-color: $indigo; border: 1px solid $indigo; - border-radius: 8px; + border-radius: $r_md; font-size: $fs_caption; font-weight: $fw_control; } @@ -937,7 +937,7 @@ QLabel#EmptyStateGlyph { QFrame#MessageBanner { border: 1px solid $line; - border-radius: 10px; + border-radius: $r_md; color: $text_soft; } QFrame#MessageBanner QLabel { background-color: transparent; } @@ -955,7 +955,7 @@ QLabel#Toast { color: $text; background-color: $raised; border: 1px solid $line_soft; - border-radius: 11px; + border-radius: $r_md; padding: 11px 16px; font-weight: $fw_control; } @@ -995,13 +995,9 @@ QLabel#UserAvatar { font-weight: $fw_heading; } QWidget#LoginBrandPanel { - background-color: qlineargradient( - x1: 0, y1: 0, x2: 1, y2: 1, - stop: 0 $surface, - stop: 1 $canvas_glow - ); + background-color: $surface_alt; border: 1px solid $line_soft; - border-radius: 22px; + border-radius: $r_lg; } QFrame#LoginCard { background-color: $glass; @@ -1043,6 +1039,7 @@ QToolTip { } """ ).substitute(_QSS_TOKENS) +GLOBAL_QSS = clinical_stylesheet(GLOBAL_QSS) #: Per-block reading rhythm, in device pixels. ``(top, bottom, line%)``. diff --git a/app/src/doctor_workstation/ui/widgets.py b/app/src/doctor_workstation/ui/widgets.py index 60efcbfca..2c0b43167 100644 --- a/app/src/doctor_workstation/ui/widgets.py +++ b/app/src/doctor_workstation/ui/widgets.py @@ -44,6 +44,7 @@ from doctor_workstation.core.errors import ( ) from . import icons, motion +from .design_system import PALETTE AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool] _AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None @@ -798,7 +799,7 @@ class _BusyTrack(QWidget): chunk_width = max(36, int(rect.width() * 0.32)) span = rect.width() + chunk_width x = int(self._phase * span) - chunk_width - painter.setBrush(QColor("#4F63D9")) + painter.setBrush(QColor(PALETTE["accent"])) painter.drawRoundedRect(x, 0, chunk_width, rect.height(), 3, 3) diff --git a/app/src/doctor_workstation/video/im_ai.py b/app/src/doctor_workstation/video/im_ai.py new file mode 100644 index 000000000..a184cb34a --- /dev/null +++ b/app/src/doctor_workstation/video/im_ai.py @@ -0,0 +1,387 @@ +"""Bounded, Qt-independent AI requests for one authenticated IM window. + +Only server-archived clinical context is submitted. This module never sends IM +messages and never shares the ordered call/recording lifecycle worker. +""" + +from __future__ import annotations + +import re +from collections import deque +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from threading import BoundedSemaphore, Event, RLock, Thread +from time import monotonic +from typing import Any +from uuid import UUID, uuid4 + +MAX_RESULT_CHARS = 65_536 +MAX_SYNC_STEPS = 24 +SYNC_TIMEOUT_SECONDS = 45.0 +_WORKER_SLOTS = BoundedSemaphore(4) +_CANCEL_SLOTS = BoundedSemaphore(4) +_ACTIONS = frozenset({"summary", "followup", "reply"}) + + +def _integer(value: Any, *, minimum: int) -> int | None: + if isinstance(value, bool) or not isinstance(value, (int, str)): + return None + if isinstance(value, str) and re.fullmatch(r"0|[1-9][0-9]{0,18}", value) is None: + return None + number = int(value) + return number if minimum <= number < 2**63 else None + + +def _request_uuid(value: Any) -> bool: + if not isinstance(value, str) or len(value) != 36: + return False + try: + return str(UUID(value)) == value.lower() + except (ValueError, AttributeError): + return False + + +def task_prompt(action: str, doctor_account: str) -> tuple[str, str]: + """Keep instructions separate from clinical source text and under API limits.""" + + if action not in _ACTIONS or not re.fullmatch(r"doctor_[1-9][0-9]{0,18}", doctor_account): + raise ValueError("AI 操作或当前医生账号无效") + shared = ( + f"这是 IM 问诊辅助,本次医生 IM 账号为 {doctor_account}。" + "优先依据该医生与本患者最近已归档对话,结合服务端授权病历;" + "其他医生及历史记录仅作背景,不能当成本次已确认事实。" + "若未找到本次对话请明确说明,不猜测最新诉求。" + "区分已知、明确否认与未知,保留日期及不确定性;" + "不补问脉象,不编造事实、不自动确诊、不新增或更改药物剂量。" + ) + instructions = { + "summary": "请用简短条目总结本次病情、病程、现用治疗与待核实事项,供医生交接复核。", + "followup": ( + "请建议最多5条优先追问,直接给出可向患者询问的自然短句," + "每条可附简短目的;避免重复已回答的问题,不做通用问卷。" + ), + "reply": ( + "请起草一段医生可审阅后发给患者的简短自然回复,围绕该对话最近的患者问题。" + "不冒称已检查、已预约或已开处方,不承诺疗效,不让患者自行停换药。" + "只给回复草稿,不写分析过程;任何缺失资料通过必要的问题核实。" + ), + } + prompt = shared + instructions[action] + "此内容须由医生复核,不能自动发送。" + if len(prompt) > 500: + raise ValueError("AI 提示词超过接口长度限制") + return ("summary" if action == "summary" else "custom"), prompt + + +def _warnings(value: Any) -> list[str]: + if not isinstance(value, (list, tuple)): + return [] + warnings = [] + for row in value[:20]: + if isinstance(row, str): + text = row + elif isinstance(row, Mapping): + text = row.get("message") or row.get("label") + if not text and row.get("code"): + text = ( + "请复核回答中的脉象判断;本流程不采集脉象。" + if row["code"] == "PULSE_EXCLUDED_FROM_ASSESSMENT" + else "请对照原始记录复核,回答中的事实、否认或未知状态可能不一致。" + ) + else: + continue + if isinstance(text, str) and text.strip(): + rendered = text.strip()[:400] + if rendered not in warnings: + warnings.append(rendered) + return warnings + + +class _RequestError(Exception): + """A deliberately safe, user-facing failure message.""" + + +@dataclass +class _Job: + identity: dict[str, Any] + action: str + cancelled: Event = field(default_factory=Event) + completed: bool = False + succeeded: bool = False + stream_started: bool = False + cancel_sent: bool = False + + +class ImAiController: + """One live request, a coalesced mailbox, and bounded daemon workers. + + Qt polls ``take_result`` every 60 ms. Worker threads only mutate plain data; + they never touch a QObject. A cancelled worker must retire before a retry + starts, so rapid clicks cannot create an unbounded collection of requests. + """ + + def __init__( + self, + repository: Any, + *, + diagnosis_id: Any, + appointment_id: Any, + doctor_account: str, + enabled: bool = False, + clock: Callable[[], float] = monotonic, + max_sync_steps: int = MAX_SYNC_STEPS, + sync_timeout: float = SYNC_TIMEOUT_SECONDS, + ) -> None: + self.repository = repository + self.diagnosis_id = _integer(diagnosis_id, minimum=1) + self.appointment_id = _integer(appointment_id, minimum=0) + self.doctor_account = str(doctor_account) + self.enabled = ( + enabled is True + and repository is not None + and self.diagnosis_id is not None + and self.appointment_id is not None + and re.fullmatch(r"doctor_[1-9][0-9]{0,18}", self.doctor_account) is not None + ) + self.session_id = str(uuid4()) + self._clock = clock + self._max_sync_steps = max(1, min(MAX_SYNC_STEPS, max_sync_steps)) + self._sync_timeout = max(0.01, min(SYNC_TIMEOUT_SECONDS, sync_timeout)) + self._lock = RLock() + self._closed = False + self._current: _Job | None = None + self._running: _Job | None = None + self._worker: Thread | None = None + self._mailbox: dict[str, Any] | None = None + self._seen: deque[str] = deque(maxlen=256) + + @property + def config(self) -> dict[str, Any]: + return { + "version": 1, + "enabled": self.enabled and not self._closed, + "sessionId": self.session_id, + **({} if self.enabled else {"reason": "当前账号或问诊暂不能使用 AI 辅助。"}), + } + + def _valid_identity(self, message: Mapping[str, Any]) -> bool: + return ( + self.enabled + and not self._closed + and message.get("source") == "doctor-call" + and message.get("sessionId") == self.session_id + and _request_uuid(message.get("requestId")) + and isinstance(message.get("contextKey"), str) + and 0 < len(message["contextKey"]) <= 128 + and _integer(message.get("diagnosisId"), minimum=1) == self.diagnosis_id + and _integer(message.get("appointmentId"), minimum=0) == self.appointment_id + and isinstance(message.get("action"), str) + and message["action"] in _ACTIONS + ) + + def handle(self, message: Mapping[str, Any]) -> bool: + with self._lock: + if not self._valid_identity(message): + return False + event = message.get("event") + identity = {key: message[key] for key in ( + "sessionId", "requestId", "contextKey", "diagnosisId", "appointmentId", "action" + )} + if event == "im-ai-cancel": + if self._current is None or self._current.identity != identity: + return False + self._cancel(self._current) + return True + if event != "im-ai-request" or message["requestId"] in self._seen: + return False + self._seen.append(message["requestId"]) + job = _Job(identity, message["action"]) + if self._running is not None: + self._cancel(self._running) + self._current = job + self._publish(job, "error", message="上次请求正在结束,请稍后重试。", terminal=True) + return True + self._current = job + if not _WORKER_SLOTS.acquire(blocking=False): + self._publish(job, "error", message="AI 正在处理其他请求,请稍后重试。", terminal=True) + return True + self._running = job + self._publish(job, "loading", message="正在同步当前聊天记录…") + self._worker = Thread(target=self._run, args=(job,), name="im-ai", daemon=True) + try: + self._worker.start() + except RuntimeError: + self._running = None + _WORKER_SLOTS.release() + self._publish(job, "error", message="AI 请求暂时无法启动,请稍后重试。", terminal=True) + return True + + def _publish(self, job: _Job, status: str, *, terminal: bool = False, **fields: Any) -> None: + with self._lock: + if self._closed or self._current is not job or job.cancelled.is_set() or job.completed: + return + if terminal: + job.completed = True + job.succeeded = status == "success" + self._mailbox = {**job.identity, "status": status, **fields} + + def take_result(self) -> dict[str, Any] | None: + with self._lock: + result, self._mailbox = self._mailbox, None + return None if self._closed else result + + def _sync(self, job: _Job) -> bool: + deadline = self._clock() + self._sync_timeout + token = "" + for _ in range(self._max_sync_steps): + if job.cancelled.is_set(): + return False + if self._clock() >= deadline: + raise _RequestError("聊天同步超时,尚未生成,请稍后重试。") + result = self.repository.sync_im_chat_messages( + self.diagnosis_id, scope="current", sync_token=token + ) + if job.cancelled.is_set(): + return False + if self._clock() >= deadline: + raise _RequestError("聊天同步超时,尚未生成,请稍后重试。") + if not isinstance(result, Mapping) or result.get("errors"): + raise _RequestError("当前聊天记录未能完整同步,尚未生成,请稍后重试。") + if result.get("completed") is True: + return True + token = result.get("sync_token", "") + if not isinstance(token, str) or re.fullmatch(r"[a-f0-9]{48}", token) is None: + raise _RequestError("聊天同步进度无效,请更新客户端或稍后重试。") + raise _RequestError("聊天记录仍在同步,尚未生成,请稍后重试。") + + def _run(self, job: _Job) -> None: + try: + if not self._sync(job): + return + task, prompt = task_prompt(job.action, self.doctor_account) + with self._lock: + if job.cancelled.is_set() or self._closed: + return + job.stream_started = True + self._publish(job, "loading", message="聊天已同步,正在整理病历资料…") + if job.cancelled.is_set(): + return + text = "" + events = self.repository.stream_diagnosis_ai( + self.diagnosis_id, prompt, task=task, + request_id=job.identity["requestId"], cancelled=job.cancelled.is_set, + ) + try: + for event in events: + if job.cancelled.is_set(): + return + if not isinstance(event, Mapping): + continue + kind = event.get("event") + if kind == "delta": + delta = event.get("text", "") + if not isinstance(delta, str) or len(text) + len(delta) > MAX_RESULT_CHARS: + raise _RequestError("AI 内容超过显示上限,已停止接收,请缩小问题后重试。") + text += delta + self._publish(job, "streaming", text=text, message="正在生成,内容尚未完成。") + elif kind in {"start", "progress"}: + message = str(event.get("message") or "正在整理资料并生成…")[:240] + self._publish(job, "streaming" if text else "loading", text=text, message=message) + elif kind == "done": + result_id = event.get("diagnosis_id") + if result_id is not None and _integer(result_id, minimum=1) != self.diagnosis_id: + raise _RequestError("AI 返回的问诊上下文不匹配,结果未采用。") + answer = event.get("answer", event.get("content", text)) + if not isinstance(answer, str) or not answer.strip(): + raise _RequestError("AI 未返回完整内容,请重试。") + if len(answer) > MAX_RESULT_CHARS: + raise _RequestError("AI 内容超过显示上限,结果未采用,请缩小问题后重试。") + self._publish( + job, "success", terminal=True, text=answer, + message="已生成,请由医生复核后使用。", + modelLabel=str(event.get("model_label") or "")[:100], + warnings=_warnings(event.get("clinical_review_warnings")), + ) + return + elif kind == "error": + raise _RequestError("AI 请求未完成,请检查权限或稍后重试。") + if not job.cancelled.is_set(): + raise _RequestError("AI 连接提前结束,内容未完成,请重试。") + finally: + close = getattr(events, "close", None) + if callable(close): + close() + except Exception as error: + message = str(error) if isinstance(error, _RequestError) else ( + "AI 请求失败,请检查权限或稍后重试。" if job.stream_started + else "当前聊天同步失败,尚未生成,请检查权限或稍后重试。" + ) + self._publish(job, "error", message=message, terminal=True) + if job.stream_started and not job.cancelled.is_set() and not job.succeeded: + self._request_cancel(job) + finally: + with self._lock: + if self._running is job: + self._running = None + _WORKER_SLOTS.release() + + def _cancel(self, job: _Job) -> None: + if job.completed or job.cancelled.is_set(): + return + job.cancelled.set() + if self._current is job and not self._closed: + self._mailbox = { + **job.identity, "status": "cancelled", + "message": ("已停止本次接收,上游是否结束尚未确认。" if job.stream_started + else "已取消,尚未向 AI 提交请求。"), + } + if job.stream_started: + self._request_cancel(job) + + def _request_cancel(self, job: _Job) -> None: + with self._lock: + if job.cancel_sent: + return + job.cancel_sent = True + if not _CANCEL_SLOTS.acquire(blocking=False): + return + + def send() -> None: + try: + result = self.repository.cancel_diagnosis_ai(self.diagnosis_id, job.identity["requestId"]) + if not isinstance(result, Mapping): + return + message = "已发送取消请求,上游是否结束尚未确认。" + terminal = result.get("upstream_terminal_status") + if result.get("upstream_terminal_confirmed") is True and terminal in {"stopped", "succeeded", "failed"}: + message = "本次接收已停止,上游工作流已结束。" + elif result.get("upstream_stop_confirmed") is True: + message = "上游已接受停止请求,是否结束尚未确认。" + with self._lock: + if not self._closed and self._current is job and job.cancelled.is_set(): + self._mailbox = {**job.identity, "status": "cancelled", "message": message} + except Exception: + pass # Keep the visible unconfirmed cancellation; never expose transport details. + finally: + _CANCEL_SLOTS.release() + + try: + Thread(target=send, name="im-ai-cancel", daemon=True).start() + except RuntimeError: + _CANCEL_SLOTS.release() + + def close(self) -> None: + with self._lock: + if self._closed: + return + self._closed = True + self._mailbox = None + if self._running is not None: + self._cancel(self._running) + + def wait(self, timeout: float = 1.0) -> bool: + """Bounded diagnostic/test helper; never called by the Qt GUI.""" + + worker = self._worker + if worker is not None: + worker.join(max(0.0, min(timeout, 5.0))) + return worker is None or not worker.is_alive() diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py index f4efccbe9..45051df94 100644 --- a/app/src/doctor_workstation/video/launcher.py +++ b/app/src/doctor_workstation/video/launcher.py @@ -413,6 +413,7 @@ class VideoCallLauncher: patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, on_open_diagnosis: Callable[[], None] | None = None, + can_ai_assistant: bool = False, ) -> Any: request = self.prepare( ticket, @@ -432,6 +433,7 @@ class VideoCallLauncher: patient_name=patient_name, patient_case=patient_case, on_open_diagnosis=on_open_diagnosis, + can_ai_assistant=can_ai_assistant is True, ) @@ -450,6 +452,7 @@ def launch_video_call( patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, on_open_diagnosis: Callable[[], None] | None = None, + can_ai_assistant: bool = False, ) -> Any: """Normalize a ticket and open a call with the requested backend.""" @@ -468,4 +471,5 @@ def launch_video_call( patient_name=patient_name, patient_case=patient_case, on_open_diagnosis=on_open_diagnosis, + can_ai_assistant=can_ai_assistant is True, ) diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index 1129e7447..aab06b288 100644 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -28,6 +28,7 @@ from ..services.local_audio_queue import ( LocalAudioUploadManager, get_local_audio_upload_manager, ) +from .im_ai import ImAiController from .launcher import ( VideoCallRequest, VideoTicketError, @@ -320,6 +321,8 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, on_open_diagnosis: Callable[[], None] | None = None, + can_ai_assistant: bool = False, + repository: Any = None, ) -> None: super().__init__() self.request = request @@ -349,6 +352,18 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._call_cycle_closed = False self._start_requested = False self._shutdown_requested = False + self._im_ai = ImAiController( + repository, + diagnosis_id=request.diagnosis_id, + appointment_id=request.appointment_id, + doctor_account=request.user_id, + enabled=can_ai_assistant is True and self.open_im, + ) + self._im_ai_timer = QTimer(self) + self._im_ai_timer.setInterval(60) + self._im_ai_timer.timeout.connect(self._flush_im_ai) + if self._im_ai.enabled: + self._im_ai_timer.start() self._screenshot_preview_size = ScreenshotPreviewSize() self._local_audio_capture: _LocalAudioCapture | None = None self._local_audio_store: LocalAudioQueueStore | None = None @@ -483,6 +498,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration "patientName": self.patient_name, "patientCase": self.patient_case, "mode": "chat" if self.open_im else "video", + "imAi": self._im_ai.config, } config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":")) script = f""" @@ -524,11 +540,23 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._injected = result is not False if not self._injected: self._request_companion_shutdown("bridge-api-missing") + return + if not self._im_ai_context_is_trusted(): + return + # open() may finish IM login before runJavaScript returns. Only + # acknowledge readiness after the native request gate is open. + session_id = json.dumps(self._im_ai.session_id, ensure_ascii=True) + self._page.runJavaScript( + f"window.doctorConsultation?.imAiReady?.({session_id});" + ) def _handle_bridge_message(self, message: Mapping[str, Any]) -> None: if self._closing: return event = str(message.get("event", "")) + if event in {"im-ai-request", "im-ai-cancel"}: + self._handle_im_ai_message(message) + return if event == "screenshot-preview": visible = message.get("visible") if isinstance(visible, bool): @@ -622,6 +650,35 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration if not self.open_im or self._shutdown_requested: self._close_from_companion("companion-error") + def _im_ai_context_is_trusted(self) -> bool: + return ( + not self._closing + and not self._released + and not self._shutdown_requested + and self._injected + and self._policy.allows_main_document(self._page.url().toString()) + ) + + def _handle_im_ai_message(self, message: Mapping[str, Any]) -> None: + if self._im_ai_context_is_trusted(): + self._im_ai.handle(message) + + def _flush_im_ai(self) -> None: + if not self._im_ai_context_is_trusted(): + return + result = self._im_ai.take_result() + if result is not None: + payload = json.dumps(result, ensure_ascii=True, separators=(",", ":")) + self._page.runJavaScript(f"window.doctorConsultation?.imAiResult?.({payload});") + + def _close_im_ai(self) -> None: + controller = getattr(self, "_im_ai", None) + if controller is not None: + controller.close() + timer = getattr(self, "_im_ai_timer", None) + if timer is not None: + timer.stop() + def _open_diagnosis_safely(self) -> None: if self._closing or self._on_open_diagnosis is None: return @@ -1197,6 +1254,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration def _request_companion_shutdown(self, reason: str) -> None: """Let MediaRecorder finish and upload before WebEngine is destroyed.""" + _EmbeddedVideoWindow._close_im_ai(self) self._close_reason = reason if self._closing or self._released: return @@ -1241,6 +1299,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration def _begin_shutdown(self) -> None: if self._closing: return + _EmbeddedVideoWindow._close_im_ai(self) self._on_compact_close = None self._closing = True self._media_active = False @@ -1342,6 +1401,7 @@ class VideoCallWindow: patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, on_open_diagnosis: Callable[[], None] | None = None, + can_ai_assistant: bool = False, ) -> None: del browser_opener # Reserved for a future authenticated handoff implementation. try: @@ -1360,6 +1420,7 @@ class VideoCallWindow: self.open_im = bool(open_im) self.patient_name = str(patient_name or "患者").strip() or "患者" self.patient_case = dict(patient_case or {}) + self.can_ai_assistant = can_ai_assistant is True self.on_open_diagnosis = on_open_diagnosis self.logger = logger or _LOGGER self.location = resolve_companion_location( @@ -1391,6 +1452,8 @@ class VideoCallWindow: patient_name=self.patient_name, patient_case=self.patient_case, on_open_diagnosis=self.on_open_diagnosis, + can_ai_assistant=self.can_ai_assistant, + repository=self.repository, ) except Exception: self.lifecycle.end("window-open-failed") @@ -1436,6 +1499,7 @@ def open_video_call( patient_name: str = "患者", patient_case: Mapping[str, Any] | None = None, on_open_diagnosis: Callable[[], None] | None = None, + can_ai_assistant: bool = False, ) -> VideoCallWindow: """Create and immediately open a trusted embedded video window.""" @@ -1452,6 +1516,7 @@ def open_video_call( patient_name=patient_name, patient_case=patient_case, on_open_diagnosis=on_open_diagnosis, + can_ai_assistant=can_ai_assistant, ).open() diff --git a/app/tests/test_ai_consult_ui.py b/app/tests/test_ai_consult_ui.py index d68fc681c..1c886d97f 100644 --- a/app/tests/test_ai_consult_ui.py +++ b/app/tests/test_ai_consult_ui.py @@ -26,6 +26,7 @@ from PySide6.QtWidgets import ( from doctor_workstation.core import PermissionSet from doctor_workstation.services import ApiClient, DemoDoctorRepository, RemoteDoctorRepository +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.dialogs import ai_consult as ai_consult_module from doctor_workstation.ui.dialogs.ai_consult import ( AiConsultDialog, @@ -2306,14 +2307,14 @@ def test_risk_block_uses_the_red_alert_palette() -> None: assert "#FEF3F2" in risk_card assert "#F1B35C" not in risk_card # 旧的橙色描边 marker = qss.split("QLabel#AiConsultRiskMarker {", 1)[1].split("}", 1)[0] - assert "#BE4B58" in marker + assert PALETTE["danger"] in marker def test_clinical_bodies_are_no_longer_rendered_at_eleven_pixels() -> None: qss = ai_consult_module.AI_CONSULT_QSS body = qss.rsplit("QLabel#AiConsultRiskBody {", 1)[1].split("}", 1)[0] - assert "color: #1a1c1f" in body.lower() + assert f'color: {PALETTE["text"]}' in body assert "font-size: 14px" in body block = qss.split("QLabel#AiConsultClinicalBody,", 1)[1].split("}", 1)[0] assert "font-size: 14px" in block diff --git a/app/tests/test_appointment_drawer_visual.py b/app/tests/test_appointment_drawer_visual.py index c34129ae7..fe057392a 100644 --- a/app/tests/test_appointment_drawer_visual.py +++ b/app/tests/test_appointment_drawer_visual.py @@ -10,6 +10,7 @@ from PySide6.QtCore import QDate, QSize, Qt from PySide6.QtWidgets import QApplication, QStyle, QStyleOptionButton, QWidget from doctor_workstation.ui.appointment_drawer import APPOINTMENT_DRAWER_QSS, AppointmentDrawer +from doctor_workstation.ui.design_system import PALETTE @pytest.fixture(scope="module") @@ -565,8 +566,39 @@ def test_keyboard_focus_has_a_visible_state( assert focus_target.hasFocus() assert application.focusWidget() is focus_target assert 'QPushButton[appointmentDate="true"]:focus' in APPOINTMENT_DRAWER_QSS - assert "border-color: #8B9AD9;" in APPOINTMENT_DRAWER_QSS + assert f"border-color: {PALETTE['focus']};" in APPOINTMENT_DRAWER_QSS drawer.close() host.close() application.processEvents() + + +@pytest.mark.parametrize("button_kind", ["date", "slot"]) +def test_appointment_hover_keeps_hit_target_stable_after_relayout( + application: QApplication, button_kind: str, +) -> None: + """Hovering must not move a time choice or restore a stale layout position.""" + from PySide6.QtCore import QEvent, QPoint, QPointF + from PySide6.QtGui import QEnterEvent + + host, drawer = _show_drawer( + application, (1440, 900), repository=_VisualRepository(), autoload=True, + ) + tomorrow = QDate.currentDate().addDays(1).toString("yyyy-MM-dd") + button = drawer.date_buttons[tomorrow] if button_kind == "date" else drawer.slot_buttons["09:30-10:00"] + original = button.geometry() + try: + for _ in range(3): + application.sendEvent(button, QEnterEvent(QPointF(10, 10), QPointF(30, 34), QPointF(30, 34))) + assert button.geometry() == original + assert button.graphicsEffect() is None + relocated = original.topLeft() + QPoint(12, 16) + button.move(relocated) # A resize/reflow while the pointer stays inside. + application.sendEvent(button, QEvent(QEvent.Type.Leave)) + assert button.pos() == relocated + button.setGeometry(original) + button.click() + assert button.isChecked() + finally: + drawer.close() + host.close() diff --git a/app/tests/test_diagnosis_drawer_visual.py b/app/tests/test_diagnosis_drawer_visual.py index 470facfa2..8d8693307 100644 --- a/app/tests/test_diagnosis_drawer_visual.py +++ b/app/tests/test_diagnosis_drawer_visual.py @@ -22,6 +22,7 @@ from PySide6.QtWidgets import ( ) from doctor_workstation.core import PermissionSet +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.diagnosis_drawer import ( DiagnosisChoiceButtons, DiagnosisComboBox, @@ -1012,14 +1013,14 @@ def test_choice_chips_keep_visible_checked_style_when_readonly( application.processEvents() # Sample the pad (not glyph center) so white text does not hide the fill. enabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2) - assert enabled_color.name().lower() == "#eef1fa" + assert enabled_color.name().lower() == PALETTE["accent_soft"].lower() diet.setReadOnly(True) application.processEvents() disabled_color = selected.grab().toImage().pixelColor(6, selected.height() // 2) assert selected.isChecked() assert selected.isEnabled() assert diet.isReadOnly() - assert disabled_color.name().lower() == "#eef1fa" + assert disabled_color.name().lower() == PALETTE["accent_soft"].lower() dialog.close() application.processEvents() @@ -1039,7 +1040,7 @@ def test_view_only_drawer_shows_selected_choice_chips( selected = next(button for button in diet._buttons if button.isChecked()) application.processEvents() color = selected.grab().toImage().pixelColor(6, selected.height() // 2) - assert color.name().lower() == "#eef1fa" + assert color.name().lower() == PALETTE["accent_soft"].lower() assert diet.isReadOnly() assert not dialog.save_button.isVisibleTo(dialog) dialog.close() diff --git a/app/tests/test_diagnosis_index_visual.py b/app/tests/test_diagnosis_index_visual.py index 450def724..75050d297 100644 --- a/app/tests/test_diagnosis_index_visual.py +++ b/app/tests/test_diagnosis_index_visual.py @@ -23,6 +23,7 @@ from PySide6.QtWidgets import ( ) from doctor_workstation.core import PermissionSet +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.diagnosis_index_widgets import ( DIAGNOSIS_INDEX_QSS, DiagnosisItemDelegate, @@ -424,8 +425,8 @@ def test_empty_loading_and_compact_footer_keep_the_table_shell( @pytest.mark.parametrize( ("record", "stripe", "channel"), [ - (_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), "#a9691d", "warning"), - (_row(702, has_appointment=0, appointments=[]), "#4f63d9", "info"), + (_row(701, DiagnosisViewRecord=[{"is_confirmed": 0}]), PALETTE["warning"].lower(), "warning"), + (_row(702, has_appointment=0, appointments=[]), PALETTE["accent"].lower(), "info"), ], ) def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background( @@ -452,9 +453,9 @@ def test_semantic_hover_preserves_three_pixel_stripe_on_neutral_background( assert image.pixelColor(0, 20).name() == stripe assert image.pixelColor(1, 20).name() == stripe assert image.pixelColor(2, 20).name() == stripe - assert image.pixelColor(3, 20).name() == "#f7f7f7", f"{channel} stripe widened" - assert image.pixelColor(6, 20).name() == "#f7f7f7" - assert image.pixelColor(40, 20).name() == "#f7f7f7" + assert image.pixelColor(3, 20).name() == PALETTE["surface_alt"].lower(), f"{channel} stripe widened" + assert image.pixelColor(6, 20).name() == PALETTE["surface_alt"].lower() + assert image.pixelColor(40, 20).name() == PALETTE["surface_alt"].lower() def test_page_hides_fixed_shadow_and_preserves_admin_token_contract( diff --git a/app/tests/test_diagnosis_table_blue.py b/app/tests/test_diagnosis_table_blue.py index fd129b46e..f26add35a 100644 --- a/app/tests/test_diagnosis_table_blue.py +++ b/app/tests/test_diagnosis_table_blue.py @@ -9,10 +9,17 @@ from pathlib import Path os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import pytest -from PySide6.QtCore import QPoint, Qt -from PySide6.QtGui import QFont +from PySide6.QtCore import QPoint, QRect, Qt +from PySide6.QtGui import QFont, QImage, QPainter from PySide6.QtTest import QTest -from PySide6.QtWidgets import QApplication, QLabel, QToolButton, QVBoxLayout, QWidget +from PySide6.QtWidgets import ( + QApplication, + QLabel, + QStyleOptionViewItem, + QToolButton, + QVBoxLayout, + QWidget, +) from doctor_workstation.ui.diagnosis_index_widgets import ( DiagnosisTableHost, @@ -115,6 +122,79 @@ def test_blue_metrics_are_opt_in_and_expand_for_complete_content(application: QA legacy.close() +@pytest.mark.parametrize( + "size,column_width,row_height", + [((1024, 640), 84, 75), ((1440, 900), 126, 72)], +) +def test_followup_paint_keeps_time_whole_and_preserves_density( + application: QApplication, size: tuple[int, int], column_width: int, row_height: int, +) -> None: + class RecordingPainter(QPainter): + def __init__(self, image: QImage) -> None: + super().__init__(image) + self.lines: list[tuple[QRect, int, str]] = [] + + def drawText(self, rect: QRect, flags: int, text: str) -> None: # noqa: N802 + self.lines.append((QRect(rect), flags, text)) + super().drawText(rect, flags, text) + + row = { + "id": 501, "has_prescription": 1, + "followup_time_text": "2026-08-17 09:00", "followup_doctor_name": "陈医生", + } + original = copy.deepcopy(row) + host = DiagnosisTableHost(tech_blue=True) + host.resize(*size) + host.set_rows([row]) + host.show() + _settle(application) + try: + assert host.main.columnWidth(6) == column_width + assert host.main.rowHeight(0) == row_height + assert host.fixed.rowHeight(0) == row_height + index = host.model.index(0, 6) + full_text = "2026-08-17 09:00\n陈医生" + assert index.data() == full_text + assert index.data(Qt.ItemDataRole.ToolTipRole) == full_text + option = QStyleOptionViewItem() + option.rect = QRect(0, 0, column_width, row_height) + image = QImage(column_width, row_height, QImage.Format.Format_ARGB32) + painter = RecordingPainter(image) + host.main.itemDelegate().paint(painter, option, index) + painter.end() + expected = ["2026-08-17", "09:00", "陈医生"] if size[0] == 1024 else [ + "2026-08-17 09:00", "陈医生", + ] + assert [line[2] for line in painter.lines] == expected + content = option.rect.adjusted(8, 8, -8, -8) + for rect, flags, _text in painter.lines: + assert content.contains(rect) + assert flags & Qt.TextFlag.TextSingleLine + assert not flags & Qt.TextFlag.TextWrapAnywhere + assert row == original + finally: + host.close() + _settle(application) + + +def test_followup_long_metadata_has_complete_tooltip(application: QApplication) -> None: + host = DiagnosisTableHost(tech_blue=True) + row = { + "id": 502, "has_prescription": 1, + "followup_time_text": "2026-08-17 09:00-09:30", + "followup_doctor_name": "陈医生(内分泌科专家门诊)", "followup_rx_voided": True, + } + original = copy.deepcopy(row) + host.set_rows([row]) + index = host.model.index(0, 6) + assert index.data(Qt.ItemDataRole.ToolTipRole) == ( + "2026-08-17 09:00-09:30\n陈医生(内分泌科专家门诊)\n处方已作废" + ) + assert index.data() == index.data(Qt.ItemDataRole.ToolTipRole) + assert row == original + host.close() + + @pytest.mark.parametrize("tech_blue", [False, True]) def test_geometry_has_no_minimum_height_feedback_and_tracks_both_scroll_axes( application: QApplication, tech_blue: bool, diff --git a/app/tests/test_doctor_selection.py b/app/tests/test_doctor_selection.py index c0729c7d4..342609447 100644 --- a/app/tests/test_doctor_selection.py +++ b/app/tests/test_doctor_selection.py @@ -8,6 +8,7 @@ from PySide6.QtCore import QPoint, Qt, QTimer from PySide6.QtTest import QTest from PySide6.QtWidgets import QApplication +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.pages.prescriptions import DoctorMultiSelect, _DoctorSelectionDialog from doctor_workstation.ui.theme import apply_theme @@ -74,7 +75,7 @@ def test_checked_row_blue_and_unchecked_white(dialog, application): rect = dialog.listing.visualItemRect(item_for(dialog, doctor_id)) colors.append(image.pixelColor(int((rect.right() - 70) * scale), int(rect.center().y() * scale)).name()) - assert colors == ["#eaf2ff", "#ffffff"] + assert colors == [PALETTE["accent_soft"].lower(), PALETTE["surface"].lower()] def test_accept_commits_cancel_preserves_and_reopen_restores(application): diff --git a/app/tests/test_im_ai_repository.py b/app/tests/test_im_ai_repository.py new file mode 100644 index 000000000..91e38d722 --- /dev/null +++ b/app/tests/test_im_ai_repository.py @@ -0,0 +1,42 @@ +"""Current-peer archive paging preserves old callers and request identities.""" + +import pytest + +from doctor_workstation.services.mock_repository import DemoDoctorRepository +from doctor_workstation.services.repository import RemoteDoctorRepository + + +class Client: + def __init__(self): + self.calls = [] + + def post(self, endpoint, payload, *, timeout=None): + self.calls.append((endpoint, payload, timeout)) + return {"completed": False, "sync_token": "a" * 48, "errors": []} + + +def test_sync_optional_parameters_and_timeout_preserve_exact_legacy_payload(): + client = Client() + repository = RemoteDoctorRepository(client) + repository.sync_im_chat_messages(501) + result = repository.sync_im_chat_messages(501, scope="current", sync_token="a" * 48) + assert client.calls == [ + ("tcm.diagnosis/triggerImChatSync", {"diagnosis_id": 501}, 15.0), + ("tcm.diagnosis/triggerImChatSync", + {"diagnosis_id": 501, "scope": "current", "sync_token": "a" * 48}, 15.0), + ] + assert result["completed"] is False + + +@pytest.mark.parametrize("kwargs", [{"scope": "other"}, {"sync_token": "bad"}, {"sync_token": None}]) +def test_sync_rejects_invalid_options_without_network(kwargs): + client = Client() + with pytest.raises(ValueError): + RemoteDoctorRepository(client).sync_im_chat_messages(501, **kwargs) + assert not client.calls + + +def test_mock_sync_supports_paging_contract_and_legacy_receipt(): + repository = DemoDoctorRepository() + assert repository.sync_im_chat_messages(501)["queued"] is True + assert repository.sync_im_chat_messages(501, scope="current")["completed"] is True diff --git a/app/tests/test_im_ai_service.py b/app/tests/test_im_ai_service.py new file mode 100644 index 000000000..99606401b --- /dev/null +++ b/app/tests/test_im_ai_service.py @@ -0,0 +1,270 @@ +"""Offline tests for native IM AI authorization, synchronization and races.""" + +from __future__ import annotations + +from collections import deque +from threading import BoundedSemaphore, Event +from uuid import uuid4 + +import pytest + +from doctor_workstation.video import im_ai + + +class Repository: + def __init__(self, pages=None, events=None): + self.pages = deque(pages or [{"completed": True, "errors": []}]) + self.events = events or [{"event": "done", "diagnosis_id": 501, "answer": "合成回复"}] + self.sync_calls = [] + self.stream_calls = [] + self.cancel_calls = [] + self.cancel_called = Event() + + def sync_im_chat_messages(self, diagnosis_id, **kwargs): + self.sync_calls.append((diagnosis_id, kwargs)) + return self.pages.popleft() + + def stream_diagnosis_ai(self, diagnosis_id, prompt, **kwargs): + self.stream_calls.append((diagnosis_id, prompt, kwargs)) + yield from self.events + + def cancel_diagnosis_ai(self, diagnosis_id, request_id): + self.cancel_calls.append((diagnosis_id, request_id)) + self.cancel_called.set() + return {"cancel_requested": True} + + +def controller(repository=None, **kwargs): + return im_ai.ImAiController( + repository or Repository(), diagnosis_id=501, appointment_id=101, + doctor_account="doctor_7", enabled=True, **kwargs, + ) + + +def request(service, **changes): + return { + "source": "doctor-call", "event": "im-ai-request", "sessionId": service.session_id, + "requestId": str(uuid4()), "contextKey": "view-1", "diagnosisId": "501", + "appointmentId": 101, "action": "summary", **changes, + } + + +@pytest.mark.parametrize("action,task", [("summary", "summary"), ("followup", "custom"), ("reply", "custom")]) +def test_current_peer_sync_completes_before_ai_and_keeps_identity(action, task): + token = "a" * 48 + repository = Repository(pages=[ + {"completed": False, "phase": "checking_accounts", "sync_token": token, "errors": []}, + {"completed": False, "phase": "syncing", "sync_token": token, "errors": []}, + {"completed": True, "errors": []}, + ], events=[ + {"event": "start"}, {"event": "delta", "text": "合成"}, + {"event": "done", "diagnosis_id": 501, "answer": "合成完整回复", "model_label": "模型", + "clinical_review_warnings": [{"code": "PULSE_EXCLUDED_FROM_ASSESSMENT", "source_id": "report"}]}, + ]) + service = controller(repository) + message = request(service, action=action) + assert service.handle(message) + assert service.wait() + result = service.take_result() + assert result["status"] == "success" + assert result["text"] == "合成完整回复" + assert result["requestId"] == message["requestId"] + assert result["modelLabel"] == "模型" + assert "不采集脉象" in result["warnings"][0] + assert len(repository.sync_calls) == 3 + assert repository.sync_calls[0] == (501, {"scope": "current", "sync_token": ""}) + assert repository.sync_calls[1][1]["sync_token"] == token + assert len(repository.stream_calls) == 1 + diagnosis_id, prompt, options = repository.stream_calls[0] + assert diagnosis_id == 501 and options["task"] == task + assert options["request_id"] == message["requestId"] + assert "doctor_7" in prompt and len(prompt) <= 500 + assert "不补问脉象" in prompt and "不自动确诊" in prompt + assert not repository.cancel_calls + assert service.take_result() is None + assert not service.handle(message) # A replay cannot submit another billable request. + + +@pytest.mark.parametrize("changes", [ + {"sessionId": "other"}, {"diagnosisId": "502"}, {"diagnosisId": True}, + {"diagnosisId": "0501"}, {"appointmentId": 102}, {"requestId": "invalid"}, + {"contextKey": ""}, {"contextKey": "x" * 129}, {"action": "prescription"}, + {"action": {}}, {"source": "another-page"}, {"event": "send-message"}, +]) +def test_invalid_identity_or_action_cannot_read_patient_context(changes): + repository = Repository() + service = controller(repository) + assert not service.handle(request(service, **changes)) + assert not repository.sync_calls and not repository.stream_calls + + +def test_permission_default_denied_and_each_host_has_unique_session(): + repository = Repository() + disabled = im_ai.ImAiController( + repository, diagnosis_id=501, appointment_id=101, doctor_account="doctor_7" + ) + assert disabled.config["enabled"] is False + assert not disabled.handle(request(disabled)) + assert controller().session_id != controller().session_id + + +@pytest.mark.parametrize("page", [ + {"queued": True}, {"completed": "true"}, {"completed": True, "errors": ["private detail"]}, + {"completed": False, "sync_token": "bad"}, None, +]) +def test_incomplete_or_failed_sync_never_generates(page): + repository = Repository(pages=[page]) + service = controller(repository) + assert service.handle(request(service)) + assert service.wait() + result = service.take_result() + assert result["status"] == "error" + assert "private detail" not in str(result) + assert not repository.stream_calls and not repository.cancel_calls + + +def test_sync_step_and_time_budget_are_bounded(): + page = {"completed": False, "sync_token": "b" * 48, "errors": []} + repository = Repository(pages=[page] * 10) + service = controller(repository, max_sync_steps=2) + service.handle(request(service)) + assert service.wait() + assert len(repository.sync_calls) == 2 + assert service.take_result()["status"] == "error" + assert not repository.stream_calls + + times = iter([0, 0, 46]) + repository = Repository() + service = controller(repository, clock=lambda: next(times)) + service.handle(request(service)) + assert service.wait() + assert "超时" in service.take_result()["message"] + assert not repository.stream_calls + + +def test_cancel_during_sync_stops_before_model_submission(): + entered, release = Event(), Event() + + class SlowSync(Repository): + def sync_im_chat_messages(self, diagnosis_id, **kwargs): + entered.set() + assert release.wait(2) + return super().sync_im_chat_messages(diagnosis_id, **kwargs) + + repository = SlowSync() + service = controller(repository) + message = request(service) + service.handle(message) + try: + assert entered.wait(1) + assert service.handle({**message, "event": "im-ai-cancel"}) + assert "尚未向 AI" in service.take_result()["message"] + finally: + release.set() + assert service.wait() + assert not repository.stream_calls and not repository.cancel_calls + assert service.take_result() is None + + +def test_cancel_is_independent_and_late_response_cannot_overwrite_next_request(): + entered, release, cancel_release = Event(), Event(), Event() + + class SlowStream(Repository): + def stream_diagnosis_ai(self, *args, **kwargs): + self.stream_calls.append((args, kwargs)) + yield {"event": "delta", "text": "尚未完成"} + entered.set() + assert release.wait(2) + yield {"event": "done", "answer": "迟到的旧结果"} + + def cancel_diagnosis_ai(self, *args): + result = super().cancel_diagnosis_ai(*args) + assert cancel_release.wait(2) + return result + + repository = SlowStream() + service = controller(repository) + first = request(service) + service.handle(first) + try: + assert entered.wait(1) + assert service.take_result()["text"] == "尚未完成" + service.handle({**first, "event": "im-ai-cancel"}) + assert repository.cancel_called.wait(1) # Independent HTTP starts while stream is blocked. + assert service.take_result()["status"] == "cancelled" + second = request(service, contextKey="view-2") + assert service.handle(second) + result = service.take_result() + assert result["requestId"] == second["requestId"] and result["status"] == "error" + assert len(repository.stream_calls) == 1 + finally: + release.set() + cancel_release.set() + assert service.wait() + assert service.take_result() is None + + +def test_close_invalidates_mailbox_and_cancels_without_waiting(): + entered, release = Event(), Event() + + class SlowStream(Repository): + def stream_diagnosis_ai(self, *args, **kwargs): + entered.set() + assert release.wait(2) + yield {"event": "done", "answer": "旧患者回复"} + + repository = SlowStream() + service = controller(repository) + message = request(service) + service.handle(message) + try: + assert entered.wait(1) + service.close() + assert repository.cancel_called.wait(1) + assert service.take_result() is None + assert not service.handle(request(service)) + finally: + release.set() + assert service.wait() + assert service.take_result() is None + + +@pytest.mark.parametrize("events", [ + [{"event": "delta", "text": "不完整"}], + [{"event": "done", "answer": ""}], + [{"event": "done", "diagnosis_id": 502, "answer": "其他患者"}], + [{"event": "delta", "text": "x" * (im_ai.MAX_RESULT_CHARS + 1)}], + [{"event": "done", "answer": "x" * (im_ai.MAX_RESULT_CHARS + 1)}], +]) +def test_incomplete_mismatched_and_oversized_results_are_not_usable(events): + repository = Repository(events=events) + service = controller(repository) + service.handle(request(service)) + assert service.wait() + assert service.take_result()["status"] == "error" + assert repository.cancel_called.wait(1) + assert len(repository.stream_calls) == 1 # No transport/validation retry. + + +def test_thousands_of_deltas_are_coalesced_into_one_mailbox_result(): + events = [{"event": "delta", "text": "字"}] * 4000 + [{"event": "done"}] + service = controller(Repository(events=events)) + service.handle(request(service)) + assert service.wait() + result = service.take_result() + assert result["status"] == "success" and result["text"] == "字" * 4000 + assert service.take_result() is None + + +def test_capacity_rejection_does_not_spawn_or_sync(monkeypatch): + slots = BoundedSemaphore(1) + slots.acquire() + monkeypatch.setattr(im_ai, "_WORKER_SLOTS", slots) + repository = Repository() + service = controller(repository) + try: + service.handle(request(service)) + assert service.take_result()["status"] == "error" + assert not repository.sync_calls + finally: + slots.release() diff --git a/app/tests/test_im_ai_window.py b/app/tests/test_im_ai_window.py new file mode 100644 index 000000000..c0107bc3d --- /dev/null +++ b/app/tests/test_im_ai_window.py @@ -0,0 +1,157 @@ +"""Exercise bridge trust and JSON delivery without starting WebEngine or HTTP.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from doctor_workstation.video import window +from doctor_workstation.video.security import TrustedDocumentPolicy + +pytestmark = pytest.mark.skipif(not window.WEBENGINE_AVAILABLE, reason="optional QtWebEngine") +TRUSTED = "https://video.example.test/im/index.html" + + +def host(**changes): + item = SimpleNamespace( + _closing=False, _released=False, _shutdown_requested=False, _injected=True, + _policy=TrustedDocumentPolicy.from_url(TRUSTED, is_local=False), + _page=Mock(), _im_ai=Mock(), _im_ai_timer=Mock(), + ) + item._page.url.return_value.toString.return_value = TRUSTED + item._im_ai_context_is_trusted = lambda: window._EmbeddedVideoWindow._im_ai_context_is_trusted(item) + for key, value in changes.items(): + setattr(item, key, value) + return item + + +@pytest.mark.parametrize("changes", [ + {"_closing": True}, {"_released": True}, {"_shutdown_requested": True}, {"_injected": False}, +]) +def test_inactive_or_closing_page_cannot_submit_or_receive_ai(changes): + item = host(**changes) + window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"}) + window._EmbeddedVideoWindow._flush_im_ai(item) + item._im_ai.handle.assert_not_called() + item._im_ai.take_result.assert_not_called() + item._page.runJavaScript.assert_not_called() + + +@pytest.mark.parametrize("url", ["about:blank", "https://evil.example.test/im/index.html", TRUSTED + "?other=1"]) +def test_document_navigation_cannot_reuse_authenticated_ai_bridge(url): + item = host() + item._page.url.return_value.toString.return_value = url + window._EmbeddedVideoWindow._handle_im_ai_message(item, {"event": "im-ai-request"}) + window._EmbeddedVideoWindow._flush_im_ai(item) + item._im_ai.handle.assert_not_called() + item._page.runJavaScript.assert_not_called() + + +def test_trusted_bridge_routes_only_to_identity_checked_controller(): + item = host() + message = {"source": "doctor-call", "event": "im-ai-request", "diagnosisId": 501} + window._EmbeddedVideoWindow._handle_im_ai_message(item, message) + item._im_ai.handle.assert_called_once_with(message) + + +def test_result_content_is_json_encoded_and_no_javascript_is_executed(): + item = host() + payload = {"status": "success", "text": '\");window.bad=true;//\n\u2028', "warnings": ["合成提示"]} + item._im_ai.take_result.return_value = payload + window._EmbeddedVideoWindow._flush_im_ai(item) + script = item._page.runJavaScript.call_args.args[0] + prefix, suffix = "window.doctorConsultation?.imAiResult?.(", ");" + assert script.startswith(prefix) and script.endswith(suffix) + assert json.loads(script[len(prefix):-len(suffix)]) == payload + assert "\\u2028" in script + + +def test_host_acknowledges_initial_summary_only_after_request_gate_opens(): + item = host(_injected=False) + item._im_ai.session_id = 'synthetic-session-\\"\u2028' + + def verify_gate(script): + assert item._im_ai_context_is_trusted() is True + prefix, suffix = "window.doctorConsultation?.imAiReady?.(", ");" + assert script.startswith(prefix) and script.endswith(suffix) + assert json.loads(script[len(prefix):-len(suffix)]) == item._im_ai.session_id + + item._page.runJavaScript.side_effect = verify_gate + window._EmbeddedVideoWindow._after_injection(item, True) + item._page.runJavaScript.assert_called_once() + + +@pytest.mark.parametrize("changes", [ + {"_closing": True}, {"_released": True}, {"_shutdown_requested": True}, +]) +def test_late_injection_cannot_acknowledge_a_closed_ai_context(changes): + item = host(_injected=False, **changes) + window._EmbeddedVideoWindow._after_injection(item, True) + item._page.runJavaScript.assert_not_called() + + +def test_navigation_cannot_receive_ai_readiness_acknowledgement(): + item = host(_injected=False) + item._page.url.return_value.toString.return_value = "https://evil.example.test/im/index.html" + window._EmbeddedVideoWindow._after_injection(item, True) + item._page.runJavaScript.assert_not_called() + + +def test_failed_injection_closes_without_ai_readiness_acknowledgement(): + item = host(_injected=False, _request_companion_shutdown=Mock()) + window._EmbeddedVideoWindow._after_injection(item, False) + item._request_companion_shutdown.assert_called_once_with("bridge-api-missing") + item._page.runJavaScript.assert_not_called() + + +def test_shutdown_cancels_ai_before_waiting_for_media_or_destroying_page(): + item = host( + _start_requested=True, _call_cycle_closed=False, _companion_ended=False, + _shutdown_timer=Mock(), close=Mock(), + ) + window._EmbeddedVideoWindow._request_companion_shutdown(item, "window-closed") + item._im_ai.close.assert_called_once() + item._im_ai_timer.stop.assert_called_once() + assert item._shutdown_requested is True + item.close.assert_not_called() # Recording shutdown still gets its existing grace period. + item._shutdown_timer.start.assert_called_once_with(190_000) + + +def test_qt_notify_rejects_oversized_or_wrong_source_payloads(): + callback = Mock() + bridge = window._QtVideoBridge(callback, Mock()) + bridge.notify("x" * 16_385) + bridge.notify(json.dumps({"source": "evil", "event": "im-ai-request"})) + bridge.notify("[]") + callback.assert_not_called() + message = {"source": "doctor-call", "event": "im-ai-cancel"} + bridge.notify(json.dumps(message)) + callback.assert_called_once_with(message) + + +def test_video_module_remains_importable_without_optional_qt(): + source = Path(__file__).resolve().parents[1] / "src" + script = """ +import builtins +original_import = builtins.__import__ +def without_qt(name, *args, **kwargs): + if name == 'PySide6' or name.startswith('PySide6.'): + raise ImportError('synthetic core-only installation') + return original_import(name, *args, **kwargs) +builtins.__import__ = without_qt +from doctor_workstation.video.window import WEBENGINE_AVAILABLE, VideoCallWindow +from doctor_workstation.video.im_ai import ImAiController +assert WEBENGINE_AVAILABLE is False +""" + result = subprocess.run( + [sys.executable, "-c", script], env={**os.environ, "PYTHONPATH": str(source)}, + capture_output=True, text=True, timeout=10, check=False, + ) + assert result.returncode == 0, result.stderr diff --git a/app/tests/test_motion.py b/app/tests/test_motion.py index aba2864ec..94f994f39 100644 --- a/app/tests/test_motion.py +++ b/app/tests/test_motion.py @@ -12,17 +12,16 @@ from __future__ import annotations import os os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") -# The module disables itself under the offscreen platform so widget grabs in the -# other suites capture settled frames; these tests are about the animation, so -# they opt back in. -os.environ["DOCTOR_MOTION"] = "on" - import pytest -from PySide6.QtCore import QEvent, QPoint, QPointF, Qt -from PySide6.QtGui import QWheelEvent +from PySide6.QtCore import QAbstractAnimation, QEvent, QPoint, QPointF, QPropertyAnimation, Qt +from PySide6.QtGui import QKeyEvent, QWheelEvent from PySide6.QtWidgets import ( + QAbstractItemView, QApplication, + QGraphicsDropShadowEffect, QLabel, + QListWidget, + QPlainTextEdit, QScrollArea, QStackedWidget, QVBoxLayout, @@ -32,6 +31,13 @@ from PySide6.QtWidgets import ( from doctor_workstation.ui import motion +@pytest.fixture(autouse=True) +def enable_motion(monkeypatch: pytest.MonkeyPatch) -> None: + # Opt in per test so collecting this module does not animate other suites' + # screenshots or leak motion settings across the shared QApplication. + monkeypatch.setenv("DOCTOR_MOTION", "on") + + @pytest.fixture(scope="module") def application() -> QApplication: return QApplication.instance() or QApplication([]) @@ -122,15 +128,22 @@ def _scroll_area(application: QApplication) -> QScrollArea: return area -def _wheel(delta: int) -> QWheelEvent: +def _wheel( + delta: int, + *, + horizontal: int = 0, + pixels: int = 0, + modifiers: Qt.KeyboardModifier = Qt.KeyboardModifier.NoModifier, + phase: Qt.ScrollPhase = Qt.ScrollPhase.NoScrollPhase, +) -> QWheelEvent: return QWheelEvent( QPointF(50, 50), QPointF(50, 50), - QPoint(0, 0), - QPoint(0, delta), + QPoint(0, pixels), + QPoint(horizontal, delta), Qt.MouseButton.NoButton, - Qt.KeyboardModifier.NoModifier, - Qt.ScrollPhase.NoScrollPhase, + modifiers, + phase, False, ) @@ -226,3 +239,273 @@ def test_reading_surfaces_get_smooth_scrolling_from_the_theme( assert getattr(area, "_doctor_smooth_scroll", None) is not None area.close() + + +def test_repeated_fade_continues_from_current_opacity(application: QApplication) -> None: + widget = QWidget() + motion.fade_in(widget) + first = widget._doctor_motion["fade"] + first.setCurrentTime(motion.BASE // 2) + opacity = widget.graphicsEffect().opacity() + + motion.fade_in(widget) + + assert widget.graphicsEffect().opacity() == pytest.approx(opacity) + assert widget._doctor_motion["fade"].startValue() == pytest.approx(opacity) + assert first.state() == QAbstractAnimation.State.Stopped + widget.close() + + +def test_fade_out_starts_at_full_opacity(application: QApplication) -> None: + widget = QWidget() + widget.show() + + motion.fade_out(widget) + + assert widget.graphicsEffect().opacity() == pytest.approx(1.0) + widget.close() + + +def test_reversing_fade_does_not_run_cancelled_hide_callback(application: QApplication) -> None: + widget = QWidget() + widget.show() + completed = [] + motion.fade_out(widget, on_finished=lambda: completed.append(True)) + outgoing = widget._doctor_motion["fade"] + outgoing.setCurrentTime(motion.FAST // 2) + opacity = widget.graphicsEffect().opacity() + + motion.fade_in(widget) + incoming = widget._doctor_motion["fade"] + + assert incoming.startValue() == pytest.approx(opacity) + incoming.setCurrentTime(incoming.duration()) + application.processEvents() + assert widget.isVisible() + assert not completed + assert widget.graphicsEffect() is None + widget.close() + + +def test_previous_fade_cleanup_does_not_delete_reentrant_fade(application: QApplication) -> None: + widget = QWidget() + widget.show() + motion.fade_out(widget, on_finished=lambda: motion.fade_in(widget)) + outgoing = widget._doctor_motion["fade"] + + outgoing.setCurrentTime(outgoing.duration()) + incoming = widget._doctor_motion["fade"] + effect = widget.graphicsEffect() + application.processEvents() + + assert widget.graphicsEffect() is effect + assert incoming.state() == QAbstractAnimation.State.Running + incoming.setCurrentTime(incoming.duration()) + application.processEvents() + assert widget.graphicsEffect() is None + assert widget.isVisible() + widget.close() + + +def test_replaced_and_completed_animations_are_released(application: QApplication) -> None: + widget = QWidget() + destroyed = [] + for _ in range(10): + motion.fade_in(widget) + widget._doctor_motion["fade"].destroyed.connect(lambda: destroyed.append(True)) + fade = widget._doctor_motion["fade"] + fade.setCurrentTime(fade.duration()) + application.processEvents() + application.sendPostedEvents(None, QEvent.Type.DeferredDelete) + + assert not widget._doctor_motion + assert not widget.findChildren(QPropertyAnimation) + assert len(destroyed) == 10 + widget.close() + + +def test_fades_preserve_existing_graphics_effects(application: QApplication) -> None: + widget = QWidget() + shadow = QGraphicsDropShadowEffect(widget) + widget.setGraphicsEffect(shadow) + + motion.fade_in(widget) + assert widget.graphicsEffect() is shadow + motion.fade_out(widget) + application.processEvents() + + assert widget.graphicsEffect() is shadow + assert widget.isHidden() + widget.close() + + +def test_repeated_enter_does_not_accumulate_position_offset(application: QApplication) -> None: + host = QWidget() + widget = QWidget(host) + origin = QPoint(10, 20) + widget.move(origin) + motion.enter(widget) + widget._doctor_motion["enter"].setCurrentTime(motion.BASE // 3) + position = widget.pos() + + motion.enter(widget) + + assert widget.pos() == position + arrival = widget._doctor_motion["enter"] + assert arrival.endValue() == origin + arrival.setCurrentTime(arrival.duration()) + assert widget.pos() == origin + host.close() + + +def test_disabling_motion_settles_an_active_entry( + application: QApplication, monkeypatch: pytest.MonkeyPatch +) -> None: + host = QWidget() + widget = QWidget(host) + origin = QPoint(10, 20) + widget.move(origin) + motion.enter(widget) + monkeypatch.setenv("DOCTOR_MOTION", "off") + + motion.enter(widget) + application.processEvents() + + assert widget.pos() == origin + assert widget.graphicsEffect() is None + assert not widget._doctor_motion + host.close() + + +def test_wheel_reversal_discards_pending_travel(application: QApplication) -> None: + area = _scroll_area(application) + motion.install_smooth_scroll(area) + scroller = area._doctor_smooth_scroll + bar = area.verticalScrollBar() + bar.setValue(500) + for _ in range(4): + scroller.eventFilter(area.viewport(), _wheel(-120)) + scroller._animation.setCurrentTime(30) + position = bar.value() + + scroller.eventFilter(area.viewport(), _wheel(120)) + + assert scroller._animation.startValue() == position + assert scroller._animation.endValue() == position - motion.SCROLL_STEP + scroller._animation.setCurrentTime(60) + assert bar.value() < position + area.close() + + +@pytest.mark.parametrize("interaction", ["set_value", "keyboard", "slider_press", "range_change"]) +def test_direct_scroll_interaction_cancels_pending_wheel( + application: QApplication, interaction: str +) -> None: + area = _scroll_area(application) + motion.install_smooth_scroll(area) + scroller = area._doctor_smooth_scroll + bar = area.verticalScrollBar() + scroller.eventFilter(area.viewport(), _wheel(-120)) + scroller._animation.setCurrentTime(30) + + if interaction == "set_value": + bar.setValue(500) + elif interaction == "keyboard": + application.sendEvent( + area, + QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_Down, Qt.KeyboardModifier.NoModifier), + ) + elif interaction == "slider_press": + bar.setSliderDown(True) + else: + bar.setRange(0, 50) + + assert scroller._animation.state() == QAbstractAnimation.State.Stopped + assert scroller._target == bar.value() + if interaction == "set_value": + scroller.eventFilter(area.viewport(), _wheel(-120)) + assert scroller._animation.endValue() == 500 + motion.SCROLL_STEP + area.close() + + +@pytest.mark.parametrize( + "wheel_options", + [ + {"pixels": -8}, + {"phase": Qt.ScrollPhase.ScrollUpdate}, + {"phase": Qt.ScrollPhase.ScrollMomentum}, + {"modifiers": Qt.KeyboardModifier.ControlModifier}, + {"modifiers": Qt.KeyboardModifier.ShiftModifier}, + {"horizontal": -120}, + ], +) +def test_native_gestures_cancel_pending_wheel( + application: QApplication, wheel_options: dict +) -> None: + area = _scroll_area(application) + motion.install_smooth_scroll(area) + scroller = area._doctor_smooth_scroll + scroller.eventFilter(area.viewport(), _wheel(-120)) + scroller._animation.setCurrentTime(30) + delta = 0 if "horizontal" in wheel_options else -120 + + assert not scroller.eventFilter(area.viewport(), _wheel(delta, **wheel_options)) + assert scroller._animation.state() == QAbstractAnimation.State.Stopped + assert scroller._target == area.verticalScrollBar().value() + area.close() + + +@pytest.mark.parametrize("kind", ["items", "text_blocks"]) +def test_non_pixel_scrollbars_keep_native_wheel_steps(application: QApplication, kind: str) -> None: + if kind == "items": + area = QListWidget() + area.addItems([f"row {index}" for index in range(300)]) + area.setVerticalScrollMode(QAbstractItemView.ScrollMode.ScrollPerItem) + else: + area = QPlainTextEdit("\n".join(f"line {index}" for index in range(300))) + area.resize(300, 200) + area.show() + application.processEvents() + motion.install_smooth_scroll(area) + + assert not area._doctor_smooth_scroll.eventFilter(area.viewport(), _wheel(-120)) + application.sendEvent(area.viewport(), _wheel(-120)) + assert 0 < area.verticalScrollBar().value() < motion.SCROLL_STEP + area.close() + + +def test_pending_scroll_reaches_edge_before_handing_wheel_back(application: QApplication) -> None: + area = _scroll_area(application) + motion.install_smooth_scroll(area) + scroller = area._doctor_smooth_scroll + bar = area.verticalScrollBar() + bar.setValue(bar.maximum() - 20) + + assert scroller.eventFilter(area.viewport(), _wheel(-120)) + assert scroller.eventFilter(area.viewport(), _wheel(-120)) + scroller._animation.setCurrentTime(scroller._animation.duration()) + assert not scroller.eventFilter(area.viewport(), _wheel(-120)) + area.close() + + +def test_horizontal_scroller_honors_horizontal_and_shift_wheel(application: QApplication) -> None: + area = QScrollArea() + content = QWidget() + content.resize(2000, 1000) + area.setWidget(content) + area.resize(300, 200) + motion.install_smooth_scroll(area, orientation=Qt.Orientation.Horizontal) + area.show() + application.processEvents() + scroller = area._doctor_smooth_scroll + + assert not scroller.eventFilter(area.viewport(), _wheel(-120)) + assert scroller.eventFilter(area.viewport(), _wheel(0, horizontal=-120)) + scroller._animation.setCurrentTime(scroller._animation.duration()) + assert area.horizontalScrollBar().value() == motion.SCROLL_STEP + assert area.verticalScrollBar().value() == 0 + assert scroller.eventFilter( + area.viewport(), _wheel(-120, modifiers=Qt.KeyboardModifier.ShiftModifier) + ) + assert scroller._animation.endValue() == motion.SCROLL_STEP * 2 + area.close() diff --git a/app/tests/test_prescriptions_tech_blue.py b/app/tests/test_prescriptions_tech_blue.py index 8a4613f86..3c529ec04 100644 --- a/app/tests/test_prescriptions_tech_blue.py +++ b/app/tests/test_prescriptions_tech_blue.py @@ -16,6 +16,7 @@ from PySide6.QtWidgets import QAbstractItemView, QApplication, QPushButton from doctor_workstation.core import PermissionSet from doctor_workstation.services import DemoDoctorRepository from doctor_workstation.ui import icons +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.pages import prescriptions as prescriptions_module from doctor_workstation.ui.shell import ShellWindow from doctor_workstation.ui.theme import apply_theme @@ -222,7 +223,7 @@ def test_sorted_native_row_view_button_targets_visible_record( def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(application) -> None: - kind, color, size = "pencil", "#1769E8", 19 + kind, color, size = "pencil", PALETTE["accent"], 19 shared = icons.icon(kind, color, size) original_key = shared.cacheKey() original_normal = shared.pixmap(size, size, QIcon.Mode.Normal).toImage() @@ -230,13 +231,19 @@ def test_blue_icon_disabled_variant_does_not_modify_shared_icon_cache(applicatio blue = prescriptions_module._blue_prescription_icon(kind, color, size) + assert blue is not shared assert icons.icon(kind, color, size) is shared assert shared.cacheKey() == original_key assert shared.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled assert blue.pixmap(size, size, QIcon.Mode.Normal).toImage() == original_normal - assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, "#A4ADBA", size).toImage() - assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() != original_disabled + assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == icons.pixmap(kind, PALETTE["disabled"], size).toImage() + assert blue.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled + # Both surfaces share the disabled colour; changing the returned icon still + # must not mutate the cached icon used by another page. + blue.addPixmap(icons.pixmap(kind, PALETTE["danger"], size), QIcon.Mode.Disabled) + assert shared.cacheKey() == original_key + assert shared.pixmap(size, size, QIcon.Mode.Disabled).toImage() == original_disabled def test_long_doctor_button_paints_compactly_without_truncating_real_value(shell_factory, application) -> None: diff --git a/app/tests/test_reception_blue_design.py b/app/tests/test_reception_blue_design.py index fdc7c696e..801f669be 100644 --- a/app/tests/test_reception_blue_design.py +++ b/app/tests/test_reception_blue_design.py @@ -6,6 +6,7 @@ from PySide6.QtGui import QPalette from PySide6.QtWidgets import QApplication, QFrame, QLabel, QPushButton from doctor_workstation.core import PermissionSet +from doctor_workstation.ui.design_system import PALETTE from doctor_workstation.ui.pages import reception as reception_module from doctor_workstation.ui.pages.reception import ReceptionPage from doctor_workstation.ui.theme import apply_theme @@ -43,12 +44,12 @@ def page(application, monkeypatch): def test_primary_action_and_reading_ink_use_separate_colors(page, application): page.video_button.setEnabled(True) settle(application) - assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == "#1769e8" - assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#ffffff" - assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == "#273244" + assert page.video_button.palette().color(QPalette.ColorRole.Button).name() == PALETTE["accent"].lower() + assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["surface"].lower() + assert page.case_labels["present"].palette().color(QPalette.ColorRole.WindowText).name() == PALETTE["text"].lower() page.video_button.setEnabled(False) settle(application) - assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == "#8e8f90" + assert page.video_button.palette().color(QPalette.ColorRole.ButtonText).name() == PALETTE["disabled"].lower() def test_typography_preserves_regular_body_and_distinct_values(page): diff --git a/app/tests/test_text_call_policy.py b/app/tests/test_text_call_policy.py index 88ccb9671..5bfa572d8 100644 --- a/app/tests/test_text_call_policy.py +++ b/app/tests/test_text_call_policy.py @@ -164,6 +164,59 @@ def test_diagnosis_callback_previews_exact_appointment_session(chat_controller): assert len(case.previews) == 1 # A closed session cannot borrow another appointment's video. +@pytest.mark.parametrize("permissions, expected", [ + (None, False), + ([], False), + (["tcm.diagnosis/read"], False), + (["tcm.diagnosis.aiAssistant"], False), + (["tcm.diagnosis/aiAssistant"], True), + (["tcm.diagnosis/*"], True), + (["*"], True), +]) +def test_im_ai_capability_comes_from_current_shell_permissions(chat_controller, permissions, expected): + case = chat_controller + case.controller.shell_window.permissions = permissions + case.controller._request_video({ + "patient_id": 8, "diagnosis_id": 123, "appointment_id": 456, + "mode": "im", "can_ai_assistant": True, + }) + case.complete(0) + assert case.launched[0][1]["can_ai_assistant"] is expected + + +def test_im_ai_permission_is_evaluated_after_ticket_load(chat_controller): + case = chat_controller + case.controller.shell_window.permissions = ["tcm.diagnosis/aiAssistant"] + case.request(456) + case.controller.shell_window.permissions = [] + case.complete(0) + assert case.launched[0][1]["can_ai_assistant"] is False + + +@pytest.mark.parametrize("capability, expected", [(True, True), (False, False), (None, False), (1, False), ("true", False)]) +def test_video_launcher_forwards_only_explicit_ai_capability(monkeypatch, capability, expected): + from doctor_workstation.video import window as window_module + from doctor_workstation.video.launcher import launch_video_call + + launches = [] + sentinel = object() + + def capture(request, **kwargs): + launches.append((request, kwargs)) + return sentinel + + monkeypatch.setattr(window_module, "open_video_call", capture) + result = launch_video_call( + ticket(), repository=object(), open_im=True, can_ai_assistant=capability, + ) + assert result is sentinel + request, options = launches[0] + assert request.diagnosis_id == 123 + assert request.patient_id == 8 + assert request.appointment_id == 456 + assert options["can_ai_assistant"] is expected + + @pytest.mark.parametrize("second_diagnosis", [123, 124]) @pytest.mark.parametrize("completion_order", [(0, 1), (1, 0)]) def test_latest_im_selection_retires_pending_callbacks(chat_controller, second_diagnosis, completion_order): diff --git a/app/tests/test_ui_contract.py b/app/tests/test_ui_contract.py index 7bc78229b..648072cb1 100644 --- a/app/tests/test_ui_contract.py +++ b/app/tests/test_ui_contract.py @@ -295,6 +295,48 @@ def test_real_demo_login_reaches_success_without_widget_adapter( application.processEvents() +def test_login_password_group_keeps_focus_when_reveal_is_keyboard_focused(tmp_path: Any) -> None: + application = QApplication.instance() or QApplication([]) + apply_theme(application) + window = LoginWindow( + object(), settings=QSettings(str(tmp_path / "focus.ini"), QSettings.Format.IniFormat), + ) + window.show() + application.processEvents() + group = window.password_edit.parentWidget() + geometry = group.geometry() + try: + for control in (window.password_edit, window.reveal_button): + control.setFocus() + application.processEvents() + assert group.property("focused") is True + assert group.geometry() == geometry + window.login_button.setFocus() + application.processEvents() + assert group.property("focused") is False + assert group.geometry() == geometry + finally: + window.close() + + +def test_compact_login_keeps_the_whole_form_visible(tmp_path: Any) -> None: + application = QApplication.instance() or QApplication([]) + apply_theme(application) + window = LoginWindow( + object(), settings=QSettings(str(tmp_path / "compact.ini"), QSettings.Format.IniFormat), + ) + window.resize(860, 640) + window.show() + application.processEvents() + try: + assert not window.brand_panel.isVisible() + assert window.login_scroll.verticalScrollBar().maximum() == 0 + assert window.card.height() >= window.card.minimumSizeHint().height() + assert window.login_button.isVisibleTo(window) + finally: + window.close() + + def test_remembered_password_survives_a_new_login_window(tmp_path: Any) -> None: application = QApplication.instance() or QApplication([]) settings_path = tmp_path / "remember-password.ini" diff --git a/app/tests/test_ui_detail_refinements.py b/app/tests/test_ui_detail_refinements.py index acac857b1..c19fb5681 100644 --- a/app/tests/test_ui_detail_refinements.py +++ b/app/tests/test_ui_detail_refinements.py @@ -38,6 +38,8 @@ def page(application, monkeypatch): def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, application): + # The responsive workspace exposes insights in its second tab. + page.workbench.mode_tabs.setCurrentIndex(1) settle(application) for button in page.ai_prompt_buttons: assert button.width() >= button.minimumSizeHint().width() @@ -48,6 +50,8 @@ def test_reception_prompts_remain_readable_in_a_narrow_workspace(page, applicati def test_hidden_tall_consultation_does_not_expand_daily_records(page, application): + # Force real overflow: a short case is allowed to fill the viewport. + page.case_labels["present"].setText("Long clinical history\n" * 80) page.detail_tabs.setCurrentIndex(0) settle(application) consultation_height = page.clinical_pages.height() diff --git a/app/video_companion/dist/assets/index-CMN1CXTr.css b/app/video_companion/dist/assets/index-CMN1CXTr.css new file mode 100644 index 000000000..38989167b --- /dev/null +++ b/app/video_companion/dist/assets/index-CMN1CXTr.css @@ -0,0 +1 @@ +:root{--accent: #4267b2;--accent-hover: #355995;--accent-soft: #eaf0fb;--surface: #fff;--surface-soft: #f5f7fa;--border: #e6eaf0;--text: #344258;--muted: #647287;--heading: #223047;--surface-alt: #f7f9fc;--border-strong: #d4dce8;--success: #287b65;--success-soft: #edf7f2;--danger: #b54a59;--danger-soft: #fcf0f2;--radius-small: 6px;--radius-panel: 16px;--radius-control: 10px;--motion-ease: cubic-bezier(.2, .7, .2, 1);font-family:Microsoft YaHei UI,PingFang SC,Noto Sans CJK SC,system-ui,sans-serif;color:var(--text);background:var(--surface-soft);font-synthesis:none;text-rendering:optimizeLegibility}*{box-sizing:border-box}html,body,#app{width:100%;height:100%;margin:0;overflow:hidden}button,textarea,input{font:inherit}button{cursor:pointer;transition:background-color .14s var(--motion-ease),border-color .14s var(--motion-ease),color .14s var(--motion-ease),transform .12s var(--motion-ease)}button:enabled:active{transform:translateY(1px)}button:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button:disabled{cursor:not-allowed;opacity:.55}.consultation-shell{width:100%;height:100%;min-width:0;min-height:0;background:var(--surface-soft)}.consultation-shell--video-only{min-height:0}.consultation-shell--with-ai{display:grid;grid-template-columns:minmax(0,1fr) var(--im-ai-panel-width, 330px);column-gap:8px}.im-ai-resizer{position:absolute;z-index:1;top:0;bottom:0;left:-8px;width:8px;min-height:0;cursor:col-resize;touch-action:none;background:var(--surface-soft);outline:none}.im-ai-resizer:before{position:absolute;inset:0 3px;border-radius:2px;background:var(--border);content:""}.im-ai-resizer>span{position:absolute;top:calc(50% - 20px);left:2px;width:4px;height:40px;border-radius:3px;background:var(--border-strong)}.im-ai-resizer:hover:before,.im-ai-resizer:focus-visible:before,.consultation-shell--resizing .im-ai-resizer:before{background:var(--accent)}.im-ai-resizer:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}.consultation-shell--resizing,.consultation-shell--resizing *{cursor:col-resize!important;user-select:none!important}.chat-panel{display:grid;grid-template-rows:minmax(74px,auto) minmax(0,1fr) auto;width:100%;height:100%;min-width:0;min-height:0;background:var(--surface-soft)}.chat-header{display:flex;align-items:center;gap:14px;padding:12px 20px;border-bottom:1px solid var(--border);background:var(--surface)}.patient-avatar{display:grid;place-items:center;width:44px;height:44px;border-radius:var(--radius-control);color:#fff;background:var(--accent);font-size:18px;font-weight:700}.chat-heading{min-width:0;flex:1}.chat-heading h1{margin:0;color:var(--heading);font-size:18px;line-height:1.4}.chat-heading p{display:flex;align-items:center;gap:7px;margin:3px 0 0;color:var(--muted);font-size:12px}.connection-dot{width:7px;height:7px;border-radius:50%;background:#a3adbd}.connection-dot--online{background:var(--success)}.primary-action,.send-button,.capture-button{border:1px solid var(--accent);border-radius:var(--radius-control);color:#fff;background:var(--accent);font-weight:600}.secondary-action{padding:9px 13px;border:1px solid var(--border-strong);border-radius:var(--radius-control);color:var(--text);background:#fff;font-weight:600}.secondary-action:enabled:hover{border-color:var(--accent);color:var(--accent-hover);background:var(--accent-soft)}.primary-action{display:flex;gap:8px;align-items:center;padding:10px 16px}.primary-action:enabled:hover,.send-button:enabled:hover,.capture-button:enabled:hover{background:var(--accent-hover)}.message-list{overflow-y:auto;padding:18px max(24px,calc((100% - 920px)/2));background:var(--surface-soft)}.load-more{display:block;margin:0 auto 18px;padding:6px 12px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:#fff;font-size:12px}.empty-chat{display:grid;justify-items:center;margin-top:min(16vh,110px);color:var(--muted);text-align:center}.empty-chat__icon{display:grid;place-items:center;width:62px;height:62px;margin-bottom:12px;border:1px solid var(--border);border-radius:var(--radius-panel);color:var(--accent);background:#fff;font-weight:800}.empty-chat h2{margin:0;color:var(--heading);font-size:17px}.empty-chat p{margin:7px 0;font-size:13px}.message-row{display:flex;flex-direction:column;align-items:flex-start;margin:12px 0}.message-row--mine{align-items:flex-end}.message-row--call-status{align-items:center;margin:16px 0}.call-status-event{display:inline-flex;align-items:center;gap:8px;min-height:32px;padding:0 12px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:var(--surface);font-size:12px}.call-status-event__icon{display:grid;place-items:center;width:20px;height:20px;border-radius:10px;color:var(--accent);background:var(--accent-soft);font-size:11px}.call-status-event strong{color:var(--heading);font-weight:700}.call-status-event time{color:var(--muted);font-variant-numeric:tabular-nums}.call-status-event--connected{border-color:#bdebdc;background:var(--success-soft)}.call-status-event--connected .call-status-event__icon{color:var(--success);background:#dff7ee}.call-status-event--failed{border-color:#f3c8cf;background:var(--danger-soft)}.call-status-event--failed .call-status-event__icon{color:var(--danger);background:#ffe6e9}.message-meta{margin:0 8px 5px;color:var(--muted);font-size:11px}.message-bubble{max-width:min(72%,620px);padding:10px 13px;border:1px solid var(--border);border-radius:10px var(--radius-panel) var(--radius-panel) var(--radius-panel);background:#fff;line-height:1.6;word-break:break-word}.message-row--mine .message-bubble{border-color:var(--accent);border-radius:var(--radius-panel) 10px var(--radius-panel) var(--radius-panel);color:#fff;background:var(--accent)}.message-bubble p{margin:0;white-space:pre-wrap}.message-image,.message-video{display:block;max-width:min(360px,100%);max-height:280px;border-radius:var(--radius-control)}.message-file{display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none}.message-bubble audio{max-width:min(320px,100%)}.composer{padding:10px 18px 14px;border-top:1px solid var(--border);background:#fff}.composer-toolbar{display:flex;align-items:center;justify-content:space-between;min-height:30px;color:var(--muted);font-size:11px}.composer-toolbar button{padding:5px 9px;border:0;border-radius:10px;color:var(--accent);background:var(--accent-soft);font-size:12px}.composer-tools{display:flex;align-items:center;gap:8px;min-width:0}.composer-toolbar .im-ai-toggle{display:none}.composer-row{display:grid;grid-template-columns:minmax(0,1fr) 86px;gap:12px}.composer textarea{width:100%;min-height:68px;max-height:150px;padding:10px 12px;resize:vertical;border:1px solid var(--border-strong);border-radius:var(--radius-control);outline:none;transition:border-color .14s var(--motion-ease),background-color .14s var(--motion-ease);color:var(--text);background:var(--surface-alt);line-height:1.5}.composer textarea:focus{border-color:var(--accent);outline:2px solid var(--accent-soft);outline-offset:1px;background:var(--surface)}.send-button{align-self:end;height:40px}.inline-notice{margin-bottom:7px;color:var(--success);font-size:12px}.inline-notice--error{color:var(--danger)}.im-ai-panel{position:relative;display:grid;grid-template-rows:auto auto minmax(0,1fr) auto;min-width:0;min-height:0;height:100%;overflow:visible;border-left:1px solid var(--border);background:var(--surface);color:var(--text)}.im-ai-header{display:flex;align-items:center;gap:10px;min-height:74px;padding:14px 18px}.im-ai-mark{display:grid;place-items:center;flex-shrink:0;width:32px;height:32px;border:1px solid var(--border-strong);border-radius:var(--radius-control);color:var(--accent);background:var(--surface-alt);font-size:12px;font-weight:700;letter-spacing:.02em}.im-ai-header>div{flex:1;min-width:0}.im-ai-header h2{margin:0;color:var(--heading);font-size:15px;line-height:1.5;font-weight:600}.im-ai-header p{margin:2px 0 0;color:var(--muted);font-size:11px}.im-ai-close{display:none;width:32px;height:32px;flex-shrink:0;border:0;border-radius:var(--radius-small);background:var(--surface-soft);color:var(--muted);font-size:23px;line-height:1}.im-ai-close:hover{background:var(--accent-soft);color:var(--accent)}.im-ai-tools{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:5px;padding:0 14px 14px;border-bottom:1px solid var(--border)}.im-ai-tools button{min-height:36px;padding:7px 4px;border:1px solid var(--border);border-radius:var(--radius-small);background:var(--surface);color:var(--muted);font-size:12px;white-space:nowrap}.im-ai-tools button:enabled:hover,.im-ai-tools .im-ai-tool--selected{border-color:var(--border-strong);background:var(--accent-soft);color:var(--accent-hover)}.im-ai-tools .im-ai-tool--selected{font-weight:600}.im-ai-tool__saved{margin-left:3px;color:var(--success);font-weight:700}.im-ai-body{min-height:0;overflow-y:auto;padding:18px;overscroll-behavior:contain}.im-ai-body:focus-visible{outline:2px solid var(--accent-soft);outline-offset:-2px}.im-ai-empty{padding:16px 0}.im-ai-empty__line{display:block;width:28px;height:3px;margin-bottom:18px;border-radius:2px;background:var(--border-strong)}.im-ai-empty strong{color:var(--heading);font-size:14px;font-weight:600;line-height:1.6}.im-ai-empty p{margin:10px 0;color:var(--muted);font-size:13px;line-height:1.85}.im-ai-empty .im-ai-source{margin-top:26px;padding-top:14px;border-top:1px solid var(--border);font-size:11px}.im-ai-result-heading{display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:6px;margin-bottom:10px}.im-ai-result-heading h3{margin:0;color:var(--heading);font-size:14px;font-weight:600}.im-ai-result-heading span{max-width:100%;color:var(--muted);font-size:10px;overflow-wrap:anywhere}.im-ai-status{margin:0 0 14px;color:var(--muted);font-size:12px;line-height:1.7;overflow-wrap:anywhere}.im-ai-status--error{padding:10px 12px;border-radius:var(--radius-small);color:var(--danger);background:var(--danger-soft)}.im-ai-text{margin:0;overflow-wrap:anywhere;font-size:14px;line-height:1.85}.im-ai-text :is(h1,h2,h3,h4,h5,h6){margin:20px 0 10px;padding-left:9px;border-left:3px solid var(--accent);color:var(--heading);font-size:14px;font-weight:700;line-height:1.65}.im-ai-text>:first-child{margin-top:0}.im-ai-text>:last-child{margin-bottom:0}.im-ai-text p{margin:0 0 12px}.im-ai-text strong{padding:1px 2px;border-radius:3px;background:var(--accent-soft);color:var(--heading);font-weight:700;-webkit-box-decoration-break:clone;box-decoration-break:clone}.im-ai-text .im-ai-metric-label{color:var(--accent-hover);font-weight:600}.im-ai-text .im-ai-metric-value{padding:1px 4px;border-radius:4px;background:#e8effb;color:#234c93;font-weight:700;font-variant-numeric:tabular-nums;-webkit-box-decoration-break:clone;box-decoration-break:clone}.im-ai-text :is(ul,ol){margin:10px 0 16px;padding-left:22px}.im-ai-text li{padding-left:2px;margin:7px 0}.im-ai-text li::marker{color:var(--accent);font-weight:600}.im-ai-text li>p{margin-bottom:6px}.im-ai-text li :is(ul,ol){margin-block:5px}.im-ai-text blockquote{margin:14px 0;padding:9px 12px;border-left:3px solid var(--border-strong);background:var(--surface-soft);color:var(--muted)}.im-ai-text blockquote>:last-child{margin-bottom:0}.im-ai-text code{padding:2px 4px;border-radius:4px;background:var(--surface-soft);color:var(--text);font-size:12px}.im-ai-text pre{margin:14px 0;padding:10px;border-radius:var(--radius-small);background:var(--surface-soft);white-space:pre-wrap;overflow-wrap:anywhere}.im-ai-text pre code{padding:0;background:none}.im-ai-text hr{margin:18px 0;border:0;border-top:1px solid var(--border)}.im-ai-text table{width:100%;margin:14px 0;border-collapse:collapse;table-layout:fixed;font-size:12px}.im-ai-text :is(th,td){padding:7px;border:1px solid var(--border);vertical-align:top;text-align:left}.im-ai-text th{background:var(--surface-soft);color:var(--heading);font-weight:600}.im-ai-loading{display:grid;gap:12px;margin:24px 0}.im-ai-loading span{height:8px;border-radius:4px;background:var(--surface-soft)}.im-ai-loading span:nth-child(2){width:86%}.im-ai-loading span:nth-child(3){width:62%}.im-ai-warnings{margin:18px 0 0;padding:12px 12px 12px 26px;border-radius:var(--radius-small);background:var(--surface-soft);color:var(--muted);font-size:11px;line-height:1.8;overflow-wrap:anywhere}.im-ai-warnings li+li{margin-top:6px}.im-ai-footer{border-top:1px solid var(--border);padding:12px 16px;background:var(--surface-alt)}.im-ai-footer p{margin:8px 0 0;color:var(--muted);font-size:11px;line-height:1.65}.im-ai-result-actions{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.im-ai-result-actions:empty{display:none}.im-ai-result-actions button{min-height:34px;padding:7px 12px;border:1px solid var(--border-strong);border-radius:var(--radius-control);background:var(--surface);color:var(--text);font-size:12px}.im-ai-result-actions button:enabled:hover{border-color:var(--accent);color:var(--accent-hover)}.im-ai-result-actions .im-ai-apply{margin-left:auto;border-color:var(--accent);background:var(--accent);color:#fff;font-weight:600}.im-ai-result-actions .im-ai-apply:enabled:hover{background:var(--accent-hover);color:#fff}.video-layer{position:relative;display:grid;grid-template-columns:minmax(0,1fr);width:100%;height:100%;min-height:420px;overflow:hidden;color:#f7f8fa;background:#101720}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) clamp(330px,31vw,380px)}.video-layer--overlay{position:fixed;z-index:1000;inset:0}.video-stage{position:relative;min-width:0;min-height:0;overflow:hidden;background:#101720}.call-kit,.video-layer :is(.TUICallKit-desktop,.TUICallKit-mobile,#tuicallkit-id){width:100%!important;height:100%!important;max-width:none!important;max-height:none!important}.status-card{position:absolute;inset:50% auto auto 50%;display:grid;grid-template-columns:12px minmax(0,1fr);gap:18px;width:min(520px,calc(100% - 48px));padding:30px 32px;transform:translate(-50%,-50%);border:1px solid var(--border);border-radius:var(--radius-panel);color:var(--text);background:var(--surface)}.eyebrow{margin:0 0 10px;color:var(--muted);font-size:12px;font-weight:600;letter-spacing:.02em}.status-card h2{margin:0;font-size:clamp(22px,2.4vw,28px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:var(--muted);font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c}.status-dot--starting,.status-dot--live{background:var(--success)}.status-dot--error{background:var(--danger)}.live-status{position:absolute;z-index:20;top:18px;left:50%;display:flex;align-items:center;gap:10px;padding:9px 14px;transform:translate(-50%);border:1px solid var(--border);border-radius:var(--radius-control);color:var(--text);background:var(--surface);font-size:13px}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none}.consultation-rail{position:relative;z-index:55;display:grid;grid-template-rows:auto minmax(0,1.08fr) minmax(0,.92fr);min-width:0;min-height:0;overflow:hidden;border-left:1px solid var(--border);color:var(--text);background:var(--surface-soft)}.consultation-rail__header{display:grid;grid-template-columns:42px minmax(0,1fr) auto;gap:11px;align-items:center;min-height:74px;padding:13px 16px;border-bottom:1px solid var(--border);background:#fff}.consultation-rail__avatar{display:grid;place-items:center;width:42px;height:42px;border-radius:var(--radius-control);color:#fff;background:var(--accent);font-size:17px;font-weight:700}.consultation-rail__identity{display:grid;gap:3px;min-width:0}.consultation-rail__identity strong{overflow:hidden;color:var(--text);font-size:16px;line-height:1.3;text-overflow:ellipsis;white-space:nowrap}.consultation-rail__identity span{overflow:hidden;color:var(--muted);font-size:11px;text-overflow:ellipsis;white-space:nowrap}.diagnosis-chip{padding:5px 7px;border-radius:var(--radius-small);color:var(--accent);background:var(--accent-soft);font-size:11px;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.consultation-rail__actions{display:grid;flex:0 0 auto;justify-items:end;gap:5px}.open-diagnosis-button{display:inline-flex;align-items:center;gap:4px;min-height:28px;padding:5px 8px;border:1px solid var(--border-strong);border-radius:10px;color:var(--accent);background:#fff;font-size:11px;font-weight:700;white-space:nowrap}.open-diagnosis-button:enabled:hover{border-color:var(--accent);background:var(--accent-soft)}.case-panel,.transcript-panel{display:grid;grid-template-rows:auto minmax(0,1fr);min-height:0;overflow:hidden}.case-panel{border-bottom:1px solid var(--border)}.rail-section-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:48px;padding:10px 16px;border-bottom:1px solid var(--border);background:var(--surface)}.rail-section-heading>div{display:flex;align-items:center;gap:8px}.rail-section-heading h2{margin:0;color:var(--heading);font-size:14px;font-weight:700;letter-spacing:-.01em}.rail-section-heading>span{overflow:hidden;max-width:154px;color:var(--muted);font-size:10px;text-overflow:ellipsis;white-space:nowrap}.rail-section-heading__index{color:var(--accent);font-family:Cascadia Mono,SFMono-Regular,Consolas,monospace;font-size:10px;font-weight:700}.case-panel__content,.live-captions{min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#b9c3d5 transparent;scrollbar-width:thin}.case-panel__content{padding:5px 16px 14px}.case-field-list{display:grid}.case-field{display:grid;grid-template-columns:72px minmax(0,1fr);gap:10px;padding:10px 0;border-bottom:1px solid var(--border)}.case-field:last-child{border-bottom:0}.case-field>span{padding-top:2px;color:var(--muted);font-size:11px;font-weight:600}.case-field p{margin:0;color:var(--text);font-size:12px;line-height:1.55;overflow-wrap:anywhere;white-space:pre-wrap}.case-field--risk>span{color:var(--danger)}.case-field--risk p{color:var(--danger);font-weight:600}.live-captions{display:grid;align-content:start;gap:9px;padding:12px 14px 18px;background:var(--surface-soft)}.caption-entry{padding:10px 11px;border-left:2px solid var(--accent);border-radius:var(--radius-control);background:#fff}.caption-entry--partial{border-left-color:#9ca6b7;opacity:.78}.caption-entry header{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:5px}.caption-entry strong{color:var(--accent);font-size:11px}.caption-entry time{color:var(--muted);font-size:10px;font-variant-numeric:tabular-nums}.caption-entry p{margin:0;color:var(--text);font-size:13px;line-height:1.58;overflow-wrap:anywhere;white-space:pre-wrap}.transcript-state{position:relative;padding-left:12px}.transcript-state:before{position:absolute;top:50%;left:0;width:6px;height:6px;transform:translateY(-50%);border-radius:50%;background:#a5adbb;content:""}.transcript-state--active{color:var(--success)!important}.transcript-state--active:before{background:var(--success)}.rail-empty{display:grid;gap:5px;align-content:center;min-height:112px;padding:18px;color:var(--muted);text-align:center}.rail-empty strong{color:var(--text);font-size:12px}.rail-empty span{font-size:11px;line-height:1.55}.rail-empty--case{min-height:100%}.video-actions{position:absolute;z-index:40;right:22px;bottom:24px;display:flex;gap:10px}.video-actions button{padding:10px 15px;border-radius:var(--radius-control);font-weight:600}.recording-status{display:inline-flex;align-items:center;gap:8px;padding:10px 15px;border:1px solid var(--border);border-radius:var(--radius-control);color:var(--muted);background:var(--surface);font-size:13px;font-weight:600}.recording-status--active,.recording-status--error{border-color:#edccd3;color:var(--danger);background:var(--danger-soft)}.recording-indicator{width:9px;height:9px;border-radius:50%;background:var(--danger)}.hangup-button{border:1px solid var(--danger);color:#fff;background:var(--danger)}.hangup-button:enabled:hover{border-color:#a64454;background:#a64454}.video-notice{position:absolute;z-index:40;left:22px;bottom:26px;max-width:calc(100% - 420px);padding:9px 12px;border:1px solid #cae5dc;border-radius:var(--radius-control);color:var(--success);background:var(--success-soft);font-size:13px}.video-notice--error{border-color:#edccd3;color:var(--danger);background:var(--danger-soft)}.screenshot-dialog-backdrop{position:absolute;z-index:120;inset:0;display:grid;place-items:center;padding:24px;background:#101720a3}.screenshot-dialog{display:grid;grid-template-rows:auto minmax(0,1fr) auto auto;gap:14px;width:min(920px,100%);height:min(840px,calc(100vh - 48px));max-height:calc(100vh - 48px);padding:20px;overflow:hidden;border:1px solid var(--border);border-radius:var(--radius-panel);color:var(--text);background:#fff;animation:screenshot-enter .16s var(--motion-ease)}.screenshot-dialog>header,.screenshot-dialog>footer{display:flex;align-items:center;justify-content:space-between;gap:16px}.screenshot-dialog h2{margin:2px 0 0;color:var(--heading);font-size:20px;line-height:1.35}.screenshot-dialog .eyebrow{margin:0;color:var(--accent)}.screenshot-dialog>header>button{width:36px;height:36px;border:0;border-radius:var(--radius-control);color:var(--muted);background:var(--surface-alt);font-size:24px}.screenshot-preview-frame{display:grid;place-items:center;min-height:0;overflow:hidden;border-radius:12px;background:#0b0f16}.screenshot-preview-frame img{display:block;width:100%;height:100%;min-height:0;max-width:100%;max-height:100%;object-fit:contain}.screenshot-dialog__hint{margin:0;color:var(--muted);font-size:13px}.screenshot-dialog>footer{justify-content:flex-end}.screenshot-dialog>footer button{min-width:112px;padding:10px 18px;border-radius:var(--radius-control);font-weight:700}.screenshot-cancel{border:1px solid var(--border);color:var(--text);background:#fff}.screenshot-confirm{border:1px solid var(--accent);color:#fff;background:var(--accent)}.screenshot-confirm:enabled:hover{background:var(--accent-hover)}@media (max-width: 980px){.consultation-shell--with-ai{grid-template-columns:minmax(0,1fr)}.composer-toolbar .im-ai-toggle{display:inline-flex;align-items:center;gap:3px}.im-ai-backdrop{position:fixed;z-index:800;inset:0;background:#22304733}.im-ai-panel{display:none;position:fixed;z-index:801;inset:0 0 0 auto;width:var(--im-ai-panel-width, min(360px, 100%))}.im-ai-resizer--drawer{left:-4px;background:transparent}.im-ai-panel--open{display:grid}.im-ai-close{display:block}.video-layer--with-rail{grid-template-columns:minmax(0,1fr) 310px}.video-actions{right:12px;bottom:14px;left:12px;flex-wrap:wrap;justify-content:flex-end}.recording-status{flex-basis:100%;width:fit-content;margin-left:auto;font-size:11px}.consultation-rail__header{padding-inline:12px}.diagnosis-chip{display:none}.case-panel__content,.rail-section-heading{padding-inline:12px}}@media (max-width: 700px){.chat-header{gap:10px;padding:10px 14px}.chat-heading h1{font-size:16px}.chat-heading p{font-size:11px}.primary-action{padding:9px 12px;font-size:12px}.secondary-action{padding:9px 10px;font-size:12px}.message-list{padding:14px}.message-bubble{max-width:88%}.composer{padding:8px 14px 12px}.composer-row{grid-template-columns:minmax(0,1fr) 68px;gap:10px}.video-layer,.video-stage{min-height:280px}.video-layer--with-rail{grid-template-columns:minmax(0,1fr)}.consultation-rail{display:none}.video-actions{right:10px;bottom:10px;left:auto;gap:6px}.recording-status{display:none}.video-actions button{padding:8px 11px;border-radius:10px;font-size:11px}.live-status{top:10px;padding:7px 10px;font-size:11px}.video-notice{left:10px;bottom:52px;max-width:calc(100% - 20px)}.screenshot-dialog-backdrop{padding:12px}.screenshot-dialog{height:calc(100vh - 24px);max-height:calc(100vh - 24px);padding:12px;gap:10px}.screenshot-dialog h2{font-size:16px}.screenshot-dialog>header>button{flex-shrink:0}}.load-more:enabled:hover,.screenshot-cancel:enabled:hover{border-color:var(--border-strong);background:var(--surface-soft)}.composer-toolbar button:enabled:hover{background:var(--accent-soft)}.screenshot-dialog>header>button:enabled:hover{color:var(--text);background:var(--border)}.message-file:hover{text-decoration:underline;text-underline-offset:3px}@keyframes screenshot-enter{0%{opacity:.8;transform:translateY(4px)}to{opacity:1;transform:translateY(0)}}@media (max-width: 480px){.patient-avatar{width:38px;height:38px;flex-shrink:0}.composer-toolbar>span{display:none}.screenshot-dialog__hint{font-size:11px}}@media (max-height: 480px){.im-ai-header{min-height:54px;padding:8px 14px}.im-ai-header p{display:none}.im-ai-tools{padding-bottom:8px}.im-ai-body{padding:12px 14px}.im-ai-empty{padding:0}.im-ai-empty__line{display:none}.im-ai-footer{padding:8px 14px}.im-ai-footer p{margin-top:5px;font-size:10px}.chat-panel{grid-template-rows:minmax(64px,auto) minmax(0,1fr) auto}.composer textarea{min-height:56px;height:56px;max-height:84px}}@media (prefers-reduced-motion: reduce){button,.composer textarea{transition:none}button:enabled:active{transform:none}.screenshot-dialog{animation:none}} diff --git a/app/video_companion/dist/assets/index-B4Apl_Sl.js b/app/video_companion/dist/assets/index-C_tMrPfb.js similarity index 58% rename from app/video_companion/dist/assets/index-B4Apl_Sl.js rename to app/video_companion/dist/assets/index-C_tMrPfb.js index cea6dbe22..3404d6492 100644 --- a/app/video_companion/dist/assets/index-B4Apl_Sl.js +++ b/app/video_companion/dist/assets/index-C_tMrPfb.js @@ -1,4 +1,4 @@ -(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))l(I);new MutationObserver(I=>{for(const h of I)if(h.type==="childList")for(const f of h.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&l(f)}).observe(document,{childList:!0,subtree:!0});function r(I){const h={};return I.integrity&&(h.integrity=I.integrity),I.referrerPolicy&&(h.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?h.credentials="include":I.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function l(I){if(I.ep)return;I.ep=!0;const h=r(I);fetch(I.href,h)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function yW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function kU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var r=function l(){return this instanceof l?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};r.prototype=i.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(l){var I=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,I.get?I:{enumerable:!0,get:function(){return t[l]}})}),r}var z1={exports:{}},HoA=z1.exports,r8;function qoA(){return r8||(r8=1,function(t,i){(function(r,l){t.exports=l()})(HoA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",I=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},h=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>h(s)||f(s),_=s=>{if(typeof s!="string")return!1;const n=s[0];return!/[^a-zA-Z0-9]/.test(n)},G=s=>{if(typeof s!="object"||s===null)return!1;const n=Object.getPrototypeOf(s);if(n===null)return!0;let g=n;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return n===g};function U(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,u)=>{if(!w(s)||!w(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",io=Et&&typeof wx.miniapp=="object",Eo=typeof uni<"u",Vs=yt&&typeof tt.enterChat=="function",ki=Et||qe||yt||Oe||gt||To||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,jo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),Ao=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Zt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!jo,oo=qe?qq:yt?tt:Oe?swan:gt?my:Et?wx:To?uni:Fi?jd:{},bi=Zt&&window&&window.navigator&&window.navigator.userAgent||"",vs=/(micromessenger|webbrowser)/i.test(bi),HA=function(){let s="WEB";return vs?s="WEB":qe?s="QQ_MP":yt?s="TT_MP":Oe?s="BAIDU_MP":gt?s="ALI_MP":Et?s=io?"DONUT_NATIVE_APP":"WX_MP":To?s="UNI_NATIVE_APP":ns?s="NS_NATIVE_APP":jo&&(s="RN_NATIVE_APP"),sA[s]}(),ce=/iPad/i.test(bi),Ve=/iPhone/i.test(bi)&&!ce,Ot=/iPod/i.test(bi),nt=Ve||ce||Ot,It=function(){const s=bi.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),ei=/Android/i.test(bi),ti=function(){const s=bi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const n=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return n&&g?parseFloat(`${s[1]}.${s[2]}`):n||null}(),be=/Firefox/i.test(bi),Ze=/Edge/i.test(bi),wt=!Ze&&/Chrome/i.test(bi),Nt=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const s=/MSIE\s(\d+)\.\d/.exec(bi);let n=s&&parseFloat(s[1]);return!n&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(n=11),n}(),po=/Safari/i.test(bi)&&!wt&&!ei&&!Ze,No=/Windows/i.test(bi),so=/MAC OS X/i.test(bi),Go=Zt&&typeof Worker<"u"&&!Nt,An=ei||nt,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!nt||s||po)}();function Es(){let s="unknown";if(so&&(s="mac"),No&&(s="windows"),nt&&(s="ios"),ei&&(s="android"),ki)try{const{platform:n}=oo.getSystemInfoSync();n!==void 0&&(s=n)}catch(n){console.error(n)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Do(s,n){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&n.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{oo.request({url:g,data:u,method:n,timeout:E,header:{"content-type":zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${Jn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${Qr}}`))},E);M.onreadystatechange=function(){if(M.readyState===4)if(clearTimeout(T),M.status===200||M.status===304)try{m(M.responseText?JSON.parse(M.responseText):null)}catch{m(M.responseText)}else D(new Error(`{"message":"Network error","code":${Jn}}`))},M.open(n,g,!0),M.setRequestHeader("Content-type",zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(G(s)){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function or(s,n){if(s===null||typeof s!="object")return s;const g=n||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const m=new Map;return g.set(s,m),s.forEach((D,M)=>{m.set(or(M,g),or(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(or(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(or(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=or(s[m],g))}),E}function en(s,n,g){const u=new WeakSet,E=(m,D)=>{if(n&&(D=n(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,n;return{promise:new Promise((g,u)=>{s=g,n=u}),resolve:s,reject:n}}var qt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:ti,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gt,IN_BAIDU_MINI_APP:Oe,IN_BROWSER:Zt,IN_DONUT_NATIVE_APP:io,IN_FEISHU_MINI_APP:Vs,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:ns,IN_QQ_MINI_APP:qe,IN_RN_APP:jo,IN_TT_MINI_APP:yt,IN_TT_MINI_GAME:Me,IN_UNI_APP:Eo,IN_UNI_NATIVE_APP:To,IN_WX_MINI_APP:Et,IN_WX_MINI_APP_DESK:jt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:Ao,IOS_VERSION:It,IS_ANDROID:ei,IS_CHROME:wt,IS_EDGE:Ze,IS_FIREFOX:be,IS_IE:Nt,IS_IOS:nt,IS_IPAD:ce,IS_IPHONE:Ve,IS_IPOD:Ot,IS_MAC:so,IS_SAFARI:po,IS_WECHAT:vs,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:oo,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:or,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:I,httpRequest:Pi,isArray:h,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:f,isPlainObject:G,isString:l,isUndefined:r,isUniIOSApp:function(){return To&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:U,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:en});class On{constructor(){this.listeners={}}on(n,g,u){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:u})}off(n,g,u){var E;g&&(this.listeners[n]=(E=this.listeners[n])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(n,...g){const u=this.listeners[n];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${en(M)}`)}})}once(n,g,u){const E=(...m)=>{g.apply(u,m),this.off(n,E)};this.on(n,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Gn=[16,17];function Js(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(qt.GROUP_MESSAGE_PINNED):g.push(qt.GROUP_TIPS_NOTIFICATION)}),g}const pr=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var n;const g=[];return(n=s?.C2cNotifyMsgArray)===null||n===void 0||n.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(qt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(qt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(qt.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(qt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(qt.TOPIC_MESSAGE_READ_SYNC):g.push(qt.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(qt.TOPIC_SYSTEM_NOTIFICATION):g.push(qt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(qt.TOPIC_AT_TIPS):g.push(qt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var n;const g=[];return(n=s?.RecentContactMod)===null||n===void 0||n.forEach(u=>{switch(u.PushType){case je.CONV_MARK_UPDATED:g.push(qt.CONVERSATION_MARK_UPDATED);break;case je.CONV_GROUP_ADDED:g.push(qt.CONVERSATION_GROUP_ADD);break;case je.CONV_GROUP_DELETED:g.push(qt.CONVERSATION_GROUP_DELETED);break;case je.CONV_GROUP_UPDATED:g.push(qt.CONVERSATION_GROUP_UPDATED);break;default:g.push(qt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Pn;function mr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=pr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(Pn||(Pn={}));const mo={[Pn.SERVER_PUSH_MESSAGE]:mr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:mr,[Pn.ERROR]:function(s){const{errorCode:n}=s;return[{type:`error:${n}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=qt}subscribeInnerEvent(s,n,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=u,D=E):(T=s,P=n,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,n){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(mo).includes(s)){const E=(u=mo[s])===null||u===void 0?void 0:u.call(mo,n);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,n,g)}unSubscribeInnerEvent(s,n,g,u){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,u)}else{const E=n;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,n){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,n)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,n,g,u){var E;const m=D=>{u.call(g,D)&&n.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:n,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===n&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,n,g)}};class Sl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,u;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(n){this._onError=n.onError}connectSocket(n){const g=this;return this._socket=oo.connectSocket({url:n,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const fr="CONNECT",Ls="SEND",Jc="DISCONNECT",ms="OPEN",as="MESSAGE",Ru="CLOSE",Wa="ERROR",Cs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(n){const g=new Blob([` +(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const I of document.querySelectorAll('link[rel="modulepreload"]'))c(I);new MutationObserver(I=>{for(const C of I)if(C.type==="childList")for(const f of C.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&c(f)}).observe(document,{childList:!0,subtree:!0});function n(I){const C={};return I.integrity&&(C.integrity=I.integrity),I.referrerPolicy&&(C.referrerPolicy=I.referrerPolicy),I.crossOrigin==="use-credentials"?C.credentials="include":I.crossOrigin==="anonymous"?C.credentials="omit":C.credentials="same-origin",C}function c(I){if(I.ep)return;I.ep=!0;const C=n(I);fetch(I.href,C)}})();var mg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function HW(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function HU(t){if(t.__esModule)return t;var i=t.default;if(typeof i=="function"){var n=function c(){return this instanceof c?Reflect.construct(i,arguments,this.constructor):i.apply(this,arguments)};n.prototype=i.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(c){var I=Object.getOwnPropertyDescriptor(t,c);Object.defineProperty(n,c,I.get?I:{enumerable:!0,get:function(){return t[c]}})}),n}var aY={exports:{}},psA=aY.exports,_8;function msA(){return _8||(_8=1,function(t,i){(function(n,c){t.exports=c()})(psA,function(){const n=s=>s===void 0,c=s=>typeof s=="string",I=s=>{var r;return(r=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||r===void 0?void 0:r[1].toLowerCase()},C=s=>typeof Array.isArray=="function"?Array.isArray(s):I(s)==="array",f=s=>s!==null&&typeof s=="object",w=s=>C(s)||f(s),_=s=>{if(typeof s!="string")return!1;const r=s[0];return!/[^a-zA-Z0-9]/.test(r)},N=s=>{if(typeof s!="object"||s===null)return!1;const r=Object.getPrototypeOf(s);if(r===null)return!0;let g=r;for(;Object.getPrototypeOf(g)!==null;)g=Object.getPrototypeOf(g);return r===g};function L(s=99999999){return Math.round(Math.random()*s)}const q=(s,r,g,u)=>{if(!w(s)||!w(r))return 0;let E=0;const m=Object.keys(r);let D;for(let M=0,T=m.length;M"u"&&typeof uni.requireNativePlugin=="function",to=ct&&typeof wx.miniapp=="object",so=typeof uni<"u",ks=Dt&&typeof tt.enterChat=="function",Gi=ct||Ve||Dt||Pt||oi||Co||Ni,As=typeof window>"u"&&!Gi&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,Lo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,zt=typeof uni<"u"?!Gi:typeof window<"u"&&!Gi&&!Lo,Ao=Ve?qq:Dt?tt:Pt?swan:oi?my:ct?wx:Co?uni:Ni?jd:{},Ri=zt&&window&&window.navigator&&window.navigator.userAgent||"",Es=/(micromessenger|webbrowser)/i.test(Ri),VA=function(){let s="WEB";return Es?s="WEB":Ve?s="QQ_MP":Dt?s="TT_MP":Pt?s="BAIDU_MP":oi?s="ALI_MP":ct?s=to?"DONUT_NATIVE_APP":"WX_MP":Co?s="UNI_NATIVE_APP":As?s="NS_NATIVE_APP":Lo&&(s="RN_NATIVE_APP"),tA[s]}(),Ee=/iPad/i.test(Ri),Je=/iPhone/i.test(Ri)&&!Ee,Ut=/iPod/i.test(Ri),ot=Je||Ee||Ut,ut=function(){const s=Ri.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),$t=/Android/i.test(Ri),Zt=function(){const s=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!s)return null;const r=s[1]&&parseFloat(s[1]),g=s[2]&&parseFloat(s[2]);return r&&g?parseFloat(`${s[1]}.${s[2]}`):r||null}(),Ge=/Firefox/i.test(Ri),Xe=/Edge/i.test(Ri),se=!Xe&&/Chrome/i.test(Ri),ve=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,pt=function(){const s=/MSIE\s(\d+)\.\d/.exec(Ri);let r=s&&parseFloat(s[1]);return!r&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(r=11),r}(),mo=/Safari/i.test(Ri)&&!se&&!$t&&!Xe,No=/Windows/i.test(Ri),no=/MAC OS X/i.test(Ri),Go=zt&&typeof Worker<"u"&&!ve,An=$t||ot,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!ot||s||mo)}();function ds(){let s="unknown";if(no&&(s="mac"),No&&(s="windows"),ot&&(s="ios"),$t&&(s="android"),Gi)try{const{platform:r}=Ao.getSystemInfoSync();r!==void 0&&(s=r)}catch(r){console.error(r)}return s}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function So(s,r){var g={};for(var u in s)Object.prototype.hasOwnProperty.call(s,u)&&r.indexOf(u)<0&&(g[u]=s[u]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(u=Object.getOwnPropertySymbols(s);E{Ao.request({url:g,data:u,method:r,timeout:E,header:{"content-type":Zr},success:M=>m(M.data),fail:()=>D(new Error(`{"message":"Network error","code":${qn}}`))})}):an?void 0:new Promise((m,D)=>{const M=new XMLHttpRequest,T=setTimeout(()=>{M.abort(),D(new Error(`{"message":"Request timeout","code":${mr}}`))},E);M.onreadystatechange=function(){if(M.readyState===4)if(clearTimeout(T),M.status===200||M.status===304)try{m(M.responseText?JSON.parse(M.responseText):null)}catch{m(M.responseText)}else D(new Error(`{"message":"Network error","code":${qn}}`))},M.open(r,g,!0),M.setRequestHeader("Content-type",Zr),M.send(u||null)})})}function Rs(s){if(s==null)return!0;if(typeof s=="boolean")return!1;if(typeof s=="number")return s===0;if(typeof s=="string"||typeof s=="function"||Array.isArray(s))return s.length===0;if(s instanceof Error)return s.message==="";if(N(s)){for(const r in s)if(Object.prototype.hasOwnProperty.call(s,r))return!1;return!0}return(Object.prototype.toString.call(s)==="[object Map]"||Object.prototype.toString.call(s)==="[object Set]"||Object.prototype.toString.call(s)==="[object File]")&&s.size===0}function rr(s,r){if(s===null||typeof s!="object")return s;const g=r||new WeakMap;if(g.has(s))return g.get(s);if(s instanceof Date)return new Date(s.getTime());if(s instanceof RegExp)return new RegExp(s.source,s.flags);if(s instanceof Map){const m=new Map;return g.set(s,m),s.forEach((D,M)=>{m.set(rr(M,g),rr(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(rr(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(rr(D,g))}),m}const u=Object.getPrototypeOf(s),E=Object.create(u);return g.set(s,E),[...Object.getOwnPropertyNames(s),...Object.getOwnPropertySymbols(s)].forEach(m=>{if(m==="__ob__"||m==="__v_skip"||m==="__v_isRef"||m==="__v_isReadonly")return;const D=Object.getOwnPropertyDescriptor(s,m);D&&(D.get||D.set?Object.defineProperty(E,m,D):E[m]=rr(s[m],g))}),E}function en(s,r,g){const u=new WeakSet,E=(m,D)=>{if(r&&(D=r(m,D)),D===void 0)return"undefined";if(D===null)return null;if(Number.isNaN(D))return"NaN";if(D===1/0)return"Infinity";if(D===-1/0)return"-Infinity";if(typeof D=="function")return`[Function: ${D.name||"anonymous"}]`;if(typeof D=="symbol")return D.toString();if(typeof D=="bigint")return`${D.toString()}n`;if(typeof D=="object"&&D!==null){if(u.has(D))return"[Circular]";u.add(D)}return D instanceof Date?D.toISOString():D instanceof Error?{name:D.name,message:D.message}:D instanceof Map?{dataType:"Map",value:Array.from(D.entries())}:D instanceof Set?{dataType:"Set",value:Array.from(D.values())}:D};try{return JSON.stringify(s,E,g)}catch(m){return console.error("Failed to stringify:",m),""}}function wn(){let s,r;return{promise:new Promise((g,u)=>{s=g,r=u}),resolve:s,reject:r}}var jt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:Zt,IE_VERSION:pt,IN_ALIPAY_MINI_APP:oi,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:zt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:ks,IN_JD_MINI_APP:Ni,IN_MINI_APP:Gi,IN_NODE:an,IN_NS_NATIVE_APP:As,IN_QQ_MINI_APP:Ve,IN_RN_APP:Lo,IN_TT_MINI_APP:Dt,IN_TT_MINI_GAME:ti,IN_UNI_APP:so,IN_UNI_NATIVE_APP:Co,IN_WX_MINI_APP:ct,IN_WX_MINI_APP_DESK:wt,IN_WX_MINI_GAME:ce,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:ut,IS_ANDROID:$t,IS_CHROME:se,IS_EDGE:Xe,IS_FIREFOX:Ge,IS_IE:ve,IS_IOS:ot,IS_IPAD:Ee,IS_IPHONE:Je,IS_IPOD:Ut,IS_MAC:no,IS_SAFARI:mo,IS_WECHAT:Es,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:Ao,USER_AGENT:Ri,base16EncodeBinaryString:lA,deepCopyWithMethods:rr,deepMerge:q,generatePromise:wn,getPlatformType:ds,getType:I,httpRequest:Yi,isArray:C,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:f,isPlainObject:N,isString:c,isUndefined:n,isUniIOSApp:function(){return Co&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:VA,randomInt:L,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let r="";for(let g=32;g>0;--g)r+=s[Math.floor(62*Math.random())];return r},safeStringify:en});class Pn{constructor(){this.listeners={}}on(r,g,u){this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push({fn:g,context:u})}off(r,g,u){var E;g&&(this.listeners[r]=(E=this.listeners[r])===null||E===void 0?void 0:E.filter(m=>{const D=m.fn===g,M=!u||m.context===u;return!(D&&M)}))}emit(r,...g){const u=this.listeners[r];u&&u.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${r} error: ${en(M)}`)}})}once(r,g,u){const E=(...m)=>{g.apply(u,m),this.off(r,E)};this.on(r,E)}}(function(s){s.BUSINESS_COMMAND="business_command",s.C2C_REALTIME_MESSAGE="c2c_realtime_message",s.C2C_MESSAGE_MODIFIED="c2c_message_modified",s.C2C_REVOKED_MESSAGE="c2c_message_revoked",s.GROUP_REALTIME_MESSAGE="group_realtime_message",s.GROUP_MESSAGE_MODIFIED="group_message_modified",s.GROUP_MESSAGE_REVOKED="group_message_revoked",s.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",s.MESSAGE_REACTION_UPDATED="message_reaction_updated",s.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",s.GROUP_AT_TIPS="group_at_tips",s.USER_STATUS_UPDATE="user_status_update",s.FRIEND_LIST_MODIFIED="friend_list_modified",s.PROFILE_MODIFIED="profile_modified",s.CONV_MODIFIED="conversation_modified",s.GROUP_TIPS_NOTIFICATION="group_tips_notification",s.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",s.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",s.GROUP_SYSTEM_NOTIFICATION="group_system_notification",s.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",s.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",s.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",s.FOLLOW_LIST_UPDATED="follow_list_updated",s.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",s.ALL_MESSAGE_READ="all_message_read",s.CONVERSATION_MARK_UPDATED="conversation_mark_updated",s.CONVERSATION_GROUP_ADD="conversation_group_add",s.CONVERSATION_GROUP_DELETED="conversation_group_deleted",s.CONVERSATION_GROUP_UPDATED="conversation_group_updated",s.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",s.TOPIC_AT_TIPS="topic_at_tips",s.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",s.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",s.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",s.TOPIC_LATEST_MESSAGE="topic_latest_message",s.GROUP_MESSAGE_PINNED="group_message_pinned"})(jt||(jt={}));const bn=[16,17];function Js(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{var E;u.GroupInfo.MillionGroupFlag===2?g.push(jt.TOPIC_TIPS_NOTIFICATION):bn.includes((E=u?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(jt.GROUP_MESSAGE_PINNED):g.push(jt.GROUP_TIPS_NOTIFICATION)}),g}const fr=[{conditions:[{type:"event",value:100}],subType:jt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:jt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:jt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:jt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:jt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:jt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:jt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:jt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:jt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:jt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(s){var r;const g=[];return(r=s?.C2cNotifyMsgArray)===null||r===void 0||r.forEach(u=>{u.WithdrawC2cMsgNotify&&g.push(jt.C2C_REVOKED_MESSAGE),u.C2cReadedReceipt&&g.push(jt.C2C_MESSAGE_PEER_READ),u.ReadC2cMsgNotify&&g.push(jt.C2C_MESSAGE_READ_SYNC),u.MuteNotificationsSync&&g.push(jt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{Array.isArray(u.MsgBody.GroupWithdrawInfoArray)?g.push(jt.GROUP_MESSAGE_REVOKED):Array.isArray(u.MsgBody.GroupMsgReceiptList)?g.push(jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(u.MsgBody.GroupReadInfoArray)?u.MsgBody.GroupReadInfoArray[0].TopicId?g.push(jt.TOPIC_MESSAGE_READ_SYNC):g.push(jt.GROUP_MESSAGE_READ_SYNC):u.GroupInfo.MillionGroupFlag===2?g.push(jt.TOPIC_SYSTEM_NOTIFICATION):g.push(jt.GROUP_SYSTEM_NOTIFICATION)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(s){var r;const g=[];return(r=s?.GroupTips)===null||r===void 0||r.forEach(u=>{const{GroupAtTips:{TopicId:E}}=u;E?g.push(jt.TOPIC_AT_TIPS):g.push(jt.GROUP_AT_TIPS)}),g}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(s){var r;const g=[];return(r=s?.RecentContactMod)===null||r===void 0||r.forEach(u=>{switch(u.PushType){case We.CONV_MARK_UPDATED:g.push(jt.CONVERSATION_MARK_UPDATED);break;case We.CONV_GROUP_ADDED:g.push(jt.CONVERSATION_GROUP_ADD);break;case We.CONV_GROUP_DELETED:g.push(jt.CONVERSATION_GROUP_DELETED);break;case We.CONV_GROUP_UPDATED:g.push(jt.CONVERSATION_GROUP_UPDATED);break;default:g.push(jt.CONV_MODIFIED)}}),g}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:jt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:jt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:jt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:jt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:jt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:jt.ALL_MESSAGE_READ}];var xn;function yr(s){var r;const g=Array.isArray((r=s?.body)===null||r===void 0?void 0:r.EventArray)?s.body.EventArray:[],u=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=fr.find(M=>M.conditions.every(T=>{switch(T.type){case"event":return E.Event===T.value;case"hasKey":return Object.prototype.hasOwnProperty.call(E,T.value);default:return!1}}));if(!m)return null;let D=[];typeof m.subTypeParser=="function"?D=m.subTypeParser(E):m.subType&&(D=m.subType),Array.isArray(D)?D.forEach(M=>{u.push({type:`${xn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):u.push({type:`${xn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),u}(function(s){s.SERVER_PUSH_MESSAGE="im_open_push.msg_push",s.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",s.ERROR="error"})(xn||(xn={}));const fo={[xn.SERVER_PUSH_MESSAGE]:yr,[xn.SERVER_PUSH_MESSAGE_MULTIPLE]:yr,[xn.ERROR]:function(s){const{errorCode:r}=s;return[{type:`error:${r}`,data:s}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Pn,this._innerEventEmitter=new Pn,this.InnerEventSubType=jt}subscribeInnerEvent(s,r,g,u,E){var m;let D,M,T,P;["string","number"].includes(typeof r)?(T=`${s}:${r}`,P=g,M=u,D=E):(T=s,P=r,M=g,D=typeof u=="function"?u:void 0),D?this._subscribeWithFilter(T,P,M,D):(m=this._innerEventEmitter)===null||m===void 0||m.on(T,P,M)}emitInnerEvent(s,r){var g,u;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,r),Object.keys(fo).includes(s)){const E=(u=fo[s])===null||u===void 0?void 0:u.call(fo,r);E?.forEach(m=>{var D;m&&((D=this._innerEventEmitter)===null||D===void 0||D.emit(m.type,m.data))})}}subscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.on(s,r,g)}unSubscribeOuterEvent(s,r,g){var u;(u=this._outerEventEmitter)===null||u===void 0||u.off(s,r,g)}unSubscribeInnerEvent(s,r,g,u){if(["string","number"].includes(typeof r)){const E=g,m=`${s}:${r}`;this._unsubscribeEvent(m,E,u)}else{const E=r;this._unsubscribeEvent(s,E,g)}}emitOuterEvent(s,r){var g;(g=this._outerEventEmitter)===null||g===void 0||g.emit(s,r)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(s,r,g,u){var E;const m=D=>{u.call(g,D)&&r.call(g,D)};this._filteredCallbackMap.has(s)||this._filteredCallbackMap.set(s,[]),this._filteredCallbackMap.get(s).push({originalCallback:r,filteredCallback:m,filter:u,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,r,g){var u,E;const m=this._filteredCallbackMap.get(s);if(m){const D=m.findIndex(M=>M.originalCallback===r&&M.context===g);if(D!==-1){const{filteredCallback:M}=m[D];return(u=this._innerEventEmitter)===null||u===void 0||u.off(s,M,g),m.splice(D,1),void(m.length===0&&this._filteredCallbackMap.delete(s))}}(E=this._innerEventEmitter)===null||E===void 0||E.off(s,r,g)}};class Ml{constructor(){this._socket=null}connectSocket(r){return this._socket=new WebSocket(r),this._socket}send(r){var g,u;try{(g=this._socket)===null||g===void 0||g.send(r)}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=u,this._socket.onclose=E,this._socket.onerror=m,this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(r){this._onError=r.onError}connectSocket(r){const g=this;return this._socket=Ao.connectSocket({url:r,header:{"content-type":"application/json"},complete:()=>{},fail:u=>g._onError(u)}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(u),this._socket.onError(m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Dr="CONNECT",Us="SEND",Jc="DISCONNECT",fs="OPEN",as="MESSAGE",wu="CLOSE",Wa="ERROR",hs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(r){const g=new Blob([` let _socket = null; self.onmessage = (event) => { @@ -95,26 +95,26 @@ _socket = null; } } -`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:fr,url:n})}send(n){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Ls,data:n})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ms]:g,[as]:u,[Ru]:E,[Wa]:m,[Cs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class HI{}var As,$i=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return ki?gt?my.getStorageSync({key:s}).data:oo.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,n){const g=this._store.get(s)||{};n instanceof Map?this._store.set(s,n):this._store.set(s,Object.assign(Object.assign({},g),n))}setStorage(s,n){ki?gt?my.setStorageSync({key:s,data:JSON.stringify(n)}):oo.setStorageSync(s,JSON.stringify(n)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(n))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(n){return this._socket=oo.connectSocket({url:n,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(n){var g;(g=this._socket)===null||g===void 0||g.send({data:n,fail:this._onSendFail})}bindSocketHandlers(n){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(As||(As={}));class ng{constructor(n){this._url="",this._readyState=As.DISCONNECTED,this._url=n,this._id=U(),this._emitter=new On,gt?this._socket=new pc:Et||To||yt||qe||Fi||Oe?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new HI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Sl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this._readyState=As.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==As.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,u){this._emitter.on(n,g,u)}off(n,g,u){this._emitter.off(n,g,u)}isConnected(){return this._readyState===As.CONNECTED}disconnect(){this._readyState=As.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===As.CONNECTING&&(this._readyState=As.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=As.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=As.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=As.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:n})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const n=$i.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&Go}}const Dg={[ut.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ut.KOREA]:[[3e7,4e7],[173e7,174e7]],[ut.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ut.IND]:[[5e7,6e7],[175e7,176e7]],[ut.JPN]:[[6e7,7e7],[176e7,177e7]],[ut.USA]:[[7e7,8e7],[177e7,178e7]],[ut.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ut.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(s){var n;if(!((n=$i.get("instance"))===null||n===void 0)&&n.oversea)return ut.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${iA}=${W[iA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const n=$i.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=n,m=ua(g);if(u)return Hn(ft.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Hn(E,{isBinary:s});const D=ft.PRODUCTION[m],M=Zt&&D.ANYCAST,T=Zt,P=!!D.BACKUP_CN;return Hn({[bo.INITIAL]:()=>(_o=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(_o=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(_o=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(_o=bo.BACKUP_WEB_ONLY,function(W){const iA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(iA))}(D.BACKUP_WEB_ONLY)):P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(_o=bo.BACKUP_CN,D.BACKUP_CN):M?(_o=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(_o=M?bo.ANYCAST:bo.DEFAULT,D[_o]),[bo.ANYCAST]:()=>(_o=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[_o](),{isBinary:s})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,n){const g=Date.now(),u=g-s;this._timeOffsetWithServer=n+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:n}=s;this.removeTask(n),this._tasks.push(s),this._taskMap.set(n,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:n,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const n=this._createTask(s);this._addTaskToScheduler(n)}addOnceTask(s){const n=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(n)}removeTask(s){const n=this._tasks.findIndex(g=>g.id===s);n>-1&&(this._tasks.splice(n,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,n){const g=this._taskMap.get(s);g&&(g.intervalMs=n,g.nextExecuteTime=Date.now()+n,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,n)=>s.nextExecuteTime-n.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const n=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),n)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const n=this._tasks[0];try{n.context?n.callback.call(n.context):n.callback(),n.isOnce?this.removeTask(n.id):(n.nextExecuteTime=s+n.intervalMs,this._sort())}catch(g){console.warn(`Task ${n.id} execution failed:`,g),n.isOnce&&this.removeTask(n.id)}}this._scheduleNextTask()}};function Ga(s){const n=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?n.push(u):u<=2047?n.push(192|u>>6,128|63&u):n.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(n)}function In(s){const n=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?n[g]=s[g]:n[g]=In(s[g]));return n}function fs(s,n){if(mA.includes(s))return 0;const g=Ga(JSON.stringify(n));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function Ea(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}function yn(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}}let ba=U();function Sa(){return ba=ba<2415919103?ba+1:U(),ba}function $(){var s;const n=$i.get("login")||{},g=$i.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(n.tinyID),user_id:n.userId||((s=$i.get("webPush"))===null||s===void 0?void 0:s.userId),platform:HA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,vA=Object.freeze({__proto__:null,calcBodyCRC:fs,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,u=function(m){const D=$i.get("login")||{},M=$i.get("instance")||{};return{servcmd:m,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(n),E=In(g);return u.cs=fs(n,E),{head:u,body:E}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const qA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class Ae{constructor(n){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=$i.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(n.errorCode&&(this.code=n.errorCode),n.errorMessage&&this.setMoreMessage(n.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(n){return Object.keys(n).forEach(g=>{Object.keys(qA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const u=g;qA[u]&&(n[qA[u]]=this[u])}),n}_getUiPlatform(){var n;const g=(n=$i.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var n;return(n=$i.get("instance"))===null||n===void 0?void 0:n.sdkEdition}}var me;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(me||(me={}));var Pe=me;const Fe=20,rt=6e4,Ct=[4,5,6],Rt="report-logger";var Yt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:xe,maxCount:Qe},single:{throttleTime:ue,maxCount:Ce}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Rt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Fe,evt_rpt_waiting:g=rt,evt_rpt_level:u=Ct,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=xe,evt_rpt_global_throttle_count:M=Qe,evt_rpt_single_throttle_time:T=ue,evt_rpt_single_throttle_count:P=Ce}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const n=new Ae(s);return n.setSSOLogModule(this),this._ssoLogMap.set(s.method,n),n}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,n="",g){this._log(IA.DEBUG,s,n,g)}info(s,n="",g){this._log(IA.INFO,s,n,g)}warn(s,n="",g){this._log(IA.WARN,s,n,g)}error(s,n="",g){this._log(IA.ERROR,s,n,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return pA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const n=this._filterLogs(s);if(n.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:n};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return ye.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(n))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const n=this._logQueue.length-200;n>0&&(this._logQueue.splice(0,n),this.debug("uploadSSOLogData",`log queue overflow, dropped ${n} oldest logs`))}_savePlatFormInfo(){var s,n;if(Et){const g=(n=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||n===void 0?void 0:n.miniProgram;if(g){const{appId:u,envVersion:E}=g;$i.set("instance",{appId:u,envVersion:E})}}else Zt&&$i.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=$i.get("login")||{},{sdkAppId:g}=$i.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const n=Date.now(),g=this._singleThrottleMap.get(s);return g?n-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=n,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:n}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(WA[s])}_formatLog(s,n,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Nt||ki?[`${cA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",cA,"",`[${m}] ${D} [${n}] ${g} params: ${en(u)}`]}_log(s,n,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,u);TA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:n})).end()}}_getThrottleKey(s,n,g){const u=`${s}${n}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Rt),gn.unSubscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Ii=15e3,ct="Channel",xt="channel_schedule_task",Ji="channel_reconnect_task",Ki="connected",qs="connecting",Mi="disconnected",zo=1e3,Mg="network_status_change",sr="activity_status_change",yr="send_fail",xn="reconnect_failed",Ml="socket_error",Ks="socket_close";function aI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wg(s){return Wg=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},Wg(s)}function fc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var wu,Ma={exports:{}},vl=(wu||(wu=1,function(s){s.exports=function n(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var iA=u[T]={exports:{}};g[T][0].call(iA.exports,function(EA){return m(g[T][1][EA]||EA)},iA,iA.exports,n,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?iA[xA++]=224|EA>>>12:(iA[xA++]=240|EA>>>18,iA[xA++]=128|EA>>>12&63),iA[xA++]=128|EA>>>6&63),iA[xA++]=128|63&EA);return iA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var iA=new E.Buf8(W.length),EA=0,RA=iA.length;EA>10&1023,SA[RA++]=56320|1023&kA)}return P(SA,RA)},u.utf8border=function(W,iA){var EA;for((iA=iA||W.length)>W.length&&(iA=W.length),EA=iA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?iA:EA+M[W[EA]]>iA?EA:iA}},{"./common":1}],3:[function(n,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var iA=T;iA>>8^P[255&(m^D[iA])];return-1^m}},{}],6:[function(n,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(n,g,u){g.exports=function(E,m){var D,M,T,P,W,iA,EA,RA,kA,xA,LA,SA,OA,JA,ae,se,_i,Ti,Ft,Ni,cs,Se,mt,UA,ri;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ri=E.output,W=P-(m-E.avail_out),iA=P+(E.avail_out-257),EA=D.dmax,RA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,JA=D.lencode,ae=D.distcode,se=(1<>>=Ft=Ti>>>24,OA-=Ft,(Ft=Ti>>>16&255)==0)ri[P++]=65535&Ti;else{if(!(16&Ft)){if(!(64&Ft)){Ti=JA[(65535&Ti)+(SA&(1<>>=Ft,OA-=Ft),OA<15&&(SA+=UA[M++]<>>=Ft=Ti>>>24,OA-=Ft,!(16&(Ft=Ti>>>16&255))){if(!(64&Ft)){Ti=ae[(65535&Ti)+(SA&(1<>>=Ft,OA-=Ft,(Ft=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Se>>>8&65280)+((65280&Se)<<8)+((255&Se)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function OA(Se){var mt;return Se&&Se.state?(mt=Se.state,Se.total_in=Se.total_out=mt.total=0,Se.msg="",mt.wrap&&(Se.adler=1&mt.wrap),mt.mode=RA,mt.last=0,mt.havedict=0,mt.dmax=32768,mt.head=null,mt.hold=0,mt.bits=0,mt.lencode=mt.lendyn=new E.Buf32(kA),mt.distcode=mt.distdyn=new E.Buf32(xA),mt.sane=1,mt.back=-1,iA):EA}function JA(Se){var mt;return Se&&Se.state?((mt=Se.state).wsize=0,mt.whave=0,mt.wnext=0,OA(Se)):EA}function ae(Se,mt){var UA,ri;return Se&&Se.state?(ri=Se.state,mt<0?(UA=0,mt=-mt):(UA=1+(mt>>4),mt<48&&(mt&=15)),mt&&(mt<8||15=Gi.wsize?(E.arraySet(Gi.window,mt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(ri<(_s=Gi.wsize-Gi.wnext)&&(_s=ri),E.arraySet(Gi.window,mt,UA-ri,_s,Gi.wnext),(ri-=_s)?(E.arraySet(Gi.window,mt,UA-ri,ri,0),Gi.wnext=ri,Gi.whave=Gi.wsize):(Gi.wnext+=_s,Gi.wnext===Gi.wsize&&(Gi.wnext=0),Gi.whave>>8&255,UA.check=D(UA.check,dg,2,0),bt=Gt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&Gt)<<8)+(Gt>>8))%31){Se.msg="incorrect header check",UA.mode=30;break}if((15&Gt)!=8){Se.msg="unknown compression method",UA.mode=30;break}if(bt-=4,Va=8+(15&(Gt>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Se.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&Gt,dg[1]=Gt>>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0,UA.mode=3;case 3:for(;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>8&255,dg[2]=Gt>>>16&255,dg[3]=Gt>>>24&255,UA.check=D(UA.check,dg,4,0)),bt=Gt=0,UA.mode=4;case 4:for(;bt<16;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>8),512&UA.flags&&(dg[0]=255&Gt,dg[1]=Gt>>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;bt<16;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>8&255,UA.check=D(UA.check,dg,2,0)),bt=Gt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(Bo=UA.length)&&(Bo=xi),Bo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ri,Gi,Bo,Va)),512&UA.flags&&(UA.check=D(UA.check,ri,Bo,Gi)),xi-=Bo,Gi+=Bo,UA.length-=Bo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(Bo=0;Va=ri[Gi+Bo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Bo>9&1,UA.head.done=!0),Se.adler=UA.check=0,UA.mode=12;break;case 10:for(;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=7&bt,bt-=7&bt,UA.mode=27;break}for(;bt<3;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,mt!==6)break;Gt>>>=2,bt-=2;break A;case 2:UA.mode=17;break;case 3:Se.msg="invalid block type",UA.mode=30}Gt>>>=2,bt-=2;break;case 14:for(Gt>>>=7&bt,bt-=7&bt;bt<32;){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>16^65535)){Se.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&Gt,bt=Gt=0,UA.mode=15,mt===6)break A;case 15:UA.mode=16;case 16:if(Bo=UA.length){if(xi>>=5,bt-=5,UA.ndist=1+(31&Gt),Gt>>>=5,bt-=5,UA.ncode=4+(15&Gt),Gt>>>=4,bt-=4,286>>=3,bt-=3}for(;UA.have<19;)UA.lens[rS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,_I={bits:UA.lenbits},Yl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Se.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=Tr,bt-=Tr,UA.lens[UA.have++]=wI;else{if(wI===16){for(iE=Tr+2;bt>>=Tr,bt-=Tr,UA.have===0){Se.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Bo=3+(3&Gt),Gt>>>=2,bt-=2}else if(wI===17){for(iE=Tr+3;bt>>=Tr)),Gt>>>=3,bt-=3}else{for(iE=Tr+7;bt>>=Tr)),Gt>>>=7,bt-=7}if(UA.have+Bo>UA.nlen+UA.ndist){Se.msg="invalid bit length repeat",UA.mode=30;break}for(;Bo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Se.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,_I={bits:UA.lenbits},Yl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,_I),UA.lenbits=_I.bits,Yl){Se.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,_I={bits:UA.distbits},Yl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,_I),UA.distbits=_I.bits,Yl){Se.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,mt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=gr){Se.next_out=Or,Se.avail_out=gr,Se.next_in=Gi,Se.avail_in=xi,UA.hold=Gt,UA.bits=bt,M(Se,ln),Or=Se.next_out,_s=Se.output,gr=Se.avail_out,Gi=Se.next_in,ri=Se.input,xi=Se.avail_in,Gt=UA.hold,bt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[Gt&(1<>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=ac,bt-=ac,UA.back+=ac}if(Gt>>>=Tr,bt-=Tr,UA.back+=Tr,UA.length=wI,xg===0){UA.mode=26;break}if(32&xg){UA.back=-1,UA.mode=12;break}if(64&xg){Se.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&xg,UA.mode=22;case 22:if(UA.extra){for(iE=UA.extra;bt>>=UA.extra,bt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[Gt&(1<>>16&255,wI=65535&Yg,!((Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>ac)])>>>16&255,wI=65535&Yg,!(ac+(Tr=Yg>>>24)<=bt);){if(xi===0)break A;xi--,Gt+=ri[Gi++]<>>=ac,bt-=ac,UA.back+=ac}if(Gt>>>=Tr,bt-=Tr,UA.back+=Tr,64&xg){Se.msg="invalid distance code",UA.mode=30;break}UA.offset=wI,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(iE=UA.extra;bt>>=UA.extra,bt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Se.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(gr===0)break A;if(Bo=ln-gr,UA.offset>Bo){if((Bo=UA.offset-Bo)>UA.whave&&UA.sane){Se.msg="invalid distance too far back",UA.mode=30;break}Bo>UA.wnext?(Bo-=UA.wnext,Il=UA.wsize-Bo):Il=UA.wnext-Bo,Bo>UA.length&&(Bo=UA.length),_C=UA.window}else _C=_s,Il=Or-UA.offset,Bo=UA.length;for(gr_i?(Ft=Il[_C+xA[mt]],Ni=bt[tE+xA[mt]]):(Ft=96,Ni=0),SA=1<>Or)+(OA-=SA)]=Ti<<24|Ft<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(Gt&=SA-1,Gt+=SA):Gt=0,mt++,--ln[Se]==0){if(Se===ri)break;Se=W[iA+xA[mt]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=vl.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=n;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${ct}.onConnect cost:${u} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${ct}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Pe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ki,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(n)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var s;const n=Ea({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const u=(s=$i.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${ct}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return pA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=To?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${ct}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:Ki,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=$i.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${ct}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(Yt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Pe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const u=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${ct}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Yt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:sr})}_resetReconnectDelay(){var s;Yt.debug(`${ct}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=$i.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?zo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=$i.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${ct}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Yt.debug(u),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Yt.info(n,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){pA(this,void 0,void 0,function*(){const n=s.split("/")[2];if(!n.startsWith("ws"))return;const g=`https://${n}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:g,data:{}})}catch(u){Yt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){pA(this,void 0,void 0,function*(){const n=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:n,data:{}})}catch(g){Yt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=n;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Qr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=$i.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=Es();if((gt||Et&&n==="windows"||Vs)&&(this._isBinarySupported=!1),To){const{uniRuntimeVersion:g=""}=oo.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const n=new Uint8Array(s);return n[0]===67&&n[1]===79&&n[2]===77&&n[3]===80}};const fe={init:function(s){$i.set("instance",s),ye.init()},destroy:function(){ye.dispose(),$i.clear(),fn.dispose()},notificationCenter:gn,channel:ye,store:$i,ssoLog:Yt,utils:yg,common:vA,constants:Mt},vg=s=>typeof s=="function";function rg(s,n,g){const u=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(n).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],n[D],g):s[D]===n[D]))}var Rg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Rg||(Rg={}));var Dn,Dr=Rg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Dn||(Dn={}));var ui,no=Dn;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(ui||(ui={}));var qc=ui;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:no.MESSAGE_MODIFIED,delete:no.MESSAGE_DELETED,revoke:no.MESSAGE_REVOKED};var Kc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Kc||(Kc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:Kc}),_u={[yc.modify]:no.TOPIC_MESSAGE_MODIFIED,[yc.delete]:no.TOPIC_MESSAGE_DELETED,[yc.revoke]:no.TOPIC_MESSAGE_REVOKED},SE={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},_g=Object.assign({},SE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),ME=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},sa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Tg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},gI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:sa,GROUP_TIPS_OPERATION_TYPE:Tg}),hs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Lo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),ME),gI),hs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),da={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},nr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Vt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Kt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Ng={[Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Kt.USER_STATUS_UPDATE},{stepId:Kt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Kt.UNREAD_MESSAGE_SYNC,dependency:Kt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Kt.CONVERSATION_RECOVER},{stepId:Kt.HISTORY_MESSAGE_RECOVER,dependency:Kt.CONVERSATION_RECOVER},{stepId:Kt.BLACKLIST_RECOVER},{stepId:Kt.FRIEND_RECOVER},{stepId:Kt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Kt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Kt.HISTORY_MESSAGE_RECOVER},{stepId:Kt.GROUP_TIPS_RECOVER,dependency:Kt.HISTORY_MESSAGE_RECOVER},{stepId:Kt.TOPIC_REQUEST_INFO_RESET},{stepId:Kt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_RECOVER]},{stepId:Kt.EMIT_C2C_MESSAGE_EVENT,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Kt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Kt.CONVERSATION_RECOVER},{stepId:Kt.STREAM_MESSAGE_RECOVER}],[Vt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Kt.COMMERCIAL_CONFIG_UPDATE},{stepId:Kt.CLOUD_CONFIG_SYNC},{stepId:Kt.USER_PROFILE_SYNC},{stepId:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Kt.GROUP_LIST_SYNC},{stepId:Kt.CONVERSATION_LIST_SYNC},{stepId:Kt.SIGNALING_MESSAGE_RECOVER,dependency:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC]},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC,Kt.CONVERSATION_LIST_SYNC]},{stepId:Kt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Kt.GROUP_LIST_SYNC,Kt.CONVERSATION_LIST_SYNC]},{stepId:Kt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Kt.CONVERSATION_GROUP_UPDATE,dependency:[Kt.CONVERSATION_LIST_SYNC,Kt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Kt.QUALITY_REPORT}],[Vt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Kt.HANDLE_C2C_NEW_MESSAGE},{stepId:Kt.UNREAD_MESSAGE_SYNC},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_C2C_NEW_MESSAGE},{stepId:Kt.EMIT_C2C_MESSAGE_EVENT,dependency:[Kt.HANDLE_C2C_NEW_MESSAGE,Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Kt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Kt.UNREAD_MESSAGE_SYNC]}],[Vt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Kt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Kt.HANDLE_GROUP_NEW_MESSAGE,Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Vt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Kt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Kt.EMIT_GROUP_TIPS_EVENT,dependency:[Kt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Kt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},cI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},rr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},qI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:da,InnerEvent:no,NEED_LOG_API:qI,OuterConstant:Lo,OuterEvent:Dr,PUSH:hs,QUALITY_METRICS:cI,SDK_EDITION:nr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:rr,SignalingEvent:qc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Vt,WORKFLOW_STEP:Kt}),na,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(na||(na={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(un||(un={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Sn||(Sn={}));const Tu={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:jc,FORCE_OFFLINE:KI}=no,{KICKED_OUT_MULT_ACCOUNT:vE,KICKED_OUT_MULT_DEVICE:lI,KICKED_OUT_REST_API:Nu,ACCOUNT_A2KEY_EXPIRED:Rl,MSG_A2KEY_EXPIRED:Sc}=da;class Gu{init(){const{notificationCenter:n}=fe;n.subscribeInnerEvent(KI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(Ua,Nu,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(jc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=n?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(n){return n.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(n){const{errorCode:g}=n;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(n){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=n,{ssoLog:u,utils:{safeStringify:E}}=fe;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield fe.login.loginAction.logout(na.KICKED_OUT):fe.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{fe.notificationCenter.emitOuterEvent(Dr.KICKED_OUT,{data:{type:Tu[g]},name:Dr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=n,E=`type:${Tu[g]} newInstanceInfo: ${JSON.stringify(u)}`;fe.ssoLog.warn("kickedOut",E)}_isKickedOut(n){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(n)}_isChatLoginEvent(n){const{requestHead:g}=n||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(n){return![Sn.usersigExpired,un.restApi].includes(n)}_isCurrentInstanceKickedOut(n){const{isLoggedIn:g,statusInstanceId:u}=fe.store.get("login")||{};return g===!0&&n===u}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(KI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(Ua,Rl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,vE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,lI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(Ua,Nu,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(jc,this._dispose,this)}}function bu(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=fe.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:iA,RichMsgAuthKey:EA,ErrorCode:RA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:iA,authKey:EA,errorCode:RA,errorInfo:kA,actionStatus:xA}}})}function wl(){const{store:s}=fe;return ua(s.get("instance").sdkAppId)!==ut.CHINA}function rs(s){var n;try{const g=$i.getStorage("errorMessage");if(!s||!g)return"";const u=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=wl()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(u?rs(n):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function ud(s,n){var g;if(s&&((g=fe.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:da.USER_NOT_LOGGED_IN,functionName:n})}function II(s,n,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,n){RE.push({interceptor:s,context:n})}function Wc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(_l,n),g&&typeof g=="object"&&Object.assign(Ed,g)}function tn(s){return fe.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(n,u),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(u).toISOString()}`))},success:(n,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${n}-${g}`),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?u-E:0;this._workflowStartTimes.delete(n),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(n,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=fe,D=Date.now();if(g){const M=this._stepStartTimes.get(`${n}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${n}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${n}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(n),T=M?D-M:0;this._workflowStartTimes.delete(n),E.error("_executeWorkflowStep",`[Workflow ${n}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(n){ws._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,u,E){if(!this._handlers.has(n))return void fe.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Ng[n].find(D=>D.stepId===g))return void fe.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const u=Ng[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(iA=>!M.runningSteps.has(iA)).forEach(iA=>{M.completedSteps.has(iA)||M.runningSteps.has(iA)||this._executeWorkflowStep(iA,M,{onComplete:()=>{if(M.pendingSteps.size===0)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:n}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(fe.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),fe.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){fe.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,u){return pA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(n),this._logWorkflowExecution(E,n,"start");try{const P=D.get(n);let W=null;P?.dependency&&(l(P.dependency)?W=M[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=M[EA]})));const iA=this._handlers.get(E).get(n);if(iA){const EA=yield Promise.resolve(iA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:iA,errorInfo:EA=`${W} failed`}=P||{},RA=new gs({functionName:W,code:iA,message:EA});fe.ssoLog.error(W,EA,{error:RA}),this._logWorkflowExecution(E,n,"error",P),u.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(n=>{this._handlers.has(n)||this._handlers.set(n,new Map)})}_cancelWorkFlow(n){const g=this._activeWorkflows.get(n);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Ng).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Ng[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=n;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(l(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(h(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:u,stepId:E}=n;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,u,E){this._logHandlers[u](n,g)}}const Ca=new Map,Xr=({type:s,groupID:n})=>s===Lo.GRP_COMMUNITY||`${n}`.startsWith(sa.COMMUNITY)&&!`${n}`.includes(sa.TOPIC),zc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(sa.COMMUNITY)&&`${n}`.includes(sa.TOPIC)},dd="openim",Zg="million_group_open_http_svc";function gg(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return wE(D)||Xg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Xg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:iA=""}=W;const EA=iA;return[iA]=EA.split(sa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:iA,TopicId:EA})}}(m):(wE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,u=fe.common.generateProtocolData({servcmd:n,data:g}),E=`${u.head.seq}${n}`;return fe.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function wE(s){const{Type:n,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return Xr({type:n,groupID:E})}function Xg(s){const{GroupId:n=""}=s;return zc(n)}function qn(s){if(s.includes(dd))return s;const n=s.split(".")[1];return`${Zg}.${n}`}function Ar(){var s;return(s=fe.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>h(s)||f(s),Cd=(s,n,g,u)=>{if(!Fa(s)||!Fa(n))return 0;let E=0;const m=Object.keys(n);let D;for(let M=0,T=m.length;M{if(r(n))return"";if(s===Lo.MSG_TEXT)return n.text||"";const g=jI[s];return g?ku(g):""},Xc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],WI="im_sdk_config_mgr.fetch_config",EI="im_sdk_config_mgr.push_configv2",$c="cloud-config",Al=2996,va=new class{init(s){this.core=s}};function bg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:WI,data:{uint32_sdkappid:n,uint64_version:s}}),u=`${g.head.seq}${WI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var ys=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(EI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return pA(this,void 0,void 0,function*(){var n;const g={code:0,data:""};return s&&(g.data=((n=this._core.store.get("cloudConfig"))===null||n===void 0?void 0:n[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:n,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:Al,replacement1:s})}_handlePushedConfig(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:$c,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",n(g))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:n}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",n(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",n(g))}})}_updateCloudConfig(s){return pA(this,void 0,void 0,function*(){const n=this._parseCloudConfig(s);n&&(this._core.store.set("cloudConfig",n),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,n),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:n}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:n,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(n===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=n===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var s;let n=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(n))try{n=JSON.parse(n),this._updateCmdFreqLimitMap(n)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask($c),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(EI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}};class Kn{constructor(n=0,g=0){this.high=n,this.low=g}equal(n){return n!==null&&this.low===n.low&&this.high===n.high}toString(){const n=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return n+g}}const vc={SEARCH_GRP_SNS:new Kn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Kn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Kn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Kn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Kn(0,Math.pow(2,6)).toString(),USER_STATUS:new Kn(0,Math.pow(2,7)).toString(),CONV_MARK:new Kn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Kn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Kn(0,Math.pow(2,11)).toString(),MSG_EXT:new Kn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Kn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Kn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Kn(Math.pow(2,7)).toString(),PLUGIN_CS:new Kn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Kn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Kn(Math.pow(2,10)).toString(),MSG_REACTION:new Kn(Math.pow(2,16)).toString(),FOLLOW:new Kn(Math.pow(2,20)).toString()},zI="CommercialConfig",ZI="commercial-config";var _E=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:n,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),n.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return pA(this,void 0,void 0,function*(){const n=parseInt(s,10).toString(2),{length:g}=n;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(u=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${zI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var s;const{ssoLog:n,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){n.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return pA(this,void 0,void 0,function*(){const{purchaseBits:n}=s?.data||{};n&&(this._parsePurchaseBits(n),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:ZI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const n=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return n&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:n}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(n.warn("_parseCommercialConfig",`${zI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${zI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${zI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([u,E])=>E===n);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(ZI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},rh=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:u}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:n,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-n<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:n,DelaySecs:g}=s;this._serverOverloadInfoMap.set(n,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}},IC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),ys.install(s),_E.install(s),rh.install(s)}},ah=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return pA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const n=yield this._fetchErrorMessage();if(!n)return;const g=this._parseResponse(n);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return pA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:n}=s;return n&&new Date().getTime()-n>=6048e5}_parseResponse(s){if(typeof s=="string"){const n=s.split(`; -`),g={},u=new RegExp(/'/g);for(let E=0;E{var JA,ae,se;const _i=function(Ti,Ft){const{From_Account:Ni,From_AccountHeadurl:cs,From_AccountNick:Se,IsNeedReadReceipt:mt,MsgBody:UA,MsgClientTime:ri,MsgRandom:_s,MsgSeq:Gi,MsgTimeStamp:Or,SendMsgControl:xi,SupportMessageExtension:gr,To_Account:Gt,TinyId:bt,MsgCheckResult:tE,CloudCustomData:ln,IsPeerRead:Bo,MsgFlagBits:Il,MsgVersion:_C,EventArray:Tr}=Ti;return{from:Ni,avatar:cs,nick:Se,needReadReceipt:mt===1,readReceiptSentByPeer:Bo,clientTime:ri,messageFlagBits:Il,random:_s,sequence:Gi,time:Or,messageControlInfo:xi,isSupportExtension:gr,to:Gt,tinyID:bt,checkResult:tE,cloudCustomData:ln,messageVersion:_C,eventArray:Tr,elements:Ft.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((se=(ae=(JA=OA?.EventArray)===null||JA===void 0?void 0:JA[0])===null||ae===void 0?void 0:ae.hasOwnProperty)===null||se===void 0)&&se.call(ae,"C2cNotifyMsgArray"))SA.push(...function(Ti){var Ft;const Ni=[];return(Ft=Ti.EventArray)===null||Ft===void 0||Ft.forEach(cs=>{var Se,mt;const{C2cNotifyMsgArray:UA}=cs,ri=(mt=(Se=UA?.[0])===null||Se===void 0?void 0:Se.WithdrawC2cMsgNotify)===null||mt===void 0?void 0:mt.C2cWithdrawInfoArray;Array.isArray(ri)&&Ni.push(...ri)}),Ni}(OA));else{const Ti=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:Ft}=_i;Ti.setElement(Ft),LA.push(Ti)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,n);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:RA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:iA}}catch(T){console.warn(T)}})}var kg,ro;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(kg||(kg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(ro||(ro={}));var uC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:n}=s;s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(n.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,n.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:n=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?ro.NEW_MESSAGE_RECEIVED:ro.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:iA=[],overflowUnreadCountList:EA,unreadCountList:RA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...iA),this._updateConversationUnreadOptions({unreadCountList:RA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),n){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return pA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return pA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:n,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;n?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return pA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var n;const{messageDataHandler:g}=this._core.message||{},u=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:n}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(n.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,n.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:iA}=E,EA=iA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:M,subType:T,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}n.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((n=E.conversationStore.getConversationMap())===null||n===void 0?void 0:n.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;try{n.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield el(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:iA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===kg.START_SYNC||n===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(n=>{const{ID:g}=n;this._unreadDBMessageMap.set(g,n)})}_handleDisconnect(){var s;const{appStore:n}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=n.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:n}=this._core,g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(s){var n;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,n;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(n=this._core)===null||n===void 0||n.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},NE=new class{init(s){var n;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,n,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((n=m?.onShow)===null||n===void 0||n.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),this._reset()}},hd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?NE.init(s):TE.init(s))}};const GE="none",tl="online";var dI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:tl})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:GE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Lu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var n,g;const{isConnected:u,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,n;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((n=this._core)===null||n===void 0?void 0:n.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uu=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?Lu.init(s):dI.init(s)}},EC=new class{constructor(){this.name="SystemStateMonitor"}install(s){hd.init(s),Uu.init(s)}};const wr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),cg="tui_room_svr.*";var Rc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=wr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:u}=s;n.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),n.subscribeInnerEvent("im_open_push.msg_push",n.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:n});return{code:0,data:(yield function(E,m){return pA(this,void 0,void 0,function*(){const{helper:D,channel:M}=m,{serviceCommand:T=cg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(RA){console.warn(RA)}const iA=D.generateProtocolData({servcmd:T,data:W}),EA=`${iA.head.seq}${T}`;return M.sendPacket(iA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:n})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const n=JSON.parse(s.rtc_cmd);Array.isArray(n)&&(this._transferredCommands=new Set([...this._transferredCommands,...n]))}catch(n){console.log(n)}}_isValidTransferredCommand(s=""){const n=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(n)}_onServerPushBusinessCommand(s){const{OuterEvent:n,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=wr}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;this._reset(),s.unSubscribeInnerEvent(n.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Fu=1,Tl=2,Bd=3,$r=4,CI=5,_n="TIMCustomElem",dC="C2C",il="GROUP",Qd="invite",hI="accept",Oa="cancel",CC="reject",Pa="modifyInvitation",ur="signaling",pd=8010,Ou="signaling-timeout";function Er(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function ol(s,n){return s.toString(16).padStart(n,"0")}function Lg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const M=this._core.common.getCurrentUserID();return D.includes(M)}return!0}updateSignaling(s){const n=`${ur}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${n} remove ${D}. localInviteeList.length:${M.length}`)),M.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},$g=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=n,E=g||u[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:u}=n,E=g||u;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Oo.getSignaling(m))===null||n===void 0?void 0:n.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,n){const g=n===CI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const n=`${ur}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Fu,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${ur}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Bd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${ur}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Tl,groupID:m,inviter:u,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${ur}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Oo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:$r,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${ur}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Oo.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:CI,inviter:m,inviteeList:g?E:[D]});return console.log(`${n} signalingData:`,M),M}_createSignaling(s,n){var g,u,E;const{groupID:m=""}=s,D={to:n,conversationType:m?il:dC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[ol(Lg(32),8),ol(Lg(16),4),ol(16384|Lg(12),4),ol(32768|Lg(14),4),ol(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return pA(this,void 0,void 0,function*(){var n;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Oo.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${Ou}-${D}`,intervalMs:1e3*(M+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},m),{inviteID:D})}return m}catch(g){throw g}})}accept(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeAccept(n),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Oo.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:n})):m}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}cancel(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeCancel(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}reject(s){return pA(this,void 0,void 0,function*(){try{const{inviteID:n}=s;this._validateBeforeReject(n),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Oo.removeSignaling(n),Object.assign(Object.assign({},E),{inviteID:n})):E}catch(n){throw n}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return pA(this,void 0,void 0,function*(){var n,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Oo.getSignaling(u),{signaling:M}=D,T=Do(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(n=this._core)===null||n===void 0?void 0:n.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Oo.hasSignaling(u)&&Oo.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Oo.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(Er([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Fu,timeout:u.timeout||0};return n.debug(`${ur} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Oo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Oo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const u=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${ur}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=$g.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:iA,inviteeList:EA,inviter:RA}=M;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:iA,inviteID:m,inviteeList:EA,inviter:RA,isSelfTimeout:!0,message:D}}),E?Oo.removeSignaling(m):Oo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Oo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:pd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=Qd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=hI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeCancel(s){const n=Oa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:u}=Oo.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=CC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Oo.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeModifyInvitation(s){const n=Pa;this._validateInviteId(n,s)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Nl=new class{constructor(){this._actionProcessor=new Map([[Fu,this._onNewInvitationReceived.bind(this)],[$r,this._onInviteeRejected.bind(this)],[Bd,this._onInviteeAccepted.bind(this)],[Tl,this._onInvitationCancelled.bind(this)],[CI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(n=>{const g=wc(n);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,n)}})}_handleMessageReceived(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Oo.getSignalingListenStatus())return;const n=Er(s.data);n.length>0&&n.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,n){var g,u;const E=`${ur}._onNewInvitationReceived`,{inviteID:m,inviteeList:D,groupID:M}=s,T=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),M&&!D.includes(T))return;let{timeout:P}=s;const W=Date.now()/1e3-n.time;P>0&&W>0&&P>W&&(P-=W);const iA=Oo.getSignaling(m);iA!==s&&(iA||Oo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Ou}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${ur}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var n;const g=`${ur}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var n;const g=`${ur}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Oo.removeSignaling(u),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var n;const g=`${ur}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Oo.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Oo.updateSignaling(s),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,n){var g;const u=`${ur}._onInvitationModified`,{inviteID:E,data:m}=s,D=Oo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Oo.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:n})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:n,inviter:g,groupID:u,data:E}=s;return{inviteID:n,inviter:g,groupID:u,data:E||""}}_dispose(){var s,n,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},Aa=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(u.DESTROY,this._dispose,this),n.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:n}={}}=s||{};if(!(n?.size!==0&&Oo.getSignalingListenStatus()))return;const g=Er([...n.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Nl.handleActionSignaling(u)}}_handleC2CActionType(s){const n=wc(s);if(!n)return;const{actionType:g}=n;g===Fu?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-n.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[n]}))}_removeOfflineInvite(s){const{inviteID:n=""}=s;this._offlineSignalingMap.has(n)&&this._offlineSignalingMap.delete(n)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(n=>{s=[...s,...n.signalingList]}),s.sort((n,g)=>n.time-g.time)}_dispose(){var s,n;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(n=this._core)===null||n===void 0||n.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const gh={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},js={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var XI=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Nl.init(s),$g.init(s),Oo.init(s),Aa.init(s),s.helper.registerValidateConfig({auth:js,params:gh})}};const Us=new class{init(s){this.core=s}};function _c(s){let n;const{message:g}=Us.core,{conversationID:u,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),n}function Ac(s){return s.map(n=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:iA,time:EA}=n;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(n.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:iA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function dr(s){var n;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:iA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:iA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(RA=>{const{MsgType:kA}=RA;return Us.core.message.messageFactory.getElementClass(kA).parseServerPushElement(RA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const bE="MSG_REACTION",hC="MSG_EXT",ch=0,ao=1,Tc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},Gl="16k_zh",BC="16k_en",QC="16k_yue",bl="16k_ja",$I="16k_zh-PY",BI={[Tc.ZH_CN]:Gl,[Tc.EN_US]:BC,[Tc.YUE_HK]:QC,[Tc.JA_JP]:bl,[Tc.ZH_PY]:$I},QI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,kE={READ:0,UNREAD:1},kl=1,Ll=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const md=16,LE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var Au;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(Au||(Au={}));const lo="StreamMsg.PushStreamHttp";var UE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;n.registerApi({apiName:"addMessageReaction",context:this}),n.registerApi({apiName:"removeMessageReaction",context:this}),n.registerApi({apiName:"getMessageReactions",context:this}),n.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:iA,time:EA,sequence:RA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:JA,clientSequence:ae,random:se,time:_i,reactionID:Ti}=xA,Ft={From_Account:OA,To_Account:JA,MsgKey:`${ae}_${se}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Ft})})}({from:T,to:P,clientSequence:W,random:iA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:JA,sequence:ae}=xA,se={GroupId:OA,MsgSeq:ae,Reaction:JA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:se})})}({to:P,reactionID:n,sequence:RA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:iA,sequence:EA}=s,RA=`conversationID:${E} messageID:${m} reactionID:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:JA,random:ae,time:se,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${JA}_${ae}_${se}`,Reaction:_i,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:iA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,xA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:JA}=kA,ae={GroupId:SA,MsgSeq:JA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:ae},xA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:RA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:RA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=n,{ssoLog:D,helper:M,constants:T}=this._core;try{let P=null;if(P=m.startsWith(T.OuterConstant.CONV_C2C)?yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:JA}=iA,ae={Reaction:RA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${JA}`};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:ae})})}({message:n,reactionID:g,nextSeq:u,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:iA,nextSeq:EA,reactionID:RA,count:kA}=W,{sequence:xA,to:LA}=iA,SA={Reaction:RA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:iA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:iA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return pA(this,void 0,void 0,function*(){const{constants:n}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===n.OuterConstant.CONV_C2C?m=yield function(kA){return pA(this,void 0,void 0,function*(){const{from:xA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,JA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:JA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:xA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:xA,MsgSeqList:LA,Count:SA};return Us.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:iA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(iA),RA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:iA.map(kA=>{const{ReactionList:xA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:xA.map(OA=>{const{Reaction:JA,Count:ae,Reaction_Account:se,ReactedByMe:_i}=OA;return{reactionID:JA,totalUserCount:ae,partialUserList:this._generatePartialUserInfo({userIDList:se,userProfileMap:RA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&n.push(...E.Reaction_Account)})}),n}_getUserProfileList(s){return pA(this,void 0,void 0,function*(){var n;try{const g=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return pA(this,void 0,void 0,function*(){const n=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;n.set(m,{nick:u,avatar:E,userID:m})}),n})}_recordMessageReactedByMe(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,n){const g=`${s}-${n}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:n,reactionID:g,reactionInfo:u}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(bE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:u}=this._core;n.forEach(E=>pA(this,void 0,void 0,function*(){const{C2CMsgInfo:m,GroupMsgInfo:D,MsgReactionSummary:M}=E,{TinyId:T,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},m),D),iA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),RA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,JA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:RA}),ae=OA?xA.Count:0,se=((LA=this._reactionsMap.get(`${iA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:iA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:ae,partialUserList:JA}}),{reactionID:SA,totalUserCount:ae,partialUserList:JA,reactedByMyself:se}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),iA=`${T}-${P}-${W}`,EA=`${iA}-${D}`;if(M===1?this._recordMessageReactedByMe(iA,D):this._removeMyReactionRecord(iA,D),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const RA=this._reactionsMap.get(EA);RA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:iA,reactionList:[RA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(u=>{n.has(u)&&g.push(n.get(u))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,iA=`${M}_${T}_${P}`;return n.set(iA,W),iA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;n.registerApi({apiName:"sendMessageReadReceipt",context:this}),n.registerApi({apiName:"getMessageReadReceiptList",context:this}),n.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return pA(this,void 0,void 0,function*(){var n;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:RA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:RA,To_Account:kA,MsgSeq:xA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),iA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:iA})})}(E):yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Us.core,P={GroupId:D[0].conversationID.replace(T.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return M.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g.ChatError({code:D,message:M,moreMessage:`peerAccount:${(n=E?.[0])===null||n===void 0?void 0:n.conversationID}`})}})}getMessageReadReceiptList(s){return pA(this,void 0,void 0,function*(){const{common:n,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T,constants:P}=Us.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(iA=>({MsgSeq:iA.sequence}))};return T.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=m||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:m}=u;throw new n.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return pA(this,void 0,void 0,function*(){const{constants:n,common:g}=this._core,{message:u,filter:E=kE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:RA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:RA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Us.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:OA})})}({groupID:P,sequence:M,filter:E,cursor:m,count:W});if(iA){const{Cursor:EA,IsFinish:RA,UnreadList:kA,ReadList:xA}=iA,LA={cursor:EA,isCompleted:RA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===kE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===kE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(iA){const{errorCode:EA,errorInfo:RA}=iA;throw new g.ChatError({code:EA,message:RA})}})}_handleC2CMessageReadReceipt(s){const n=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA}=T,EA=`${P}-${W}-${iA}`,RA=_c({conversationID:M,messageID:EA});RA&&!RA.readReceiptInfo.isPeerRead&&(RA.readReceiptInfo.isPeerRead=!0,RA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,u=new Map;n.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:iA,ReadNum:EA,UnreadNum:RA}=T,kA=`${P}-${W}-${iA}`,xA=_c({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};xA&&(typeof EA=="number"&&(xA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof RA=="number"&&(xA.readReceiptInfo.unreadCount=RA,LA.unreadCount=RA),n.push(LA))})}),this._emitReadReceiptEventIfNeed(n)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:n,OuterEvent:g}=this._core;s.length>0&&n.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(n=>{const{from:g}=n;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:n}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===n.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(n=>n.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:n,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function eu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:n}})})}function Pu(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Us.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:n,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),n.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),n.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),iA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield eu(s,W,kl):T===g.CONV_GROUP&&(EA=yield Pu(s,W,kl)),EA){const{resultList:RA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:RA},successLog:{message:`${iA} successCount:${kA} failCount:${xA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:RA,moreMessage:iA})}})}getMessageExtensions(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(n)||(P=Ll,n?.forEach(RA=>{W.push({key:RA,value:"",seq:0})}));const iA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let RA;if(E===u.CONV_C2C?RA=yield eu(s,EA,P):E===u.CONV_GROUP&&(RA=yield Pu(s,EA,P)),RA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,RA);return{code:0,data:{extensions:kA},successLog:{message:`${iA}successCount:${xA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(RA){const{errorCode:kA}=RA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:iA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(n,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:u}=n,E=n.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:iA}=P,{Key:EA,Value:RA,Seq:kA}=iA;m.push({code:W,key:EA,value:RA}),W===0?D++:M++,T.push({key:EA,value:RA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,n){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);n?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{from:W,to:iA,clientSequence:EA,random:RA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:iA,MsgKey:`${EA}_${RA}_${kA}`,StartSeq:T}})}(s,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Us.core,{to:W,sequence:iA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:iA,StartSeq:T}})}(s,n)),E){const{LatestSeq:M,ClearSeq:T,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,T),this._extensionsLatestSequenceMap.set(D,M),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const iA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((RA,kA)=>{const{value:xA}=RA;u(xA)||iA.push({key:kA,value:xA})})}return iA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(hC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:iA}=P,EA=`${m}-${W}-${iA}`;this._extensionsLatestSequenceMap.set(EA,D),E===kl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===Ll?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const pI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Us.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},sl={setMessageExtensions:[pI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[pI],deleteMessageExtensions:[pI]},nl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const n=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return n!==!0?n:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:n,isNumber:g}}=Us.core;return n(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),sl),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class FE{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class ra{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,sequence:u}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class kr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=n;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(n){return pA(this,void 0,void 0,function*(){const g=n.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&n.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var rl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new ra(s),this._c2cMessageAction=new FE(s),this._messageHelper=new kr(s);const{helper:n}=s;n.registerApi({apiName:"deleteMessage",context:this}),n.registerApi({apiName:"revokeMessage",context:this}),n.registerApi({apiName:"resendMessage",context:this}),n.registerApi({apiName:"findMessage",context:this}),n.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return pA(this,void 0,void 0,function*(){let n=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:iA,random:EA,time:RA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${iA}_${EA}_${RA}`:String(iA);n.push(kA)}g.push(D)}}),n.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};n.length>30&&(n=n.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:n}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:n}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:M}}=this._core,{errorCode:T,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:T,message:P,moreMessage:`messageIdentifiers: ${M(n)}`})}})}revokeMessage(s){return pA(this,void 0,void 0,function*(){var n;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,iA=((n=W?.[0])===null||n===void 0?void 0:n.RetCode)||0;if(iA!==0)throw new this._core.helper.ChatError({code:iA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:iA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:iA,moreMessage:P})}})}resendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:u,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=n.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return pA(this,void 0,void 0,function*(){var n;const g=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Ul{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:u,Data:E}=g;return new Ul({index:u,data:E})}constructor(n){this.type=Vr.MSG_FACE;const{index:g,data:u}=n;this.content={index:g,data:u}}validateBeforeSend(){var n,g;return typeof((n=this.content)===null||n===void 0?void 0:n.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(n){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=n;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class OE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new OE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=n;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(n){if(!n||n.length===0)return;const g=n.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(n,g){if(n.length===0)return[];const u=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),n.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const n=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(n.length===0)this.content.binaryData=new Uint8Array(0);else if(n.length===1)this.content.binaryData=n[0];else{const g=n.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of n)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(n){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Ul),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,OE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:n,data:g}=s?.payload||{},u=new Ul({index:n,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:ch,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ao}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new n.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new n.ChatError({functionName:"createForwardMessage",code:2453});const iA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:iA,conversationType:E,isPlaceMessage:0,priority:m,payload:D,needReadReceipt:M,isSupportExtension:W,cloudCustomData:P,receiverList:T});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:n,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:n,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let xu=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:n}=s;n?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:n}}=s;yield this._parseAndEmitC2CRevokedMessages(n)}catch(n){console.debug(n)}})}_parseAndEmitC2CRevokedMessages(s){return pA(this,void 0,void 0,function*(){const n=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:iA,Revoke_Reason:EA}}=m,RA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,xA=this._messageHelper.generateRevokeMessage({conversationID:RA,sequence:T,random:M,revoker:iA,revokeReason:kA});n.push(xA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:n}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return pA(this,void 0,void 0,function*(){const{revokedMessageList:n}=s.result;yield this._parseAndEmitC2CRevokedMessages(n)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleC2CNotifyMessage,this)}},pC=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;n.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(iA=>{const{Random:EA,MsgSeq:RA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:JA=n?.Reason||""}}=iA,ae=SA?`GROUP${SA}`:`GROUP${kA}`,se=this._messageHelper.generateRevokeMessage({conversationID:ae,sequence:RA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:JA});W?(se.revokerInfo.nick=u.From_AccountNick,se.revokerInfo.avatar=u.From_AccountHeadurl,E.push(se)):m.push(se)}),m.length>0&&(yield this._messageHelper.updateRevokerInfo(m),E.push(...m)),E.length!==0&&D.emitOuterEvent(M.MESSAGE_REVOKED,{name:M.MESSAGE_REVOKED,data:E})}catch(n){console.debug(n)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(n,g,this._handleGroupNotifyMessage,this)}};var tu=new class{constructor(){this._c2cMessageReceiver=new xu,this._groupMessageReceiver=new pC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},lh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"translateText",context:this})}translateText(s){return pA(this,void 0,void 0,function*(){try{const{sourceLanguage:n,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return pA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:iA}=m,{store:EA,common:RA}=D,kA={SourceText:P,Source:W,Target:iA,FromAccount:(M=EA.get("login"))===null||M===void 0?void 0:M.tinyID,SDKAppID:(T=EA.get("instance"))===null||T===void 0?void 0:T.sdkAppId},xA=yield RA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(xA){const{CmdErrorCode:LA,TargetText:SA}=xA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Yu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((n=QI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=BI[u]||$I;try{const T=yield function(P){var W;const{store:iA,common:EA}=Us.core,{url:RA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:RA,BytesEngServiceType:xA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=iA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:M});if(T){const{CmdErrorCode:P,BytesResult:W}=T;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(T){const{code:P,message:W}=T||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!QI.test(s))throw new this._core.common.ChatError({code:2119})}};class mI{constructor(n){const{constants:g,common:u,utils:E}=Us.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:iA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:RA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:JA,_elements:ae,time:se}=n;this.ID=M||`${T}-${iA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=se,this.messageSequence=RA,this.clientSequence=SA||RA,this.clientTime=iA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const _i=E.deepCopyWithMethods(ae);_i.forEach(Ti=>{Ti.payload=Ti.content,delete Ti.content}),this.messageBody=_i,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):JA?(this.receiverGroupID=JA,this.messageReceiver=JA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(n=>n.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class al{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>dr(W));return new al({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Us.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(iA=>{if(iA){const EA=new mI(iA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Us.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:iA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(iA)}}}}var mC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:u}}=s;n.messageFactory.registerElementClass(u.MSG_MERGER,al),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new al(s.payload),u=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Us.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let iA,EA=0,RA=0;if(RA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return pA(this,void 0,void 0,function*(){const{payload:{messageList:RA}}=EA,kA={MsgList:Ac(RA)};return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:iA}=D;M=new al(Object.assign(Object.assign({},iA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,n);return M&&T.setElement(s._elements),{code:0,data:{message:T}}}catch(m){const{errorCode:D}=m;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=Do(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(iA){return pA(this,void 0,void 0,function*(){return Us.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:iA}})})}(u),{MsgList:P}=T||{},W=P?.map(iA=>{const EA=dr(iA);return new mI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},M)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),n.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},aa=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return pA(this,void 0,void 0,function*(){const{appStore:n,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:n,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),n.registerApi({apiName:"pinGroupMessage",context:this}),n.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:iA}}=Us.core,{groupID:EA,sequence:RA,isPinned:kA}=P,xA=iA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:RA};return kA?SA.Pinner_Account=xA:SA.UnPinner_Account=xA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:iA}=P||{};throw new E({code:W,message:iA})}})}getPinnedGroupMessageList(s){return pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(u){return pA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Us.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:iA}}=D,{UserId:EA,NickName:RA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===md){LA=!0;const SA=n.parseServerGroupMessage(T);xA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),xA.setElement(SA.elements),xA.pinnerInfo={userID:EA,nick:RA,avatar:kA}}else if(P===LE){const{ClientTime:SA,Random:OA,SenderTinyId:JA,ServerTime:ae,MsgSeq:se}=iA;xA={ID:`${JA}-${SA}-${OA}`,sequence:se,random:OA,time:ae,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:RA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let iA=0;iA{const{sequence:kA}=RA,xA=T.get(kA),LA=iA[xA]||{userID:xA,nick:"",avatar:""};RA.pinnerInfo=LA}),m.sort((RA,kA)=>RA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((n=P[1])===null||n===void 0?void 0:n.data)||[]).forEach(iA=>{const{userID:EA,nick:RA="",avatar:kA=""}=iA;W[EA]={userID:EA,nick:RA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return pA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(n){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var fI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:n,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(lo,this._handleStreamMessageChunkPush,this),n.subscribeOuterEvent(g,this._handleMessageReceived,this),n.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:n,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};n(T)&&n(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var n,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(n=s?._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(n=s._elements)===null||n===void 0?void 0:n[0],M=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:T,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const iA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:RA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:RA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Us.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(iA){const{ErrorCode:EA,ErrorInfo:RA}=iA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=RA,{errorCode:EA,errorMessage:RA}}}catch(T){if(T.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:n}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(n(g)&&g<=3)}_onStreamEnded(s,n,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(n=D._elements)===null||n===void 0?void 0:n[0];if(M&&this._validateExpectedChunk(M,E)){if(E.length>0){const T=E.map(P=>new lg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:iA},ssoLog:EA,channel:RA}=Us.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});RA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",iA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:n,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;n.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,n){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:n}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!RA.includes(EA))return s.url=this._domainName2IP(RA,EA),s.uploadByIP=!0,this.request(s,n);n({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,iA&&EA),SA=this._buildResponse(kA,LA),OA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};n(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,JA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:JA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(` -`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:n}}_getResponseBody(s,n,g){return s.status===200&&n?{location:n,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,n="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(n):M+encodeURIComponent(s[D])}).filter(Boolean).join(n):void 0}_domainName2IP(s,n){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${n}/`)}};const Ju=["unknown","image","video","audio","log"];var yI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,iA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const RA=decodeURIComponent(EA[3]),kA=RA.includes("?")?RA.split("?")[0]:RA||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,JA]=T.split("?sign=");JA&&(W=`${OA}?sign=${encodeURIComponent(JA)}`,LA.sign=decodeURIComponent(JA),LA.signature=decodeURIComponent(JA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},xA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,JA=Do(SA,["name"]);SA=Object.assign(Object.assign({},JA),{fileName:"file",fileType:s.fileType?Ju[s.fileType]:"image"})}return iA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:n})}})),iA.onProgressUpdate&&iA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),iA}_handleResponse(s){const{downloadUrl:n,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function gl(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Lr(s){const n=s||99999999;return Math.round(Math.random()*n)}function Ur(s,n=!0,g=!0){const u=Date.now();return n?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function ar(s,n){return Math.round(Number(s)*10**n)/10**n}function _r(s){return s<=1048576?`${ar(s/1024,1)}KB/s`:`${ar(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Fl="TIMVideoFileElem",ha="RichMediaMessagePlugin",DI=["rich.my-imcloud.com","imrich.qcloud.com"],iu=1,Ba=2,cl=3,xE=255;var ou;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(ou||(ou={}));const YE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var su,Pt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const n=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(n)}removeAuthToUrl(s){return function(n,g){const[u,E]=n.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(YE).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return gl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?n(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:n(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return pA(this,void 0,void 0,function*(){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const n=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=n;return g!=="0"}getFileDNList(){var s;let n=DI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return n;try{JSON.parse(u).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=DI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${u}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),u&&n.indexOf("authKey=")===-1&&function(D,M){let T=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let iA=0;iA-1?`${n}&authKey=${u}`:`${n}?authKey=${u}`),n}getCurrentUserID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.userId}getSDKAppID(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.sdkAppId}getFileDownloadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileDownloadProxy)||""}getFileUploadProxy(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.fileUploadProxy)||""}getAuthKey(){var s,n;return((n=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||n===void 0?void 0:n.authKey)||""}isPrivateNetWork(){var s,n;return(n=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||n===void 0?void 0:n.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:n,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var n;const{isEmpty:g}=(n=this._core)===null||n===void 0?void 0:n.utils;return g(s)}generateURL(s,n){const{needAddAuthToUrl:g=!0}=n||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var n;const{MINI_APP_NAMESPACE:g}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),u()},g.onerror=()=>{n({width:0,height:0}),u()},g.src=s})}},Hu={exports:{}},qu=(su||(su=1,function(s){s.exports=function(n){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],JA=LA[1],ae=LA[2],se=LA[3];JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[0]-680876936|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[1]-389564586|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[2]+606105819|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[3]-1044525330|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[4]-176418897|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[5]+1200080426|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[6]-1473231341|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[7]-45705983|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[8]+1770035416|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[9]-1958414417|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[10]-42063|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[11]-1990404162|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&ae|~JA&se)+SA[12]+1804603682|0)<<7|OA>>>25)+JA|0)&JA|~OA&ae)+SA[13]-40341101|0)<<12|se>>>20)+OA|0)&OA|~se&JA)+SA[14]-1502002290|0)<<17|ae>>>15)+se|0)&se|~ae&OA)+SA[15]+1236535329|0)<<22|JA>>>10)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[1]-165796510|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[6]-1069501632|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[11]+643717713|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[0]-373897302|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[5]-701558691|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[10]+38016083|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[15]-660478335|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[4]-405537848|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[9]+568446438|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[14]-1019803690|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[3]-187363961|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[8]+1163531501|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA&se|ae&~se)+SA[13]-1444681467|0)<<5|OA>>>27)+JA|0)&ae|JA&~ae)+SA[2]-51403784|0)<<9|se>>>23)+OA|0)&JA|OA&~JA)+SA[7]+1735328473|0)<<14|ae>>>18)+se|0)&OA|se&~OA)+SA[12]-1926607734|0)<<20|JA>>>12)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[5]-378558|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[8]-2022574463|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[11]+1839030562|0)<<16|ae>>>16)+se|0)^se^OA)+SA[14]-35309556|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[1]-1530992060|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[4]+1272893353|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[7]-155497632|0)<<16|ae>>>16)+se|0)^se^OA)+SA[10]-1094730640|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[13]+681279174|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[0]-358537222|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[3]-722521979|0)<<16|ae>>>16)+se|0)^se^OA)+SA[6]+76029189|0)<<23|JA>>>9)+ae|0,JA=((JA+=((ae=((ae+=((se=((se+=((OA=((OA+=(JA^ae^se)+SA[9]-640364487|0)<<4|OA>>>28)+JA|0)^JA^ae)+SA[12]-421815835|0)<<11|se>>>21)+OA|0)^OA^JA)+SA[15]+530742520|0)<<16|ae>>>16)+se|0)^se^OA)+SA[2]-995338651|0)<<23|JA>>>9)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[0]-198630844|0)<<6|OA>>>26)+JA|0)|~ae))+SA[7]+1126891415|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[14]-1416354905|0)<<15|ae>>>17)+se|0)|~OA))+SA[5]-57434055|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[12]+1700485571|0)<<6|OA>>>26)+JA|0)|~ae))+SA[3]-1894986606|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[10]-1051523|0)<<15|ae>>>17)+se|0)|~OA))+SA[1]-2054922799|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[8]+1873313359|0)<<6|OA>>>26)+JA|0)|~ae))+SA[15]-30611744|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[6]-1560198380|0)<<15|ae>>>17)+se|0)|~OA))+SA[13]+1309151649|0)<<21|JA>>>11)+ae|0,JA=((JA+=((se=((se+=(JA^((OA=((OA+=(ae^(JA|~se))+SA[4]-145523070|0)<<6|OA>>>26)+JA|0)|~ae))+SA[11]-1120210379|0)<<10|se>>>22)+OA|0)^((ae=((ae+=(OA^(se|~JA))+SA[2]+718787259|0)<<15|ae>>>17)+se|0)|~OA))+SA[9]-343485551|0)<<21|JA>>>11)+ae|0,LA[0]=OA+LA[0]|0,LA[1]=JA+LA[1]|0,LA[2]=ae+LA[2]|0,LA[3]=se+LA[3]|0}function E(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return OA}function m(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return OA}function D(LA){var SA,OA,JA,ae,se,_i,Ti=LA.length,Ft=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Ft,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,JA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ft,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=se,JA[15]=_i,u(Ft,JA),Ft}function M(LA){var SA,OA,JA,ae,se,_i,Ti=LA.length,Ft=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)u(Ft,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(JA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ft,JA),SA=0;SA<16;SA+=1)JA[SA]=0;return ae=(ae=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),se=parseInt(ae[2],16),_i=parseInt(ae[1],16)||0,JA[14]=se,JA[15]=_i,u(Ft,JA),Ft}function T(LA){var SA,OA="";for(SA=0;SA<4;SA+=1)OA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return OA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,OA){return(SA=0|SA||0)<0?Math.max(SA+OA,0):Math.min(SA,OA)}ArrayBuffer.prototype.slice=function(SA,OA){var JA,ae,se,_i,Ti=this.byteLength,Ft=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),Ft>Ni?new ArrayBuffer(0):(JA=Ni-Ft,ae=new ArrayBuffer(JA),se=new Uint8Array(ae),_i=new Uint8Array(this,Ft,JA),se.set(_i),ae)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,JA=this._buff,ae=JA.length,se=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=JA.charCodeAt(SA)<<(SA%4<<3);return this._finish(se,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},xA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},xA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},xA.prototype._finish=function(LA,SA){var OA,JA,ae,se=SA;if(LA[se>>2]|=128<<(se%4<<3),se>55)for(u(this._hash,LA),se=0;se<16;se+=1)LA[se]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),JA=parseInt(OA[2],16),ae=parseInt(OA[1],16)||0,LA[14]=JA,LA[15]=ae,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=RA(this._buff.buffer,LA),JA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=JA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=JA[SA]<<(SA%4<<3);return this._finish(se,ae),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.ArrayBuffer.prototype.getState=function(){var LA=xA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},xA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=iA(LA.buff,!0),xA.prototype.setState.call(this,LA)},xA.ArrayBuffer.prototype.destroy=xA.prototype.destroy,xA.ArrayBuffer.prototype._finish=xA.prototype._finish,xA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},xA}()}(Hu)),Hu.exports),fC=aI(qu),q=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var n;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?yI:Vu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${ha} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),iA=`size:${W} time:${P}ms speed:${_r(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${iA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${u(m)}`),m}})}_handleUploadError(s,n){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,n){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:n.data.location||"",uploadTime:Ur(Date.now(),!1),uploadSpeed:_r(1e3*s.size/Ur(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,existFlag:EA}=m,RA=!Pt.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:iA,uploadIP:RA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(m){throw console.error("Failed to create COS pre-signed URL options:",m),m}})}_prepareUploadParams(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Pt.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),iA=`${Lr(999999)}${W}`,EA=T?E.name:iA,RA=yield this._generateHashFileName(E);return{fileName:u(RA)?Ig(EA):`${RA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return pA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:n,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),n&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(n.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new fC.ArrayBuffer,iA=new FileReader,EA=setTimeout(()=>{iA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function RA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;iA.readAsArrayBuffer(D.call(s,kA,xA))}iA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},RA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof n?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{n.getFileSystemManager().getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_generateFileNameInUNINativeApp(s){return pA(this,void 0,void 0,function*(){var n;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((n=plus==null?void 0:plus.io)===null||n===void 0?void 0:n.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),m;try{m=yield new Promise((D,M)=>{plus.io.getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_handleUploadProgress(s,n){if(typeof n.onProgress=="function")try{n.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core,u=Pt.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return pA(this,void 0,void 0,function*(){try{const{helper:iA,channel:EA}=W,RA=iA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${RA.head.seq}${T}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(iA){throw console.warn("getCosSig error:",iA),iA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var n;const g=Pt.isSimpleCos(),u=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:iA,uint32_file_id:EA,uint32_exist_flag:RA,str_download_url:kA,str_upload_url:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:iA,fileID:EA,existFlag:RA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Pt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Pt.getPlatform(),uint32_sdkappid:Pt.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return pA(this,void 0,void 0,function*(){return new Promise((n,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,u;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Pt.getFileUploadProxy();let g=s;return n&&(g=s.replace(/^https:\/\/[^/]+/,n)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const L=2108,oA=2251,b=2252,x=2253,tA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},wA=1,XA=2;class pe{constructor(n,g){this.instanceID=Lr(9999999),this.sizeType=n.type||0,this.type=0,this.size=n.size||0,this.width=n.width||0,this.height=n.height||0,this.imageUrl=Pt.addAuthToUrl(n.imageUrl||n.url||""),this.url=Pt.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Pt.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:n,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=n,M.width=m,M.height=D;else{D<=m?(M.width=Math.ceil(m*E/D),M.height=E):(M.width=E,M.height=Math.ceil(D*E/m));const T=n&&n.indexOf("?")>-1?`${n}&`:`${n}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(n===void 0){const{url:T}=M;return Do(M,["url"])}return M}class B{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=Pt.getPlatformFlags();return n&&((u||E)&&(g=n.url),m&&(g=window.URL.createObjectURL(n))),g}initImageInfoArray(n=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=n[u]||Object.assign({},g),m=new pe(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(n){this._percent=Math.min(n,1)}updateImageFormat(n){this.content.imageFormat=uA[n.toUpperCase()]||uA.UNKNOWN}addImageInfo(n){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(n)}updateImageInfoArray(n){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Pt.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[iu]:"i",[cl]:"a",[Ba]:"v",[xE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((n=g.get("cloudConfig"))===null||n===void 0?void 0:n.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[N[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var rA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,u;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Pt.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:iA,largeImageHeight:EA,largeImageUrl:RA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:JA,thumbFileSize:ae,thumbImageWidth:se,thumbImageHeight:_i,thumbImageUrl:Ti}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(OA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Ft=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:iA,height:EA,imageUrl:RA,url:RA},{instanceID:JA,size:ae,width:se,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(Ft),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(u);return n.updateImageFormat(u?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:iu,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield q.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:n,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:iA}=s,EA=Pt.addAuthToUrl(n),RA={size:g,url:EA,width:u,height:E};return iA?.length>0?this._processImageInfoArray(iA,g):m&&T?[Object.assign({},RA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},RA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,n,g,u){return p({originUrl:s,originWidth:n,originHeight:g,min:u})}_processImageInfoArray(s,n){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(u,n,"large")),Pt.isSimpleCos()&&!Pt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,n),n?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,n))}return n}catch(g){throw g}})}_extractDomainFromUrl(s){var n;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(n=this._core)===null||n===void 0||n.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,n,g){return pA(this,void 0,void 0,function*(){var u;try{const E=Pt.addAuthToUrl(s),{width:m=0,height:D=0}=yield Pt.probeImageWidthHeight(E);n.width=m,n.height=D,g==="thumb"?(n.smallImageUrl=s,n.smallImageWidth=m,n.smallImageHeight=D):(n.largeImageUrl=s,n.largeImageWidth=m,n.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper;if(!s)throw new g({code:oA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var n;try{const{IN_MINI_APP:g}=(n=this._core)===null||n===void 0?void 0:n.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){gl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const n=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:n,name:n.slice(n.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:n.slice(n.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var n;const{ChatError:g}=(n=this._core)===null||n===void 0?void 0:n.helper,u=Pt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${ha} getDownloadIP domainName: ${s}`;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){try{const{helper:M,channel:T}=D,P="im_cos_msg.get_final_ip",W={str_domain:m},iA=M.generateProtocolData({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=n.location.split("/");E[0]=u.str_final_ip,n.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return pA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return n.imageInfoArray=this._processImageInfoResponse(g),n}catch(g){throw n.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:n}=s;return n.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:n,helper:g}=this._core;let u="";if(n.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),tA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:b})}_checkImageSize(s){const{utils:n,helper:g,store:u}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(iu)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=XA,s[2].type=wA}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,VA=2402,ee="2.5.0",Ee="1.18.0";function We(s,n){const g=s.split("."),u=n.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Pt.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(n){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(n.fileName&&n.fileSize)return{size:n.fileSize,name:n.fileName};const{file:u}=n;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(n){if(n.path&&n.path.includes(".")){const g=n.path.slice(n.path.lastIndexOf(".")+1).toLowerCase();n.type=g,n.name||(n.name=`${Lr(999999)}.${g}`)}n.name||(n.type="",n.name=n.path.slice(n.path.lastIndexOf("/")+1).toLowerCase()),n.suffix&&(n.type=n.suffix),n.url||(n.url=n.path)}}ot=Jr;var Ut=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Pt.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:T,uuid:P,fileSize:W,fileName:iA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),RA=new at({url:T,uuid:P,file:{size:W,name:iA},isCustomUpload:!0});return EA.setElement(RA),EA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{file:n}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(n);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,n),E=Pt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(xE)||104857600;if(s.size>g)throw new n({code:VA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:xE,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processFile(s){var n,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(n=this._core)===null||n===void 0?void 0:n.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=Pt.extractFileFromInput(s);if(!P)throw new T({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(m||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,n;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(n=this._core)===null||n===void 0?void 0:n.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&We(T,ee)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ee} or higher`});if(m&&We(T,Ee)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${Ee} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Jt=2108,Ui=2351,go=2352,Xi=["mp4","quicktime","mov","video"];var Ei;class Po{constructor(n){this.type=Fl,this.uploadProgress=0,this[Ei]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[Jr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Pt.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Pt.addAuthToUrl(n.videoUrl),videoDownloadFlag:2,videoUUID:n.videoUUID,thumbUUID:n.thumbUUID,thumbFormat:n.thumbFormat,thumbWidth:n.thumbWidth,snapshotWidth:n.thumbWidth,thumbHeight:n.thumbHeight,snapshotHeight:n.thumbHeight,thumbSize:n.thumbSize,snapshotSize:n.thumbSize,thumbDownloadFlag:2,thumbUrl:Pt.addAuthToUrl(n.thumbUrl),snapshotUrl:Pt.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:iA,SnapshotWidth:EA,ThumbHeight:RA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:JA}=g;return new Po({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:iA,snapshotWidth:EA,thumbHeight:RA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:JA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=n;Pt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Pt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),Pt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteVideoUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:iA,thumbWidth:EA,snapshotWidth:RA,thumbHeight:kA,snapshotHeight:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:JA,snapshotUrl:ae}=u;return{MsgType:this.type,MsgContent:{VideoUrl:Pt.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:iA,ThumbWidth:EA,SnapshotWidth:RA,ThumbHeight:kA,SnapshotHeight:xA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:Pt.removeAuthToUrl(JA),SnapshotUrl:Pt.removeAuthToUrl(ae)}}}}Ei=Jr;var es,pi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fl,Po),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:ar(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Pt.generateUUID(E.videoFile),thumbUUID:Pt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Po(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:iA,videoFileSize:EA,videoType:RA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),JA=new Po({videoFormat:RA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:iA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(JA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const n=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=u,D=Pt.addAuthToUrl(E);return n.updateVideoUrl(D),Pt.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ba)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:Jt});if(Xi.indexOf(s.videoFile.type)===-1)throw new n({code:go})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:Ba,file:g,to:u,message:n,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(n.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield q.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var n,g;try{const{ChatError:u}=(n=this._core)===null||n===void 0?void 0:n.helper,{IN_MINI_APP:E,IN_BROWSER:m}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,M={};if(E&&(M=this._processMiniVideoFile(D),D.name=M.name,D.url=M.url,D.type=M.type),m){const T=Pt.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ha} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(gl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:n,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Pt.getPlatform(),cover_name:Ig(Lr(99999)),snapshot_url:s},u=yield function(T,P){return pA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:iA,channel:EA}=P,RA=iA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${RA.head.seq}${W}`;return yield EA.sendPacket(RA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(n.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Pt.isEmpty(E))return{};const m=Pt.addAuthToUrl(E),{width:D=0,height:M=0}=yield Pt.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};class ji{constructor(n){this.uploadProgress=0,this.type=Fg,this[es]=!1,this[Jr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Pt.generateURL(n.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:Pt.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new ji({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateAudioUrl(n){this.content.remoteAudioUrl=n}validateBeforeSend(){if(this[Jr])return{isValid:!0};const n=this.content.remoteAudioUrl!=="";return{isValid:n,error:n?null:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:Pt.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}es=Jr;const Ws=2108,_e=2300,_t=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Fg,ji),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:Pt.generateUUID(E)},T=new ji(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var n,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(n=E.get("login"))===null||n===void 0?void 0:n.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},iA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new ji({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return iA.setElement(EA),this._messageOptionsMap.set(iA.clientSequence,s),iA}catch(E){throw E}}upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${ha} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=Pt.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:n},store:g}=this._core;if(!s)throw new n({code:_e});const u=X(cl)||20971520;if(s.size>u)throw new n({code:_t});if(s.size===0)throw new n({code:Ws})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:u}=n,E={uploadFileType:cl,file:g,to:u,message:n,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(n.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield q.uploadToCOS(E);return m})}_processAudioFile(s){var n;const{IN_MINI_APP:g,IN_BROWSER:u}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const n=URL.createObjectURL(s);return s.tempFilePath=n,s}_validateCustomUploadOptions(s){var n;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Xt={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},En={createImageMessage:Xt,createAudioMessage:Xt,createVideoMessage:Xt,createFileMessage:Xt},Ai={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:rA,[Ya]:Ut,[Fl]:pi,[Fg]:FA};var vi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:n,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Ut.init(s),pi.init(s),FA.init(s),q.init(s),Pt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Ai,params:En})}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)}catch(m){throw m}})}_upload(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(n.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),n.info("_upload",` type:${s.type}`))}catch(u){throw s.status=ou.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var n,g;return((g=(n=s._elements)===null||n===void 0?void 0:n[0])===null||g===void 0?void 0:g[Jr])===!0}};const ho=new class{init(s){this.core=s}};class ht{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=ho.core.common.buildLastMessage(n.lastMessage),this.peerReadTime=n.peerReadTime||0,this.groupAtInfoList=[],this.remark=n.remark||"",this.isPinned=n.isPinned||!1,this.messageRemindType=n.messageRemindType,this.markList=n.markList||[],this.customData=n.customData||"",this.conversationGroupList=n.conversationGroupList||[],this.draftText=n.draftText||"",this.userProfile=n.userProfile,this.groupProfile=n.groupProfile,this.subType=n.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var n;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=ho;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((n=this.groupProfile)===null||n===void 0)&&n.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=ho,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=ho.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=ho,{sequence:u,time:E}=n;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(n){this.lastMessage.isRevoked=n}setLastMessageRevoker(n){this.lastMessage.revoker=n}setDraftText(n){this.draftText=n}updateGroupAtInfoList(n){const{core:{common:{updateGroupAtInfo:g}}}=ho;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Qt=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,3)===n.CONV_C2C},ug=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s.slice(0,5)===n.CONV_GROUP},ks=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=ho;return g(s)&&s===n.CONV_SYSTEM};function Wi(s){const{OuterConstant:n}=ho.core;let g="";return s===0?g=n.MSG_REMIND_ACPT_AND_NOTE:s===1?g=n.MSG_REMIND_DISCARD:s===2?g=n.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=n.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:n}=ho.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,n){const{helper:g}=ho.core,u=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,u),u}var is,ga;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(is||(is={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ga||(ga={}));var Qa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Qa||(Qa={}));const ea=0,H=1;var BA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){try{const{common:n}=this._core,g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:M}=E,T={To_Account:D,Peer_Account:M};return m.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:T})})}({toAccount:n.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=Wi(D);NA.patchMessageRemindType([M],T)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return pA(this,void 0,void 0,function*(){if(s.length!==0)try{const n=yield function(u,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=n||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(n){console.error(`${this._name}.get fail:`,n)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:n,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:iA,CONVERSATION_UPDATED:EA,LOGOUT:RA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),n.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),n.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(T,this._handleNewMessage,this),g.subscribeInnerEvent(M,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(iA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,xA,this._handleMessageRead,this),g.subscribeInnerEvent(RA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:n}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[n.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var n;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:n=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(n.length===0)return;const{common:{isTopic:m}}=this._core;m(n[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:n,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),n.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:n=[]}=s;n.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:n,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:n,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${n.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),M.updateLastMessage(D),T=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),T&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,M.lastMessage))}_handleMessageRevoked(s){const{messageList:n=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${n.length}`),n.length===0)return;let u=null,E=!1;n.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(n(D))return;const{lastMessage:M}=D;if(M){const T=m?.[0]||{};M.lastTime===T.time&&M.lastSequence===T.sequence&&M.version!==T.version&&(M.type=T.type,M.payload=T.payload,M.messageForShow=g(T.type,T.payload),M.cloudCustomData=T.cloudCustomData,M.version=T.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:n}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),n||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:n}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const n=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");n.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),n.length>0&&this._updateC2CConversation(n),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var n;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(n=E.userProfile)===null||n===void 0||n.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(M=>{var T;const{userID:P}=M,W=this.getLocalConversation(`${g}${P}`);if(W){const iA=((T=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=iA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),BA.get(s)}_updateGroupConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>pA(this,void 0,void 0,function*(){const T=g.getGroup(M),P=this.getLocalConversation(`${n}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${n}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:n,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=n.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),n.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var n,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,n===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var n,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(n=E?.syncConversationHandler)===null||n===void 0?void 0:n.isSyncCompleted)===null||g===void 0?void 0:g.call(n)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const n=this.getTotalUnreadMessageCount();this._totalUnreadCount!==n&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${n}`),this._totalUnreadCount=n,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:n}))}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:n}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,n){return this._conversationStore.getConversationMap().set(s,n)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[n,g]of s)this.setLocalConversation(n,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,n){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==n&&(E.messageRemindType=n,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${n} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:n}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=n?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const n=[...this._conversationStore.getConversationMap().entries()],g=n.findIndex(u=>u[1].isPinned===!1);n.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(n),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:n,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(n,this._handleNewMessage,this),s.unSubscribeInnerEvent(n,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},zA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return pA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:n,isArray:g,isPlainObject:u}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,n){const{OuterConstant:g}=this._core;return n!==g.CONV_C2C&&n!==g.CONV_GROUP||s.type===n}_filterGroupName(s,n){const{utils:{isString:g}}=this._core;return!g(n)||(n===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(n))}_filterMarkType(s,n){const{utils:{isNumber:g}}=this._core;return!g(n)||(n===0?s.markList.length===0:s.markList.includes(n))}_filterUnreadCount(s,n){let g=!0;return n===!0?g=s.unreadCount>=1:n===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,n){let g=!0;return n===!0?g=s.groupAtInfoList.length>=1:n===!1&&(g=s.groupAtInfoList.length===0),g}},we=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(ks(s))return D.data.conversation=M,D;let T=!1;const P=Qt(s)?n:g;if(m(M)&&(T=!0,M=new ht({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===n){const W=s.replace(n,"");yield this._handleC2CConversation(M,W),T&&(yield BA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[n]});if(W?.data.length===0)throw new m.ChatError({code:Qa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const iA=(u=T.getFriend(n))===null||u===void 0?void 0:u.remark;D(iA)||s.remark===iA||(s.remark=iA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?M.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,n){return pA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:n});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},le=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},Ne=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;n.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),n.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!n(E)){const{UinPairReadArray:m=[]}=E;m.forEach(D=>{const{From_Account:M,LastReadTime:T}=D,P=`${g.CONV_C2C}${M}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${T}`),NA.markMessageAsRead({conversationID:P,lastReadTime:T}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:n,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${n.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${T} lastReadSequence:${M}`),NA.markMessageAsRead({conversationID:T,lastReadSequence:M}),NA.updateUnreadCount(T),this._clearGroupAtInfoList(T)})})}setMessageRead(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(n=this._core)===null||n===void 0?void 0:n.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:iA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:iA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return pA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:n},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ea&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return pA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return ho.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:n,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(n),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===n){const P=this._getLocalMessageMaxTime(T);NA.markMessageAsRead({conversationID:M,lastReadTime:P})}else if(T.type===g){const P=M.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:M,lastReadSequence:W})}}NA.updateUnreadCount(M,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ea,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,M]of D){const{type:T,unreadCount:P}=M;if(this._shouldSetAllMessageRead({scope:s,type:T,unreadCount:P})){if(T===n&&m.allC2CMessageReadStatus===ea){if(m.allC2CMessageReadStatus=H,s===u)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:iA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:iA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:n}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;n(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return pA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const n=NA.getLocalConversation(s);if(!n)return;const g=n?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(this,void 0,void 0,function*(){const{messageListToDelete:iA}=P,EA={DelMsgList:iA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:T},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,n=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${n}`)),n&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var n;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((n=s?.lastMessage)===null||n===void 0?void 0:n.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:n,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${n}`),NA.markMessageAsRead({conversationID:s,lastReadTime:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,n){return pA(this,void 0,void 0,function*(){try{yield function(g,u){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:n},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${n}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:n}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:n,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ge=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,n){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${n}`),n&&!P.isPinned&&(P.isPinned=!0,E=!0),!n&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(ks(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Qt(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:RA,operationType:kA,itemList:xA}=iA,LA={From_Account:RA,OperationType:kA,RecentContactItem:xA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:m===!0?1:2,itemList:[P]},this._core)){if(M)M.isPinned!==m&&(M.isPinned=m);else{const iA=new ht({conversationID:E,type:Qt(E)?n.CONV_C2C:n.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,iA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:iA}=P;throw new u({functionName:"pinConversation",code:W,message:iA,moreMessage:T})}})}},Ue=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:n}}=this._core;if(!n(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return pA(this,void 0,void 0,function*(){const{utils:{isString:n}}=this._core;if(n(s))return this._deleteConversation({conversationIDList:[s],flag:ga.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return pA(this,void 0,void 0,function*(){const{conversationIDList:n,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${n} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(n),this._deleteConversationFromServer(n,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});return{code:0,data:u===ga.ONLY_CONVERSATIONID?{conversationID:M[0]}:{conversationIDList:M},successLog:{message:m}}}catch(D){const{errorCode:M,errorInfo:T}=D;throw new E({code:M,message:T,moreMessage:m})}})}_deleteConversationFromLocal(s){const{OuterConstant:n}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==n.CONV_GROUP||this._hasLocalGroup(g)?E===n.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:n?1:0};if(s.forEach(D=>{var M;if(NA.hasLocalConversation(D)){const T=((M=NA.getLocalConversation(D))===null||M===void 0?void 0:M.type)||"",P=D.replace(T,"");T===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):T===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const m=yield function(D,M){return pA(this,void 0,void 0,function*(){const{fromAccount:T,conversationList:P,clearHistoryMessage:W}=D,iA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:iA})})}(E,this._core);if(m){const{ResultItem:D=[]}=m,M=[];return D.length>0&&D.forEach(T=>{if(T.ResultCode===0){const P=T.Type===1?`${g.CONV_C2C}${T.To_Account}`:`${g.CONV_GROUP}${T.ToGroupid}`;M.push(P)}}),this._deleteLocalConversationList(M),M}return[]})}_deleteLocalConversationList(s){let n=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),n=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${n}`),n&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,n=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),n&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:n},appStore:{groupStore:g}}=this._core,u=s.replace(n,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},vt=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return pA(this,void 0,void 0,function*(){const{conversationID:n,draftText:g}=s;if(console.log(`${this._name} conversationID:${n} draftText:${g}`),!NA.hasLocalConversation(n))throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});const u=NA.getLocalConversation(n);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},Wt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:iA}=ho.core.OuterConstant;return{[P]:0,[W]:1,[iA]:2}}()[n],u=yield function(P,W){return pA(this,void 0,void 0,function*(){const{userIDList:iA,receiveMessageOption:EA}=P,RA={Peer_Account:iA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:RA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:iA}=P;m.push({userID:W,code:iA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],M=[],{OuterConstant:T}=this._core;return s.forEach(P=>{M.push(`${T.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(M,n),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},ci=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,n){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,userID:T,receiveMessageOption:P}=m,W={GroupId:M,Member_Account:T,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:n},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},Dt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:n},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!n(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=Wi(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return pA(this,void 0,void 0,function*(){const n="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${n} groupID:${g} messageRemindType:${E}`),yield ci.set(g,E);if(!D(u))return M.debug(`${this._name}.${n} userIDList:${u} messageRemindType:${E}`),yield Wt.set(u,E);throw new m.ChatError({functionName:n,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},Bi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),we.init(s),le.init(s),Ne.init(s),ge.init(s),Ue.init(s),vt.init(s),Dt.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=n;n.subscribeInnerEvent(g,E,this._onConversationModified,this),n.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),n.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),n.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),n.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===n.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Ue.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ge.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ge.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Ne.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;Dt.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Ne.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,u,this._onConversationModified,this),s.unSubscribeInnerEvent(n,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(n,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(n,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},eo=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:n}}=this._core,{messageRemindType:g=n,isRepeated:u=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return pA(this,void 0,void 0,function*(){const{common:T}=ho.core,{startTime:P,endTime:W,isRepeated:iA,messageRemindType:EA}=M,RA={StartTime:P,EndTime:W,IsRepeated:iA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:RA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:u?is.ON:is.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){oc("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:n}=this._core;return{[n.MSG_REMIND_ACPT_AND_NOTE]:0,[n.MSG_REMIND_DISCARD]:1,[n.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:u}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const n=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:n})}getAllReceiveMessageOpt(){return pA(this,void 0,void 0,function*(){try{const s=yield function(){return pA(this,void 0,void 0,function*(){const{common:n}=ho.core,g={To_Account:n.getCurrentUserID()};return n.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){oc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===is.ON}}},Uo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Wt.init(s),ci.init(s),BA.init(s),yA.init(s),eo.init(s),Is.init(s)}};const si=s=>!Qt(s)&&!ug(s)&&!ks(s),Fr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!si(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:n,isObject:g,isString:u}}}=ho;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&si(s))return"conversationID is invalid.";if(g(s)){if(!n(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(si(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!Qt(s)&&!ug(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Zo={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var jn=new class{constructor(){this.name="Conversation"}install(s){ho.init(s),Bi.init(s),Uo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Fr})}};const Wn=new class{init(s){this.core=s}},ta="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",Ku="Set",mm="Increase",Ri="Decrease",ni=0,yo=1,on=2,os=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Eg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ol=["Role","JoinTime","MsgFlag","MsgSeq"],fd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Mr=1,SI="notStart",nu="resolved",Og="rejected",ru=10018,MI=11e3,Uc=2,ju=["Owner","Admin","Member"],fm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],ym=0,Dm=1,Sm=2,cD=4,lD=1,Fv=2,ID=3,uD=4,Ov=5,BT=1,yd=0,QT=4,ED=6,pT=400,dD=300,mT={from:!0,groupID:!0,groupName:!0,to:!0},Pv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},fT=2,xv=4,yT=5,DT=7,CD=8,hD=15,TQ=20,Mm=21,vm=2600,Dd=2602,ST=2603,MT=2620,Rm=2621,BD=2623,Ih=2660,vT=2661,RT=2681,wm=2683,Yv=2684,QD=2685,_m=2687,Vv=3122,wT=10018,_T={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Jv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Sd=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,Tm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let u=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Md=s=>{const n=[];if(!s)return n;for(let g=0,u=s.length;g{const n=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(n){this.selfInfo.nameCard=n}}var Yi=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:n}}=s;this._groupMap=n.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:n}}=this._core;let g;s.forEach(E=>{var m;g=E.groupID,this.hasLocalGroup(g)?(m=this.getLocalGroup(g))===null||m===void 0||m.updateGroup(E):(this._groupMap.set(g,new Wu(E)),this._clearGroupLocalMessage(g))});const u=n();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:n}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==n})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:n},notificationCenter:g}=this._core;g.emitOuterEvent(n,{name:n,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=n.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Gm(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,n){return{code:0,data:s||{},successLog:n}};var Hv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=SI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return pA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Yi.updateLocalGroup(g),Yi.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Og||this._pagingStatus===SI)return this._syncGroupList().then(()=>{const g=Yi.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const n=Yi.getLocalGroupList();return dn({groupList:n,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${n.length}`})})}_syncGroupList(){return pA(this,void 0,void 0,function*(){this._pagingStatus===SI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=nu,this._groupListTreeShaking(n),Yi.updateLocalGroup(n);const g=Yi.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Yi.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...os];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Gm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},iA=this._convertGroupKey(P);u.push(...iA);const EA=D+m,RA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${RA} current:${u.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?RA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):RA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===ru)return n.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===MI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Gm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...os],SelfInfoFilter:[...Ol]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const iA=D+m,EA=!(P>iA),RA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${RA}`),EA?E:(D=iA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===wT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const n=new Map([...Yi.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},zu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"createGroup",context:this})}createGroup(s){return pA(this,void 0,void 0,function*(){var n;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{name:RA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:JA,joinOption:ae,inviteOption:se,memberList:_i,groupCustomField:Ti,isSupportTopic:Ft}=iA;let Ni,cs;_i&&(Ni=_i.map(mt=>{const{userID:UA,memberCustomField:ri}=mt;return{Member_Account:UA,AppMemberDefinedData:ri?VE(ri):void 0}})),Ti&&(cs=VE(Ti));const Se={Name:RA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:JA,ApplyJoinOption:ae,InviteJoinOption:se,MemberList:Ni,AppDefinedData:cs,SupportTopic:Ft,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Se})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(iA=>T.includes(iA.userID))),s.type===m)return dn({group:new Wu(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Yi.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Yi.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Yi.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:iA}=Wn.core.OuterConstant;return[M,T,P,W,iA]})().includes(n))throw new this._core.helper.ChatError({code:vm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(n)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(n)||E(s.joinOption)||(s.joinOption=void 0),m({type:n})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Sd(s)}_canIUseJoinOption(s){return Jv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:n}=s;return n===!0}_notNeedSendCustomMessage(s){const{type:n,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return n===u||n===E&&g===1}_sendCustomMessage(s,n){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),iA=Lc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),iA=Mr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:iA,opUser:this._core.store.get("login").userId,version:4})}},RA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(RA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:n,constants:g}=s;n.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:n}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${n} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:n,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(n))}initGroupAttributesCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupAttributesCache.set(n,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${n} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:n,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==Ov&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(n,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:n,groupAttributeList:g=[],operation:u}=s;u!==ID?u!==uD?(u===lD&&n.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;n.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{n.values.delete(E.key)}):n.values.clear()}getGroupAttributesCacheValues(s){var n;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((n=m.get(D))===null||n===void 0?void 0:n.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var n,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(n=this._core)===null||n===void 0?void 0:n.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:m,updatedKeyList:M,deletedKeyList:T}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:m,updatedKeyList:M,deletedKeyList:T}})))}_computeValuesChangedData(s){const{utils:{isUndefined:n}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var n;(n=this._core)===null||n===void 0||n.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const n=[];return Object.keys(s).forEach(g=>{n.push({key:g,value:s[g]})}),n}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},Eh=new class{constructor(){this._name="DismissGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:u,message:E})}})}},Pl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupCustomFieldFilter:g}=s,u={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...os],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...fd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Sd(D[0].type)?T=new Wu(D[0]):(Yi.updateLocalGroup(D),T=Yi.getLocalGroup(n)),T.isSupportTopic||Yi.updateConversationGroupProfile(n),dn({group:T},{message:`groupID:${n}`})}catch(m){const{code:D,message:M}=m;throw new E({functionName:"getGroupProfile",code:D,message:M})}})}getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{groupIDList:n}=s,{common:{isCommunity:g}}=this._core,u=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=Do(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:RA}=W,kA={GroupIdList:EA,ResponseFilter:RA};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=m||{},M=this._convertGroupProfileKey(D),T=M.filter(W=>g(W.errorCode)||W.errorCode===0),P=M.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return n.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:n,avChatRoomKey:g}=s;this._groupCountersMap.set(n,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,n){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(n)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(n);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},JE=new class{constructor(){this._name="JoinGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Pl.getGroupProfile({groupID:n}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${n} was unjoined, start to join!`),Yi.deleteLocalGroup(n),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g({functionName:"joinGroup",code:D,message:M,moreMessage:`groupID:${n}`})}})}_applyJoinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:JA,applyMessage:ae,historyMessageFlag:se}=SA,_i={GroupId:JA,ApplyMsg:ae,HugeGroupHistoryMsgFlag:se};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:iA,HugeGroupFlag:EA,AVChatRoomKey:RA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${iA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new Wu({groupID:E,type:T});if(P===n.JOIN_STATUS_WAIT_APPROVAL)return dn({status:n.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===n.JOIN_STATUS_SUCCESS){try{LA=(yield Pl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:iA,avChatRoomKey:RA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:Ih})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:u}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},NQ=new class{constructor(){this._name="QuitGroup"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:BD});const{helper:{ChatError:n}}=this._core;try{yield function(u,E){return pA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Yi.getLocalGroup(s);return Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},cB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return pA(this,void 0,void 0,function*(){try{const n=yield function(OA,JA){return pA(this,void 0,void 0,function*(){const ae={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return JA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:ae})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:iA,Owner_Account:EA,Type:RA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Md(u),SA=new Wu({groupID:s,name:iA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:RA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(n){const{errorCode:g,errorInfo:u}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},TT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Yi.getLocalGroup(n);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${n} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:iA,introduction:EA,notification:RA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:iA,Introduction:EA,Notification:RA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?VE(SA):void 0};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:OA})})}(s,this._core),D?(D.updateGroup(s),Yi.emitGroupListUpdate()):D=new Wu(s),dn({group:D},{message:`groupID:${n}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return Jv(s)||this._core.common.isCommunity({type:s})}},NT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return pA(this,void 0,void 0,function*(){const n="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Yi.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:n,code:MT});if(u===M())throw new m.ChatError({functionName:n,code:Rm});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:iA}=T,EA={GroupId:W,NewOwner_Account:iA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},GQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="getGroupOnlineMemberCount";if(!Yi.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return pA(this,void 0,void 0,function*(){const T={GroupId:D};return M.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:T})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${n} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo})}})}},bQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),Hv.init(s),zu.init(s),Eh.init(s,n),JE.init(s,n),NQ.init(s,n),cB.init(s),Pl.init(s),TT.init(s),NT.init(s),GQ.init(s,n)}dismissGroup(s){return Eh.dismissGroup(s)}joinGroup(s){return JE.joinGroup(s)}quitGroup(s){return NQ.quitGroup(s)}getGroupOnlineMemberCount(s){return GQ.getGroupOnlineMemberCount(s)}},qv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return pA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const n=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...n[0],...n[1]]);return dn({applicationList:g})}catch(n){throw new this._core.helper.ChatError({functionName:s,code:n?.errorCode,message:n?.errorInfo})}})}_getGroupApplicationList(s){return pA(this,void 0,void 0,function*(){const{type:n,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:iA,startTime:EA,limit:RA,handleAccount:kA}=P,xA={Type:iA,StartTime:EA,Limit:RA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:n,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const n=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=Do(u,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:n,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},Kv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return pA(this,void 0,void 0,function*(){const{application:n}=s,g=this._handleParams(s);try{n?.applicationType===Uc?yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,m){return pA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,messageKey:iA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:iA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Yi.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:iA}=E||{};D=iA.operatorID,M=(n=iA.groupProfile)===null||n===void 0?void 0:n.groupID,T=iA.authentication,P=iA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},pD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),qv.init(s),Kv.init(s)}};let DC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:n},common:{deepMerge:g}}}=Wn;n(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),n(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&Tm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function lB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=VE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var mD=new class{constructor(){this._name="GetGroupMemberList"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:ju.includes(m)?[m]:void 0,memberInfoFilter:fm};try{const W=yield function(se,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:Ft,offset:Ni,limit:cs,memberRoleFilter:Se,memberInfoFilter:mt}=se,UA={GroupId:Ft,Limit:cs,MemberRoleFilter:Se,MemberInfoFilter:mt};return Ti({groupID:Ft})?UA.Next=String(Ni):UA.Offset=Ni,_i.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:UA})})}(P,this._core),{MemberList:iA,MemberNum:EA,Next:RA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${RA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(iA)||iA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(RA)?0:RA),iA.lengthD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:JA}=kA,ae={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:JA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:ae})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...fm]},this._core),{MemberList:iA}=W||{};if(!M(iA)||iA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(iA);EA=yield this._getMemberAvatarAndNick(EA);const RA=this._generateGroupMember(EA);return dn({memberList:RA},{message:P})}catch(W){throw new D.ChatError({functionName:n,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const n=[];for(let g=0,u=s.length;gD.userID),u=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const n=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(RA,kA){return pA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=RA,SA={GroupId:xA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:T=[]}=M||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:iA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${iA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===ym?n.push(M):D===Dm?g.push(M):D===Sm?u.push(M):D===cD&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},Rd=new class{constructor(){this._name="DeleteGroupMember"}init(s,n){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!n.getInstalledSubPlugins().includes(ta)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:ST});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,reason:EA}=T,RA={GroupId:W,MemberToDel_Account:iA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:RA})})}({groupID:g,userIDList:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},jv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return pA(this,void 0,void 0,function*(){const{helper:n}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield lB(s,this._core);const D=Yi.getLocalGroup(g),M=new DC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new n.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:n}=s,{store:g,helper:u}=this._core;if(n===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:QD})}},LQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield lB(s,this._core);const M=Yi.getLocalGroup(u),T=new DC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var n;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Yi.getLocalGroup(g);if(((n=P?.selfInfo)===null||n===void 0?void 0:n.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:RT});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Yv});const W=[...ju];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:wm})}},fD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return pA(this,void 0,void 0,function*(){var n;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield lB({groupID:m,userID:D,nameCard:M},this._core);const W=Yi.getLocalGroup(m);D===((n=W?.selfInfo)===null||n===void 0?void 0:n.userID)&&(W.updateSelfInfo({nameCard:M}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m));const iA=new DC({userID:D,nameCard:M});return dn({group:W,member:iA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:_m})}},bm=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return pA(this,void 0,void 0,function*(){const n="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield lB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new DC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:n}=s,{helper:g}=this._core,u=Yi.getLocalGroup(n);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:_m})}},Wv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),mD.init(s,n),kQ.init(s),vd.init(s),Rd.init(s,n),jv.init(s),LQ.init(s),fD.init(s),bm.init(s)}getGroupMemberList(s){return mD.getGroupMemberList(s)}deleteGroupMember(s){return Rd.deleteGroupMember(s)}},GT=new class{init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return pA(this,void 0,void 0,function*(){const n="getGroupCounters";try{Nm(n,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:iA,avChatRoomKey:EA}=P,{common:RA}=Wn.core,kA={GroupId:W,keyList:iA,BytesKey:EA};return RA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){yC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return n(u)?3e4:Number(u)}},km=new class{init(s){const{helper:n}=s;n.registerApi({apiName:"setGroupCounters",context:this}),n.registerApi({apiName:"increaseGroupCounter",context:this}),n.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ku,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(mm,s)})}decreaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(Ri,s)})}_handleCounterOperation(s,n){return pA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{Nm(g,sc);const{groupID:u,key:E,value:m=0}=n,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===Ku?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){yC(g,u)}})}_updateGroupCounters(s){return pA(this,void 0,void 0,function*(){const n=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Wn.core,W={GroupId:m,GroupCounter:D,Mode:M,BytesKey:T};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=n,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},IB=new class{init(s){this._core=s,GT.init(s),km.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:n}}=s,{utils:{isEmpty:g}}=this._core;return!g(n)}handleGroupCounterUpdated(s){const{to:n,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==ni&&E!==on||this._processAndNotifyCounterUpdate(n,m,D),E===yo&&nc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Lm=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(n),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,iA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:RA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:RA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return iA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:iA,seq:EA}=W;return{key:iA,value:g[iA],sequence:EA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:lD}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${M}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},bT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"setGroupAttributes",context:this}),n.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(n),M=zs.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:iA}=T;return{key:W,value:iA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,RA){return pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,JA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return RA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:JA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},iA=W.map(EA=>{const{Key:RA,seq:kA}=EA;return{key:RA,value:g[RA],sequence:kA}});return zs.saveGroupAttributesCacheValuesCopy(n),zs.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:iA,operation:Fv}),zs.emitGroupAttributesUpdated(n),dn({groupAttributes:g},{message:` groupID:${n} serverMainSequence:${P}`})}catch(T){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:T?.errorCode,message:T?.errorInfo})}})}setRichStatus(s){return pA(this,void 0,void 0,function*(){const{groupID:n,richStatus:g}=s;return this.setGroupAttributes({groupID:n,groupAttributes:g,richStatusMode:!0})})}},yD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"deleteGroupAttributes",context:this}),n.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return zs.saveGroupAttributesCacheValuesCopy(g),zs.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),zs.emitGroupAttributesUpdated(g),dn({keyList:D},{message:W})}catch(m){throw new this._core.helper.ChatError({functionName:n,code:m?.errorCode,message:m?.errorInfo})}})}deleteRichStatus(s){return pA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,M=[],T=[];m.forEach(iA=>{if(E.has(iA)){const{sequence:EA=0}=E.get(iA)||{};T.push({key:iA,seq:EA}),M.push(iA)}});const P=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=iA,OA={GroupId:RA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:uD}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:iA,mainSequence:EA,avChatRoomKey:RA,richStatusMode:kA}=P,xA={GroupId:iA,AttrMainSeq:EA,BytesKey:RA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:ID}})}},DD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"getGroupAttributes",context:this}),n.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:iA,value:EA,seq:RA}=W;return{key:iA,value:EA,sequence:RA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:Ov}),{serverGroupAttributeList:T}})}},UQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Lm.init(s),bT.init(s),yD.init(s),DD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(zs.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(n);DD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:u})}reset(){zs.reset()}};function HE(s,n="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:iA,MsgBody:EA}=s,RA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:JA,From_Account:ae,To_Account:se}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:JA,from:ae,to:se}}(iA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:RA,elements:n==="tips"?Zu(EA):dh(EA)}}function Zu(s){const n={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":n.memberCount=s[g];break;case"OpType":n.operationType=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"List_Account":n.userIDList=s[g];break;case"MsgMemberExtraInfo":n.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>SD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=SD(s[g]);break;case"MsgGroupNewInfo":n.newGroupProfile=function(m){const D={};return Object.keys(m).forEach(M=>{switch(M){case"GroupIntroduction":D.introduction=m[M];break;case"GroupName":D.groupName=m[M];break;case"GroupFaceUrl":D.avatar=m[M];break;case"GroupNotification":D.notification=m[M];break;case"ApplyJoinOption":D.joinOption=m[M];break;case"InviteJoinOption":D.inviteOption=m[M];break;case"ShutupAll":D.muteAllMembers=m[M];break;case"Owner_Account":D.ownerID=m[M];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:iA,OpType:EA,PushChangedAttrValFlag:RA,GroupAttrInfo:kA}=P,xA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:JA}=LA;return{key:SA,value:OA,sequence:JA}});return{changedKeyList:W,groupAttributeList:xA,serverMainSequence:iA,operation:EA,withChangedAttributeInfo:RA}}(m[M]);break;case"MsgAppDefinedData":D.groupCustomField=(T=m[M])==null?void 0:T.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=_T[m[M]]||m[M]}var T}),D}(s[g]);break;case"MsgMemberInfo":n.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(m=>function(D){const{ShutupTime:M,User_Account:T}=D;return{muteTime:M,userID:T}}(m));break;case"OnlineMemberInfo":n.onlineMemberInfo=function(m){const{ExpireTime:D,OnlineMemberNum:M}=m;return{expireTime:D,onlineMemberNum:M}}(s[g]);break;case"GroupCounterInfo":n.groupCounterInfo=function(m){return m.map(D=>{const{GroupCounterSeq:M,GroupCounter:T,Type:P}=D;return{type:P,groupCounterSeq:M,counterList:T}})}(s[g])}}),n}function SD(s){const{ImageUrl:n,NickName:g,Role:u,UserId:E}=s;return{avatar:n,nick:g,role:u,userID:E}}function dh(s){const n={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":n.messageKey=s[g];break;case"Operator_Account":n.operatorID=s[g];break;case"ReportType":n.operationType=s[g];break;case"Authentication":n.authentication=s[g];break;case"MsgFlag":n.messageRemindType=s[g];break;case"UserDefinedField":n.userDefinedField=s[g];break;case"RemarkInfo":n.remarkInfo=s[g];break;case"BanDuration":n.duration=s[g];break;case"MuteTime":n.muteTime=s[g];break;case"MsgMemberExtraInfoList":n.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":n.inviteeList=s[g]}var u}),n}class Um{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=Zu(n);return new Um(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(n[g]);break;case"operatorInfo":this._initOperatorInfo(n[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(n[g]);break;case"newGroupProfile":this._initNewGroupProfile(n[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=n[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u{n.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case n.JOINED:this._handleNewMemberJoined(g);break;case n.QUITTED:this._handleMemberQuitted(g);break;case n.KICKED:this._handleMemberKicked(g);break;case n.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case n.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case n.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var n;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Yi.getLocalGroup(m);Object.keys(g).forEach(T=>{switch(T){case"ownerID":this._handleGroupOwnerChanged(m,g);break;case"groupName":D.name=g[T];break;case"groupCustomField":Array.isArray(D[T])&&Array.isArray(g[T])?Tm(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((n=D?.selfInfo)===null||n===void 0?void 0:n.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,n){const{common:g,OuterConstant:u}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;n===pT?u=g.GRP_MBR_ROLE_OWNER:n===dD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,u=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(n)&&u.memberCount!==n&&(u.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_ADMIN}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class FQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=dh(n);return new FQ(g)}_initContent(n){Object.keys(n).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=n[g];break;case"groupProfile":this._initGroupProfile(n[g]);break;case"memberInfoList":break;default:this.content[g]=n[g]}})}_initGroupProfile(n){this.content.groupProfile={};const g=Object.keys(n);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,n){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=n.createMessage(s),m=new FQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&u.unreadCount++,u}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:u}=g.payload;switch(u){case fT:this._handleGroupJoinResult(g);break;case xv:this._handleMemberKicked(g);break;case yT:this._handleGroupDismissed(g);break;case DT:this._handleGroupInvitedResult(g);break;case CD:this._handleGroupQuitResult(g);break;case TQ:this._handleMessageRemindTypeSynced(g);break;case Mm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:u}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Sd(u)||(Yi.updateLocalGroup([Object.assign({},n)]),Yi.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:n,type:g}}=s.payload;Yi.hasLocalGroup(n)&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:n}=s.payload,{groupID:g}=n,u=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||Pl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Yi.updateLocalGroup([Object.assign({},m)]),Yi.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:n,type:g}}=s.payload,u=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(n,g),this._updateConversationProfile(n,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:n},messageRemindType:g}=s.payload;this._updateConversationProfile(n,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:n,type:g}}=s.payload;this._deleteLocalGroup(n,g)}_deleteLocalGroup(s,n){if(Sd(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},MD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),zv.init(s),Zv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:u}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g}}=this._core;n.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){Zv.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},OQ={required:!0,rules:["number"],allowEmpty:!1},wd={required:!0,rules:["array"],allowEmpty:!1},vD={required:!0,rules:["object"],allowEmpty:!1},kT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:wd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:wd},deleteGroupMember:{groupID:vn,userIDList:wd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:wd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},OQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:wd},initGroupAttributes:{groupID:vn,groupAttributes:vD},setGroupAttributes:{groupID:vn,groupAttributes:vD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:vD},increaseGroupCounter:{groupID:vn,key:vn,value:OQ},decreaseGroupCounter:{groupID:vn,key:vn,value:OQ}},LT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var UT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=bQ,this.groupAttribute=UQ,this.groupMember=Wv,this.groupCounter=IB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),bQ.init(s,this),Wv.init(s,this),pD.init(s),IB.init(s),UQ.init(s),MD.init(s),s.helper.registerValidateConfig({auth:LT,params:kT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),UQ.reset(),IB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const uB=new class{init(s){this.core=s}},Xv="AV_MBR_LIST",FT="AV_BAN_MBR",qE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Ch={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},RD=60,wD=2603,OT=2686,PT=2688,PQ=3122;class $v{constructor(n){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return pA(this,void 0,void 0,function*(){try{const n=this._getRequestParams(this._groupID),g=yield function(E,m){return pA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:M,startBroadcastSeq:T,simplifiedMessage:P}=E,W={Key:D,StartSeq:M,StartBroadcastSeq:T,DownsizeFlag:P,USP:1,HoldTime:90};return m.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(n,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(n){this._onFail(this._groupID,n),this._runNextPolling(2e3)}})}_runNextPolling(n){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),n))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class hh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(n,1)}has(n){return this._map.has(n)}delete(n){this.has(n)&&this._map.delete(n)}clear(){this._map.clear()}}const Xu=s=>s===qE.GROUP_TIPS_HAS_NO_ROAMING||s===qE.GROUP_TIPS_HAS_ROAMING,xQ=s=>s===qE.GROUP_SYSTEM_MESSAGE;function Fm(s){const n=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:iA,IsSys:EA,GInf:RA,MsgBody:kA}=g,xA=Do(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:iA,IsSystemMsg:EA,GroupInfo:_D(RA),MsgBody:xT(kA)},xA)}(s);return function(g){const{Event:u}=g;(Xu(u)||xQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===qE.BROADCAST_MESSAGE||(m=>m===qE.NORMAL_MESSAGE)(u))&&function(m){const{core:{OuterConstant:D}}=uB;m.CloudCustomData=m.CloudCustomData||"",m.MsgBody=m.MsgBody.map(M=>{if(M.MsgType===D.MSG_CUSTOM){const{content:T={}}=M;M.content=Object.assign({Data:"",Desc:"",Ext:""},T)}return M})}(g);var E;Xu(u)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:iA}=m.MsgBody||{};typeof D=="number"||iA!==1&&iA!==2||(m.MsgBody.GroupJoinType=iA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),iA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),xQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(n),n}function _D(s){const n=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=n,M=Do(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function xT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:iA}=u,EA=Do(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),RA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(RA.MsgOperatorMemberExtraInfo=function(kA){const{Img:xA,NN:LA}=kA,SA=Do(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),iA&&(RA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=Do(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(iA)),W&&(RA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),RA});return Array.isArray(s)?g:g[0]}var Bh=new class{constructor(){this._name="MessageParser",this._sequenceList=new hh(200),this._messageIDList=new hh(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,n){this._core=s,this._avChatRoomHandler=n}onMessageReceived(s,n,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:n,isHistoryMessage:g});const u=this._handleMessageList(s,n);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,iA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:iA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:n,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${n} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,n){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===qE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===qE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===qE.MESSAGE_REACTION)(n)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${n}`),null)}_createMessage(s){const{message:{messageFactory:n},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:n}=this._core;if(!n.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:n,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:iA,MsgSeq:EA}=T,RA={conversationID:`${n.CONV_GROUP}${u}`,ID:`${P}-${W}-${iA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(RA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:n}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:n}=s;if(n>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${n} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:n},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:n}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(n(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=RD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);n(M)?M={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:m}:(M.latestUpdateTime=D,M.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,M)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const EB=s=>{const{core:{store:n}}=uB;return(n.get("cloudConfig")||{})[s]},Qh=s=>{const{core:{utils:{isUndefined:n}}}=uB;return!n(s)},YQ=()=>{const s=EB("polling_interval");return Qh(s)?parseInt(s,10):300},dB=()=>{const s=EB("polling_simplified_msg");return Qh(s)?parseInt(s,10):0};var AR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},OuterConstant:g}=this._core,u=n.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${n} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const n=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return pA(this,void 0,void 0,function*(){const n="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return pA(this,void 0,void 0,function*(){const P={GroupId:M};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=RD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,n){this._core=s,this._parentPlugin=n,Bh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(n=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),n}handleJoinGroupResult(s){return pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),AR.getGroupOnlineMemberCount(T),M.length>0&&Bh.onMessageReceived(T,M,!0),n(m)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return pA(this,void 0,void 0,function*(){const{common:n,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=EB("polling_count_limit");return Qh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code:PT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,M]=this._joinedGroupMap.entries().next().value;if(M.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(T){m.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,T)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:n}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,YQ()),this._startPolling(m),this._reportLongPollingCount(),{status:n.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const n=new $v({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});n.start(),this._pollingInstanceMap.set(s,n)}_handleRequestParams(s){const{longPollingKey:n,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:n,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:dB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:dB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,YQ())),Bh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=EB("polling_no_msg_count");return Qh(T)?parseInt(T,10):20})()){const T=YQ()+(()=>{const P=EB("polling_interval_plus");return Qh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&Bh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(n)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let n=[];return this._joinedGroupMap.size>0&&(n=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),n.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,n){this._joinedGroupMap.set(s,n),this._parentPlugin.groupDataHandler.updateLocalGroup([n])}handleLiveHistoryMessages(s,n){Bh.onMessageReceived(s,n,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:n,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=EB("av_members_freq_limit");if(Qh(m)){const{interval:D,count:M}=JSON.parse(m);if(M>0&&D>0)return{interval:D,count:M}}return{interval:30,count:4}})();return Date.now()-n>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:n,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:n},OuterConstant:{CONV_GROUP:g}}=this._core;n.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const n of this._pollingInstanceMap.values())n?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,n){this._pollingNoMessageCountMap.set(s,n)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:n,OuterConstant:g,ssoLog:u}=this._core,E=n.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,Bh.reset()}},eR=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?u===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},YT=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}quitGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},tR=new class{init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===n.GRP_AVCHATROOM&&Pg.reset(s),g})}},Om=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const{appStore:{groupStore:n},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(Xv)){if(Pg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return pA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,iA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:iA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${n} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:n,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Pm=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,n){this._core=s,this._parentPlugin=n;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>n.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:n,code:wD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(FT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:PQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:n,code:OT});try{return yield function(T,P){return pA(this,void 0,void 0,function*(){const{groupID:W,userIDList:iA,duration:EA,reason:RA}=T,kA={GroupId:W,Members_Account:iA,Duration:EA,Description:RA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(n,`${this._name}.${n} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},_d=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:n}=s;n.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(iA,EA){return pA(this,void 0,void 0,function*(){const{groupID:RA,operationType:kA,memberList:xA}=iA,LA={GroupId:RA,CommandType:kA,MemberList:xA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:T=[]}=M||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(T,m);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${n} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:n,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:n,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:n,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,n){const g=[],u=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:u}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},iR=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),eR.init(s,n),YT.init(s,n),tR.init(s,n),Om.init(s,n),AR.init(s,n),Pm.init(s,n),_d.init(s)}},oR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:n,ssoLog:g}=s;n.registerExperimentalAPI("startMessageLongPolling",this),n.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:n,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=n.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Pg.reset(n),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${n}`),Promise.resolve({groupID:n})}_getLiveHistoryMessages(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{groupID:g}=s;try{const u=yield function(m,D){return pA(this,void 0,void 0,function*(){const{groupID:M,longPollingKey:T,startSequence:P}=m,W={GroupId:M,LongPollingKey:T,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},xm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,uB.init(s),Pg.init(s,n),iR.init(s,n),oR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(n.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},Ym="message",CB="user",hB={OR:"or",AND:"and"},vI=20,VT=20,sR=20,ph={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Vm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![hB.OR,hB.AND].includes(s)||"keywordListMatchType should be OR or AND"},SC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},VQ={required:!1,rules:["string"],allowEmpty:!0},nR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[n.GRP_PUBLIC,n.GRP_COMMUNITY,n.GRP_WORK,n.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core,g=[n.MSG_TEXT,n.MSG_IMAGE,n.MSG_AUDIO,n.MSG_FILE,n.MSG_VIDEO,n.MSG_LOCATION,n.MSG_CUSTOM,n.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:n}=Ag.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},Jm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),TD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=Ag.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},Hm={searchCloudMessages:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:rR,conversationID:aR,timePosition:Jm("timePosition"),timePeriod:Jm("timePeriod")},searchCloudUsers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,miniBirthday:Jm("miniBirthday"),maxBirthday:Jm("maxBirthday"),gender:TD},searchCloudGroupMembers:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:nR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:ph,keywordListMatchType:Vm,cursor:VQ,count:SC,groupTypeList:nR}},ND={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var GD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:ND,params:Hm})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=Do(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(n.CONV_C2C)?M.account=u.replace(n.CONV_C2C,""):u.startsWith(n.CONV_GROUP)&&(M.groupID=u.replace(n.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return pA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:JA,senderUserIDList:ae,messageTypeList:se,endTime:_i,startTime:Ti,cursor:Ft,account:Ni,groupID:cs}=LA,Se={Count:SA,KeywordList:OA,MatchType:JA,SendUserIDList:ae,MsgTypeList:se,EndTime:_i,StartTime:Ti,Cursor:Ft,PeerAccount:Ni,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Se})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:iA,Cursor:EA="",ConversationMsgs:RA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${iA}`;return{code:0,data:{searchResultList:RA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:JA,UserID:ae}=LA,se=JA?`${n.CONV_GROUP}${JA}`:`${n.CONV_C2C}${ae}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:se,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(JA)?function(Ft,Ni){const cs=Ni.OuterConstant.CONV_C2C,Se=Ni.message.messageHelper.parseServerPushMessage(Ft),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core):function(Ft,Ni){const cs=Ni.OuterConstant.CONV_GROUP,Se=Ni.message.messageHelper.parseServerGroupMessage(Ft),mt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},Se),{conversationType:cs,flow:"in"}));return mt.setElement(Se.elements),mt}(Ti,this._core));return{conversationID:se,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:iA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:Ym,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:u=VT}=s,E=Do(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===hB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:JA,cursor:ae,gender:se}=kA,_i={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:ae,UserBirthStart:OA,UserBirthEnd:JA,Gender:se};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:_i})})}(m);if(!D)return{error:0,data:{}};const{ErrorCode:M,ErrorInfo:T,TotalCount:P,Cursor:W="",Users:iA=[]}=D;if(M!==0)throw{errorCode:M,errorInfo:T};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,RA=[];for(let kA=0,xA=iA.length;kA({tag:ae.Tag,value:ae.StrValue})),JA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);RA.push(JA)}return{code:0,data:{searchResultList:RA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:CB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=sR,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(RA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:JA}=RA,ae={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:JA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:ae})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,GroupMembers:T=[],Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(RA=>{const{GroupID:kA,GroupName:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:JA,GroupMemberNameCard:ae,GroupMemberAvatar:se=""}=RA,_i={groupID:kA,name:xA,type:LA,avatar:SA},Ti={userID:JA,nick:OA,nameCard:ae,avatar:se};if(EA.has(kA)){const Ft=EA.get(kA);Ft.memberList.push(Ti),EA.set(kA,Ft)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=vI,keywordListMatchType:g}=s,u=Do(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===hB.AND?1:0},u),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:RA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:RA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const iA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(RA){const{GroupFaceUrl:kA,GroupID:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:JA,GroupOwnerUserID:ae,GroupOwnerUserName:se,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:Ft}=RA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:JA,ownerID:ae,ownerNick:se,type:_i,joinOption:Ti,inviteOption:Ft}}(EA))||[],cursor:P,totalCount:W},successLog:{message:iA}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};this._handleError({errorCode:g,errorInfo:u,searchType:CB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:n,timePosition:g}){n&&n>0&&(s.startTime=g&&g>0?g-n:this._core.helper.timeManager.getServerTimeSeconds()-n),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:n,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Ym&&s===27003?E="SearchParamsError":g!==Ym&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:u}=n;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function mh(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const gR="qualityStat",bD="im-ssolog-quality-stat";var kD;(function(s){s[s.ONLINE=8]="ONLINE"})(kD||(kD={}));const qm="networkRTT",fh="messageE2EDelay",BB="sendMessageC2C",yh="sendMessageGroup",Dh="sendMessageGroupAV",QB="sendMessageRichMedia",pB="cosUpload",MC="messageReceivedGroup",JQ="messageReceivedGroupAVPush",HQ="messageReceivedGroupAVPull",JT={[qm]:2,[fh]:3,[BB]:4,[yh]:5,[Dh]:6,[QB]:7,[MC]:8,[JQ]:9,[HQ]:10,[pB]:11},cR=[BB,yh,Dh,QB,pB],Sh=[MC,JQ,HQ],mB=[qm,fh,BB,yh,Dh,QB,pB,MC,JQ,HQ],LD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},Km="quality_stat";var qQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(LD))}init(s){this._core=s,Object.values(cR).forEach(n=>{this._messageStatsMap.set(n,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:n,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(n){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const n=this._messageStatsMap.get(s);if(!n||n.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=n,m=mh(u/g*100,2),D=u+E,M=mh(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.totalCount++}_handleSuccessCount(s){const n=this._getSendMessageSpecifiedKey(s),g=n&&this._messageStatsMap.get(n);g&&g.successCount++}_handleFailedCount(s,n){var g;const u=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-n,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:n,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,u,E].includes(s.type))return QB;if(s.conversationType===m)return BB;if(s.conversationType===D){const{groupStore:T}=this._core.appStore,P=T.getGroup(s.to);if(!P)return;const{type:W}=P;return W===M?Dh:yh}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===pB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const n=this._messageStatsMap.get(s);n&&(n.totalCount=0,n.successCount=0,n.failedCountOfUserSide=0,n.costSum=0,n.costCount=0,n.fileSizeSum=0)}},KQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:n,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(n.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const n=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${gR}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(n);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(n,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:mh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Sh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:n=[]}=s;n.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const n=this._currentCycleStats.get(s);if(!n)return;const g=new Map;n.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:n,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===n&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?HQ:MC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((u,E)=>u-E),n.dirty=!1);const g=this._findInsertPos(n.sortedSequences,s);n.sortedSequences.splice(g,0,s),n.minSeq=Math.min(n.minSeq,s),n.maxSeq=Math.max(n.maxSeq,s)}_findInsertPos(s,n){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===n)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:n}}=this._core;s.unSubscribeOuterEvent(n,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:n=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:mh(this._totalDelay/s,1)}_calculatePercentage(s,n){return mh(s/n*100,2)}},lR=new class{init(s){this.core=s}},HT=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;lR.init(s),qQ.init(s),KQ.init(s),jQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:n,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Km,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...mB.map(n=>{const g=this._buildQualityReportItem(n);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:n}}=this._core,{label:g,data:u}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&qQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!n.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const n=this._getStatResultByKey(s);if(n===null)return null;const g={quality_type:JT[s],timestamp:Date.now(),network_type:kD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case fh:return jQ.getStatResult();case BB:case yh:case Dh:case QB:case pB:return qQ.getStatResult(s);case MC:case JQ:case HQ:return KQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return pA(this,void 0,void 0,function*(){try{const n={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=lR.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(n),this._reportIndex++,this._wholePeriod=!1}catch(n){console.warn("doReport failed. error:",n),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,n=`${gR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(bD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(bD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Km)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),jQ.dispose(),KQ.dispose()}};const ll=new class{init(s){this.core=s}};function IR(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=ll.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(n=D.get(s))===null||n===void 0?void 0:n.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;ll.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function uR(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(u){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=ll.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(n);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const UD=1,ER=2,Mh=20,WQ=2500,dR=1,vh=300;function zQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=ll.core,{messageList:P,conversationID:W}=s,iA=u.conversationStore.getConversationMap();let EA=(n=iA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),xA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return ll.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;EA=LA?.[0],iA.has(W)&&(iA.get(W).peerReadTime=EA)}}if(iA.has(W)){const kA=(g=iA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const RA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,RA.push(kA))}),RA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:RA})})}var CR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return pA(this,void 0,void 0,function*(){try{const{message:n,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=Mh;if(M==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:M,nextReqMessageID:T});if(this._needFetchHistoryMessageList({conversationID:M,availableLocalMessagesCount:W,targetCount:P})){let iA=null;if(M.startsWith(E)?iA=yield n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(iA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),iA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:RA,messageList:kA}=iA,xA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(ae){const{appStore:se,message:_i,OuterConstant:Ti}=ll.core,Ft=se.conversationStore.getConversation(ae),Ni=_i.messageDataHandler.getLocalMessageList(ae);if(!Ft||Ni.length===0||ae===Ti.CONV_SYSTEM)return;const cs=[];for(let mt=0;mtUA.isRevoked).length;Se=cs.length-Ft.unreadCount-mt}else Se=cs.length-Ft.unreadCount;for(let mt=0;mtae.isRevoked);yield uR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:RA?"":String(EA),messageList:LA,isCompleted:RA},JA=LA.map(ae=>ae.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(JA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:M,nextReqMessageID:T,count:P}),successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W}}`}}}catch(n){const{code:g,message:u}=n||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:iA},message:EA,notificationCenter:RA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=Mh}=s;xA=xA>Mh?Mh:xA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:xA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:JA,invisibleSequenceList:ae}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(JA),RA.emitInnerEvent(kA,JA),W===u.FORWARD){const se=OA&&SA<1;return{code:0,data:{messageList:JA,isCompleted:se,nextMessageSeq:se?"":SA}}}if(W===u.BACKWARD){if(iA(JA)&&iA(ae))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const se=((n=JA?.[JA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=ae?.[ae.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:JA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(se,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:xA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:JA}=LA;return RA.emitInnerEvent(kA,SA),JA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield zQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:JA,nextMessageTime:JA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:WQ});const W={fromAccount:E()},{type:iA}=P;iA===m?(W.type=UD,W.toAccount=s.replace(m,"")):iA===D&&(W.type=ER,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(RA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=RA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return ll.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:RA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:RA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:n}=this._core;n.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!n)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===n):s?.startsWith(u)&&(D=E.findIndex(M=>n.includes("-")?M.ID===n:String(M.sequence)===n)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:n,targetCount:g}){const{message:u}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=iA>u?iA-u:0,T=iA):W=M>u?M-u:0,P.messageList=D.slice(W,iA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield IR(n),yield zQ({messageList:P.messageList,conversationID:n})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:n}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[n].ID:String(g[n].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},fB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:n},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:n}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(n)){const E=n.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return pA(this,void 0,void 0,function*(){const{OuterConstant:n}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${n.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:iA,appStore:EA,common:{getMessagePreviewText:RA,buildLastMessage:kA}}=this._core,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield iA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:JA,hasNoMoreHistoryMessage:ae,messageList:se,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=ae&&JA<0,Ft=[];if(m(se)&&(se.forEach(Ni=>{iA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),iA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(Ft.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),Ft.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Ft})),!Ti&&se.length>0){const Ni=se[se.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=RA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(n,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${n}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,n=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of n){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:n}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const u=g-n;return g!==0&&n>0&&u>=dR&&u{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return pA(this,void 0,void 0,function*(){yield Promise.all(s?.map(n=>pA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,u=g-n;return n>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:iA,message:EA,appStore:RA,common:{getMessagePreviewText:kA,buildLastMessage:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:JA}=SA,ae=[];m(JA)&&(JA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(ae.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=xA(_i)))}),ae.length>0&&iA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:ae}));const se=(n=JA[JA.length-1])===null||n===void 0?void 0:n.time;!OA&&se>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:se,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),RA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${T(LA)}`)}})}_getLocalLastMessageTime(s){const{message:n}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},yB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,ll.init(s),CR.init(s),fB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(n.DESTROY,this.dispose,this),fB.dispose()}_reset(){fB.reset()}},FD=new class{init(s){this.core=s}},vC=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:n}}=s;this._core=s,n("reportModalView",this),n("reportTUIFeatureUsage",this),n("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:n,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");n.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){n.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:n,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){n.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:n},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${n(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${n(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},ZQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;FD.init(s),vC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(u,this._dispose,this)}_reset(){vC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),vC.dispose()}};let jm=nr.STANDARD,DB=[];jm=nr.STANDARD,DB=[ah,IC,uC,EC,Rc,HT,yB,ZQ,PE,vi,jn,UT,xm,GD,XI];function SB(s,n){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const XQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Zc(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var $Q=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:XQ,get builtInPlugins(){return DB},checkBusinessCapabilityBits:tn,deepMerge:Cd,getCurrentUserID:Ar,getErrorMessage:rs,getMessagePreviewText:Zc,isC2CConv:s=>l(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:Xr,isGroupConv:s=>l(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:wl,isTopic:zc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=fe.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ca,registerInterceptor:Mc,registerValidateConfig:Wc,requireAuth:ud,get sdkEdition(){return jm},setGroupTipsUserInfo:SB,t:ku,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Lo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:iA}=Lo,{groupID:EA,sequence:RA}=M;let kA=!1;return Xr({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===RA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[iA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[iA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};n.push(D)},validateAndExecute:Sr,validateParameters:II});class au{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return au._instance||(au._instance=new au),au._instance}static setInstance(n){au._instance=n}installBuiltInPlugin(n){n&&this._installPlugin(n,this._builtInPlugins)}installExternalPlugin(n){n&&this._installPlugin(n,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(n,g){let u=[];u=h(n)?n:[n];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(Cr.getInstance().exposeApiForPlugin(),m)):D.install(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(Cr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(n){return this._builtInPlugins.has(n)||this._externalPlugins.has(n)}_isLoggedIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var MB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),u&&fe.notificationCenter.emitInnerEvent(no.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),fe.notificationCenter.emitInnerEvent(no.CONVERSATION_UPDATED))}},Ap=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,n){const g=this._groupMap.get(s);g&&!Rs(n)&&Object.keys(n).forEach(u=>{g[u]=n[u]})}},ep=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=Do(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var n;return[...((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,n){const{conversationID:g}=n;zc(g)?fe.notificationCenter.emitInnerEvent(_u[s],n):fe.notificationCenter.emitInnerEvent(s,n)}},rc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},OD=Object.freeze({__proto__:null,conversationStore:MB,groupStore:Ap,messageStore:ep,userStore:rc});class Cr{static getInstance(){return Cr._instance||(Cr._instance=new Cr),Cr._instance}static setInstance(n){Cr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:fe.notificationCenter.subscribeOuterEvent.bind(fe.notificationCenter),off:fe.notificationCenter.unSubscribeOuterEvent.bind(fe.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:au.getInstance().installExternalPlugin.bind(au.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){fe.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){fe.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){fe.ssoLog.debug("setLogLevel",n),fe.ssoLog.setLogLevel(n)}setApplicationID(n){fe.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:u}}=fe,{apiName:E,context:m,methodName:D=E,matcher:M}=n;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:m,methodName:D,matcher:M}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...T)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),qI.includes(E)&&fe.ssoLog.debug(E,`${E} start params: ${u(T)}`),Sr(D,T);const iA=this._apiHandlersMap[E];for(const EA of iA)if(!EA.matcher||EA.matcher(T))try{const RA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(RA)?this._handleAsyncResult(RA,E,W,P):(this._reportApiSuccessLog({result:RA,apiName:E,eventType:W,startTime:P}),RA)}catch(RA){throw fe.ssoLog.error(E,`${E} fail ${RA?.message||RA?.errorMessage})`,{error:RA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),RA}})}registerExperimentalAPI(n,g,u){const E=u||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=fe.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),fe.notificationCenter.emitInnerEvent(no.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{fe.notificationCenter.emitOuterEvent(Dr.SDK_DESTROY,{SDKAppID:(g=fe.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ca.clear(),au.getInstance().clear(),ws.getInstance().destroy(),fe.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:no,InnerEventSubType:fe.notificationCenter.InnerEventSubType,OuterEvent:Dr,OuterConstant:Lo,SignalingEvent:qc,helper:Object.assign(Object.assign(Object.assign({},fe.utils),fe.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:Wc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},fe),{constants:Object.assign(Object.assign({},za),fe.constants),common:Object.assign(Object.assign(Object.assign({},$Q),fe.common),{workflowManager:ws.getInstance()}),utils:fe.utils,appStore:OD})}callExperimentalAPI(n,g){return fe.ssoLog.debug(`callExperimentalAPI.${n} start params: ${fe.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(fe.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${fe.utils.safeStringify(g)}`),Promise.reject(new gs({code:da.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,u,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw fe.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:fe.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:u,startTime:E,eventType:m}=n;const{timeManager:D}=fe.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),qI.includes(u)&&fe.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class hR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=fe;g.set("login",{isReady:!1}),Cr.getInstance().registerApi({apiName:"login",context:this}),Cr.getInstance().registerApi({apiName:"logout",context:this}),Cr.getInstance().registerApi({apiName:"getLoginUser",context:this}),Cr.getInstance().registerApi({apiName:"isReady",context:this}),Cr.getInstance().registerApi({apiName:"getServerTime",context:this}),Cr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(no.RECONNECTED,this._reLogin,this),fe.notificationCenter.subscribeInnerEvent(no.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=fe.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:da.REPEAT_LOGIN});const E=yield this._performLogin(n);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=fe.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=fe.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==da.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return pA(this,void 0,void 0,function*(){var n;try{if(!this._isLoginIn())return;const g=yield bu(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;fe.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:SE.USER_STATUS_ONLINE});const m=(n=fe.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();fe.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=na.USER_INITIATED){const{ssoLog:g}=fe;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),fe.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=fe.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),fe.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=fe.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){fe.store.set("login",{isReady:!0}),setTimeout(()=>{fe.notificationCenter.emitOuterEvent(Dr.SDK_READY,{name:Dr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){fe.store.set("login",{isReady:!1}),fe.notificationCenter.emitOuterEvent(Dr.SDK_NOT_READY,{name:Dr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=n||{};if(!u)throw new gs({functionName:g,code:da.NO_TINYID});if(!E)throw new gs({functionName:g,code:da.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(n=fe.store.get("login"))===null||n===void 0?void 0:n.userId}),repeatLogin:!0}}}_performLogin(n){return pA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=n;return fe.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),bu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=fe.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(n),fe.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),fe.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=fe.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield fe.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=n;fe.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return pA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const n="im_open_status.wshello",g=fe.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),u=`${g.head.seq}${n}`;return fe.channel.sendPacket(g,{requestId:u})}()}catch(n){fe.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=fe.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){fe.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",fe.store.clear("login"),fe.store.set("login",{isReady:!1}),fe.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}const BR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},qT={logout:!0};class Rh{constructor(){this.loginAction=new hR,this.kickedOutHandler=new Gu,this.loginAction.init(),this.kickedOutHandler.init(),Wc({auth:qT,params:BR})}}var Kr,$u,KE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}($u||($u={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(KE||(KE={}));const PD={1:$u.MSG_PRIORITY_HIGH,2:$u.MSG_PRIORITY_NORMAL,3:$u.MSG_PRIORITY_LOW,4:$u.MSG_PRIORITY_LOWEST},xD=0,QR=1;var AE;(function(s){s.IN="in",s.OUT="out"})(AE||(AE={}));const pR=2,tp={};function gu(s){if(!s)return 0;if(tp[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),u=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);tp[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${tp[s]}`)}else tp[s]+=1;return tp[s]}class jE{constructor(n){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=$u.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=fe.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:iA="",time:EA,messageControlInfo:RA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:JA,checkResult:ae=0,isPlaceMessage:se=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:Ft=!1,status:Ni=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Se,clientSequence:mt,protocol:UA="JSON",revokerInfo:ri={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Or,atUserList:xi,flow:gr,isRead:Gt=!1,priority:bt=$u.MSG_PRIORITY_NORMAL,onlineOnlyFlag:tE=!1,nameCard:ln="",quoteInfo:Bo}=n;var Il;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=iA,this.protocol=UA,this.random=Gi===void 0?(Il=Il||99999999,Math.round(Math.random()*Il)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!RA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!RA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=JA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=ae>1,this.version=SA,this.isPlaceMessage=se,this.isRevoked=se===2||_i===8,this.isSystemMessage=Ft,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=ri,this._receiverList=Ti,this.conversationSubType=Se,this.revoker=ri?.revoker||"",this.clientSequence=mt||JA||0,this.status=Ni,this.atUserList=xi||[],this.flow=gr,this.isRead=Gt,this.priority=bt,this._onlineOnlyFlag=tE,this.nameCard=ln,this.quoteInfo=Bo,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Or)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(n){Array.isArray(n)?this._elements=n:this._elements=[n],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(n=>n.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(n){this._relayFlag=n}validateBeforeSend(){var n,g,u;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(n){const{readReceiptSentByPeer:g,timestamp:u=0}=n;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(n){n===this.from&&(this.isRead=!0),this._initSequence(n),this._concatConversationID(n),this.generateMessageID()}_concatConversationID(n){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=gu(n)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class Td{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:u,Ext:E,Desc:m}=g;return new Td({data:u,description:m,extension:E})}constructor(n){this.type=KE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=n;this.content={data:g,description:u,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=fe.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!n(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Nd{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:u}=g;return new Nd({text:u})}constructor(n){this.type=wg.MSG_TEXT,this.content={text:n.text||""}}validateBeforeSend(){var n,g;return((g=(n=this.content)===null||n===void 0?void 0:n.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var Wm=new class{constructor(){this._elementClassMap={[KE.MSG_CUSTOM]:Td,[KE.MSG_TEXT]:Nd}}init(){Cr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Cr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,n){var g;(g=n).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=n)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:n,flow:g=AE.OUT}=s,{userId:u}=fe.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:u})&&(s.flow=AE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new jE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),u=this._elementClassMap[KE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var n;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((n=s?.payload)===null||n===void 0?void 0:n.text)||"",u=new Nd({text:g}),E=Ar(),m=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var n,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=fe.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=AE.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(n=Ap.getGroup(D))===null||n===void 0?void 0:n.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===AE.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:u}=s;return n===u&&g===AE.OUT}};const mR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Gd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},YD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function fR(s,n){return Object.keys(n).forEach(g=>{const{range:u,defaultValue:E}=n[g];s[g]=u.includes(s[g])?s[g]:E}),s}function ip(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function yR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,u=n.OPPOChannelID||g,E=fR(n,Gd),{sound:m="",FCMChannelID:D=""}=E,M=Do(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:ip(m),OPPOChannelID:u,GoogleChannelID:D})}function DR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=fR(n,YD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=Do(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(u)||(W=u===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function VD(s){return fe.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:DR(s),AndroidInfo:yR(s)}:mR}function zm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:iA,SendMsgControl:EA,SupportMessageExtension:RA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:JA,InnerSdkCustomData:ae}=s;let se,{From_Account:_i,To_Account:Ti}=s;if(m===1){const Ft=Ti;Ti=_i,_i=Ft}if(JA){const{Reason:Ft,Revoker_Account:Ni,Revoker_FromUin:cs}=JA;se={reason:Ft,revoker:Ni,revokerFromUin:cs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:u===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:iA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:RA,to:Ti,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:se,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:RC(D),onlineOnlyFlag:T===0,quoteInfo:op(ae)}}function Zm(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,to:M,elements:RC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function JD(s){const{ClientSeq:n,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:iA,CloudCustomData:EA,MsgVersion:RA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:JA,InnerSdkCustomData:ae}=s;let se,_i=$u.MSG_PRIORITY_NORMAL;if(Object.keys(PD).includes(String(s.MsgPriority))&&(_i=PD[s.MsgPriority]),SA){const{Reason:Ft,Revoker_Account:Ni,Revoker_FromUin:cs}=SA;se={reason:Ft,revoker:Ni,revokerFromUin:cs,userID:Ni}}const Ti=function(Ft){const Ni=[];return Array.isArray(Ft)&&Ft.forEach(cs=>{cs.GroupAtAllFlag===xD?Ni.push(cs.GroupAt_Account):cs.GroupAtAllFlag===QR&&Ni.push(Lo.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:u,clientTime:m,priority:_i,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:iA,cloudCustomData:EA,messageVersion:RA,checkResult:kA,needReadReceipt:xA,isPlaceMessage:LA,revokerInfo:se,atUserList:Ti,elements:RC(E),to:KT(s),onlineOnlyFlag:JA===1,quoteInfo:op(ae)}}function KT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=fe,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?u:m}function RC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=fe.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const n=fe.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function HD(s){const{From_Account:n,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:iA}=s;return{from:n,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:RC(g),messageVersion:P,cloudCustomData:W,checkResult:iA}}function op(s){const{utils:{isString:n,safeStringify:g},ssoLog:u}=fe;if(!n(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function sp({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":XQ(n),P=!D&&m===AE.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function vB(s){return s.filter(n=>{const g=!Rs(n?._elements),u=n?.isPlaceMessage===1;return g||fe.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!u})}function RB(s){const{messageDataHandler:n}=fe.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var SR=Object.freeze({__proto__:null,autoIncrementIndex:gu,createAndroidPushInfo:yR,createApnsPushInfo:DR,createOfflinePushInfo:VD,filterValidMessages:vB,getAndroidSoundName:ip,parseServerGroupMessage:JD,parseServerPushC2CModifyMessage:Zm,parseServerPushGroupModifyMessage:HD,parseServerPushMessage:zm,parseServerPushMessageElement:RC,shouldStoreMessage:RB,updateConversationFields:sp});const{isPlainObject:MR}=fe.utils;function np(s,n={}){const{onlineUserOnly:g,messageControlInfo:u}=n;let{offlinePushInfo:E}=n;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&MR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function qD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const u=[];return n&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function wh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let RA;return h(E._receiverList)&&E._receiverList.length>0&&(RA=E._receiverList,E._receiverList.length>50&&(RA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:T?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:VD(iA),SendMsgControl:T?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:RA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:qD(m),InnerSdkCustomData:_B(E)}}}(s,n):function(E,m){var D;const M=np(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:iA}=M,EA=T===!0?0:void 0,RA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=fe.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:RA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:VD(iA),ForbidCallbackControl:qD(m),InnerSdkCustomData:_B(E)}}}(s,n),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function _h(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:iA,MsgVersion:EA,CloudCustomData:RA}=W;return{elements:RC(iA),messageVersion:EA,cloudCustomData:RA}}})}function wB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:RC(M),messageVersion:T,cloudCustomData:P}}})}function Th(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),h(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Xm(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function _B(s){if(fe.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:u}})}}var KD=Object.freeze({__proto__:null,createMessagePackOptions:np,generateForbidCallbackControl:qD,getC2CRoamingMessagesByAnchor:Xm,getGroupRoamingMessagesByAnchor:Th,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:_h,modifyGroupMessage:wB,sendMessage:wh});const{isPlainObject:jT}=fe.utils,{MSG_AUDIO:jD,MSG_FILE:WD,MSG_IMAGE:vR,MSG_VIDEO:RR,MSG_MERGER:wR}=Lo;class $m{constructor(){this._sendProtocolMap=new Map}init(){Cr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![jD,WD,vR,RR,wR].includes(n[0].type)})}registerSendProtocol(n,g,u){this._sendProtocolMap.set(n,g.bind(u))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=rr;if(!(n instanceof jE))throw new gs({code:da.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:iA=""}=M.error||{};throw new gs({code:W,message:iA})}this._reportMessageSendQuality({name:u,message:n});let T=!1;const{messageDataHandler:P}=fe.message||{};try{const{messageControlInfo:W}=g||{};let iA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),RA=this._getSendProtocol(n);if(n.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,iA=yield RA(n,g)):n.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),iA=yield RA(n,g)),iA){const{messageDropReason:kA,sequence:xA,time:LA}=iA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,xA,kA),this._reportMessageSendQuality({name:m,message:n}),this._reportMessageSendQuality({name:E,message:n,startTs:EA}),n.isResend===!0){const SA=P.findMessage(n.ID);SA&&(fe.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Yr.SUCCESS,n.time=LA,n.conversationType===Kr.CONV_GROUP&&(n.sequence=xA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===wg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:iA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Yr.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:iA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(iA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(iA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new gs({code:iA,message:EA,data:{message:n},moreMessage:`type:${n.type} from:${n.from} to:${n.to}`})}})}_hasRiskContent(n){return n===80001||n===80004}_isRejectedByRestApi(n){return n>=10100&&n<=10200||n>=120001&&n<=13e4}_emitOnlineMessageSent(n){const g=n._isExcludedFromLastMessage?"":n,{conversationID:u,conversationType:E}=n,m=zc(u)?no.TOPIC_NEW_MESSAGE:no.NEW_MESSAGE;fe.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&jT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,u){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${u}`;fe.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=fe.message||{};let u=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=n;let M=m,T=Ap.getGroup(M);if(Xr({groupID:M})&&T?.isSupportTopic)throw new gs({code:da.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zc(m)&&([M]=m.split(sa.TOPIC),T=Ap.getGroup(M)),!T&&typeof((g=Cr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield Cr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Lo.GRP_AVCHATROOM){const W=rs({code:da.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:da.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){fe.notificationCenter.emitInnerEvent(no.QUALITY_STAT,{label:cI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||wh}}var WT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){fe.notificationCenter.subscribeInnerEvent(no.LOGOUT,this._reset,this),fe.notificationCenter.subscribeInnerEvent(no.DESTROY,this._dispose,this)}get _messagesByConversation(){return ep.getMessages()}storeConversationMessage(s,n=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,n)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:n}=s;s.flow==="out"?this._setLatestMsgSentByMe(n,s):n.startsWith("C2C")&&this._setLatestMsgSentByPeer(n,s)}_shouldSkipStoreMessage(s,n){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(u))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(fe.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(n=E.get(s)||null,n)break}return n}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:n,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m){const M=this._getUniqueIdOfMessage(m);return ep.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:n}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:n}=s[0],g=s.length;this._sparseMessagesByConversation.has(n)||this._sparseMessagesByConversation.set(n,new Map);const u=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var n;const g=Array.from(((n=this._messagesByConversation.get(s))===null||n===void 0?void 0:n.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:u,sequence:E,time:m}=s;return`${n}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,n){this._latestMessageSentByPeerMap.set(s,n)}_setLatestMsgSentByMe(s,n){this._latestMessageSentByMeMap.set(s,n)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:n="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(n);if(!m)return;const D=Array.from(m.values()),M=E?"out":"in";D.forEach(T=>{const{nick:P,avatar:W,flow:iA}=T;iA===M&&(P!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(u)}isMessageSentByCurrentInstance(s){const{random:n}=s;return this._randomOfSentMessageList.has(n)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const n=this._messagesByConversation.get(s);return n?[...n.values()]:[]}getSparseMessageList(s){const n=this._sparseMessagesByConversation.get(s);return n?[...n.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),fe.notificationCenter.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),fe.notificationCenter.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}};function Af(s,n){const g=MB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:iA}=n;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=Zc(u.type,u.payload),u.cloudCustomData=iA,u.version=P,MB.updateConversation(s,{lastMessage:u}))}}class _R{init(){Cr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=n;if(this._canModifyMessageElement(P)){const W=n?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,iA=null;if(m===Kr.CONV_C2C?W=yield _h(n):m===Kr.CONV_GROUP&&(W=yield wB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Kr.CONV_C2C&&(EA=`${m}${T}`),iA={conversationType:m,from:T,to:g,time:M,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(iA),{code:0,data:{message:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:iA}=W||{};throw new gs({functionName:"modifyMessage",code:iA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent(Dr.MESSAGE_MODIFIED,{name:Dr.MESSAGE_MODIFIED,data:[E]}),fe.notificationCenter.emitInnerEvent(no.MESSAGE_MODIFIED,{conversationID:g,message:E}),Af(g,n)}_canModifyMessageElement(n){return[KE.MSG_TEXT,KE.MSG_CUSTOM,KE.MSG_LOCATION,KE.MSG_FACE].includes(n)}}class Nh{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Vt.RECEIVE_C2C_NEW_MESSAGE,Kt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Vt.RECEIVE_C2C_NEW_MESSAGE,Kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){ws.getInstance().executeWorkflow(Vt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):RB(M)&&(u.storeConversationMessage(M)&&sp({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[Kt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:u=[]}=((g=n.result)===null||g===void 0?void 0:g[Kt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=n?.filter(E=>!E?.isModified);u.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(n){const g=Kr.CONV_C2C,u=zm(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:AE.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=n;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:iA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(iA)?iA:n.avatar):D===W&&M===iA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:u,avatar:E}=n,m=MB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||MB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),fe.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Af(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=Zm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=fe.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;fe.notificationCenter.unSubscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),fe.notificationCenter.unSubscribeInnerEvent(no.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),fe.notificationCenter.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}class Gh{init(){const{notificationCenter:n}=fe,{InnerEventSubType:g}=n;ws.getInstance().registerWorkflowStep(Vt.RECEIVE_GROUP_NEW_MESSAGE,Kt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Vt.RECEIVE_GROUP_NEW_MESSAGE,Kt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){this._canExecuteReceiverNewMessageWorkFlow(n)&&ws.getInstance().executeWorkflow(Vt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:u}=fe.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):RB(T)&&u.storeConversationMessage(T)&&(E.push(T),sp({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:u}=((g=n.result)===null||g===void 0?void 0:g[Kt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Kr.CONV_GROUP,u=JD(n),E=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:AE.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:u}=fe.message||{},E=(g=fe.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=n;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Lo.CONV_SYSTEM){const{operationType:W,memberInfoList:iA,operatorInfo:EA}=P;let RA={};if(Rs(iA)?Rs(EA)||(RA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(RA=Object.assign({},iA[0])),!Rs(RA)){const{nick:kA="",avatar:xA=""}=RA;n.nick=kA,n.avatar=xA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:u,message:E}=fe.message.messageDataHandler.modifyConversationMessage(g,n);u===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Af(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=HD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=fe,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=n;n.unSubscribeInnerEvent(no.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(no.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,u;const{GroupId:E,GroupType:m}=((u=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!Ap.getGroup(E)&&D)}}var zD=new class{constructor(){this.c2cMessageReceiver=new Nh,this.groupMessageReceiver=new Gh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const TR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(n){var g;return typeof n?.text!="string"||typeof n.text=="string"&&((g=n?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},zT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var ZT=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){try{const{conversationID:n,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===Kc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const iA=yield Th({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(iA){const{RspMsgList:EA=[],NextReqMsgSeq:RA=0,IsFinished:kA,InvisibleMsgSeq:xA}=iA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${RA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let ae=0;ae=E),OA&&D&&this.completedHistoryConversations.add(n);const JA=vB(SA);return fe.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:JA,invisibleSequenceList:xA,nextReqMessageIDFromServer:RA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:u}=n||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Lo.MSG_GRP_TIP);const u=JD(s),E=Wm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return SB(((n=u.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?fe.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const RA=this._historyMessageListFetchAnchors.get(g);T=RA.lastMessageTime,P=RA.messageKey}}const W=g.replace(ka.CONV_C2C,""),iA=yield Xm({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(iA){const{MsgList:EA=[],Complete:RA,MsgKey:kA,LastMsgTime:xA}=iA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let ae=0;ae{const{tag:E,value:m}=u;E&&E.indexOf(XD)>-1?g.profileCustomField.push({key:E,value:m}):bd.has(E)&&(g[bd.get(E)]=m)}),Object.assign(Object.assign({},ef),g)}parseProfileItem(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.Value})}),n}parseProfileList(s=[]){const n=[];return s.forEach(g=>{n.push({tag:g.Tag,value:g.ValueBytes})}),n}convertParamsToProfile(s){const n=[];return Object.keys(s).forEach(g=>{g!==$D&&n.push({tag:xl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&h(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(XD)>-1&&g.push({key:E,value:m}),bd.has(E)&&m!==void 0){const D=bd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:GR}=fe.common;function bR(s){return pA(this,void 0,void 0,function*(){const n="profile.portrait_get_all",g={From_Account:Ar(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=GR({servcmd:n,data:g}),E=`${u.head.seq}${n}`,m=yield fe.channel.sendPacket(u,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:iA}=D,EA=[];return iA.map(RA=>{const{To_Account:kA,CustomSequence:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:JA}=RA,ae=eE.parseProfileItem(JA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:ae})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function WE(s){return rc.getFriendMap().has(s)}const{isEmpty:AS}=fe.utils;class tf{constructor(){this._strangerProfileMap=new Map}init(){Cr.getInstance().registerApi({apiName:"getMyProfile",context:this}),Cr.getInstance().registerApi({apiName:"getUserProfile",context:this}),Cr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=eE.createProfile.bind(eE);const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,Kt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield bR([n]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(n,u),{code:0,data:u}}}catch(n){const{errorCode:g,errorInfo:u}=n;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>NR&&(fe.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=NR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!AS(D))throw D;if(h(m))return m.forEach(iA=>{WE(iA.userID)?rc.getUserProfileMap().set(iA.userID,iA):this._strangerProfileMap.set(iA.userID,iA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new gs(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=rc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u={};for(const m in n)n[m]!==void 0&&(u[m]=n[m]);const E=eE.convertParamsToProfile(u);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",iA=GR({servcmd:W,data:P}),EA=`${iA.head.seq}${W}`,RA=yield fe.channel.sendPacket(iA,{requestId:EA});if(RA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=RA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):eE.createProfile(g,E);const T=!rg(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),rc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${fe.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${fe.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,n):eE.createProfile(g,n),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(n){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:eE.parseProfileList(T)}}(n.ProfileDataMod[0]);if(AS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){fe.notificationCenter.emitInnerEvent(no.PROFILE_UPDATE,{name:no.PROFILE_UPDATE,data:[n]}),fe.notificationCenter.emitOuterEvent(Dr.PROFILE_UPDATED,{name:Dr.PROFILE_UPDATED,data:[n]}),MB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(n){const{userId:g,profileList:u}=n,E=rc.getUserProfile(g);if(!(Ar()===g||WE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=eE.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===$D?this._isCustomFieldChanged(E.profileCustomField,m.profileCustomField):E[W]!==m[W]);if(!D)return{isProfileUpdated:!1,profile:E};const M=Date.now(),T=Object.prototype.hasOwnProperty.call(m,$D)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return rc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],u=[];return n.forEach(E=>{const m=rc.getUserProfileMap().has(E);WE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!AS(m.profileItem)),E=Date.now();return u.map(m=>{const D=eE.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!WE(n)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(n)||{},E=((g=fe.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(u,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(bR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);h(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!h(g)||g.length===0)return!1;if(!h(n)||n.length===0)return!0;const u=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const u=h(n)?n.map(E=>Object.assign({},E)):[];return h(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const of=new Map,eS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=eS.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:$T}=fe.utils,{generateProtocolData:sf}=fe.common;function kR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=sf({servcmd:n,data:{To_Account:s}}),u=`${g.head.seq}${n}`,E=yield fe.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:RA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:RA,statusType:kA,customStatus:rp(xA),onlineDevices:AN(LA)}}),iA=T.map(EA=>{const{To_Account:RA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:$T(kA)?RA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:iA}}(E)})}function AN(s){const n=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&n.push(u)}),n}class eN{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=fe;Cr.getInstance().registerApi({apiName:"getUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Cr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Cr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.USER_STATUS_UPDATE,this._onReOnline,this),n.subscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this)}setSelfStatus(n){return pA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:u}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=sf({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield fe.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:bh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(n){return pA(this,void 0,void 0,function*(){const{userIDList:g=[]}=n;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=rp(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_subscribe",W=sf({servcmd:P,data:{To_Account:M}}),iA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:iA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=fe,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const iA=sf({servcmd:P,data:W}),EA=`${iA.head.seq}${P}`;return yield T.sendPacket(iA,{requestId:EA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:rp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(n){const g=rp(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:Ar(),statusType:bh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(n){fe.notificationCenter.emitOuterEvent(Dr.USER_STATUS_UPDATED,{name:Dr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:fe.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!fe.store.get("commercialConfig").get(XT))throw new gs({functionName:n,code:da.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=fe.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:bh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(n,g),E=yield kR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this),n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const tS={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const n of s){if(typeof n!="object")return"Each item in profileCustomField must be an object";if(typeof n?.key!="string")return"Each item.key in profileCustomField must be a string";if(!n?.key.startsWith(XD))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},tN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class iN{constructor(){this.userProfile=new tf,this.userStatus=new eN,this.userProfile.init(),this.userStatus.init(),Wc({auth:tN,params:tS})}}function iS(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let u=g-1;u>=0;u--)s[u]==="1"&&n.push(2**(g-u-1));return n}var kd,wC,Ld;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(kd||(kd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(wC||(wC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Ld||(Ld={}));class oS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=fe;ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Kt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Vt.SYNC_SERVER_INFO_AFTER_LOGIN,Kt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(no.LOGOUT,this._reset,this),n.subscribeInnerEvent(no.DESTROY,this._dispose,this),fe.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===kd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=fe;n.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=kd.RESOLVED;const{conversationList:E=[]}=u||{};return n.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);n.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=kd.PENDING;const u=yield function(iA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:RA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=iA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:RA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:Ar(),pagingTimeStamp:n?this._pagingTimeStamp:0,pagingStartIndex:n?this._pagingStartIndex:0,pagingPinnedTimeStamp:n?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:n?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=kd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),fe.notificationCenter.emitInnerEvent(no.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:iA}=yield this._pagingGetConversationList(n);g.push(...iA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=fe,u=this._convertConversationKey(n);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===wC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:u})=>g===wC.C2C&&!function(E){let m;return E.startsWith(Lo.CONV_C2C)&&(m=E.replace(Lo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(n){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${Lo.CONV_C2C}${n.userID}`,type:Lo.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(u=n.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=n.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(n.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=n.lastMsg)===null||m===void 0?void 0:m.elements)===null||D===void 0?void 0:D[0])===null||M===void 0?void 0:M.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(n),revoker:((P=(T=n.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:n.peerReadTime,isPinned:n.isPinned===1,customData:n.customMark||"",markList:iS(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:u,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=fe.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=n;return u===g&&E<=m}_assembleGroupOption(n){var g,u,E,m,D;return{conversationID:`${Lo.CONV_GROUP}${n.groupID}`,type:Lo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(u=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Ld.GROUP,onlineOnlyFlag:!1,nick:n.msgGroupFromNickName||"",nameCard:n.msgGroupFromCardName||"",revoker:((D=(m=n.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:n.groupID,name:n.groupNick,avatar:n.groupImage,type:n.groupType,nextMessageSeq:n.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(n),peerReadTime:0,isPinned:n.isPinned===1,version:0,customData:n.customMark||"",markList:iS(n.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(n.messageRemindType),subType:n.groupType}}_convertConversationKey(n){return n.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(n){var g,u,E;const{utils:{isEmpty:m}}=fe;if(m(n))return null;let D="",M=null;if(!m(n.GroupTips)){const{From_Account:T,GroupName:P}=((g=n.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Lo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(u=n.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,n.MsgBody[0])),{event:n.Event,elements:[{type:D,content:M,cloudCustomData:n.CloudCustomData}],revokerInfo:{revoker:(E=n.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(n,g){var u;if(!g)return g;const E=fe.message.messageFactory.getElementClass(n);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return Do(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=Lo.MSG_REMIND_ACPT_AND_NOTE:n===1?g=Lo.MSG_REMIND_DISCARD:n===2?g=Lo.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=Lo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:u}}=fe,{event:E,elements:m=[]}=n.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Lo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:u=0}=n,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=fe;n.unSubscribeInnerEvent(no.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(no.DESTROY,this._dispose,this)}}class sS{constructor(){this.syncConversationHandler=new oS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Zr}`);var nS={create:function(s){var n,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:iA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ca.has(EA))return Ca.get(EA);let RA=null;if(P)RA=P,RA._workflowManager&&ws.setInstance(RA._workflowManager),RA._pluginManager&&RA._pluginManager.installBuiltInPlugin(DB),P.isReady()&&((g=(n=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Vt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function ae(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${ae()+ae()}${ae()}${ae()}${ae()}${ae()}${ae()}${ae()}`}();fe.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:jm,version:Zr,proxyServer:iA}),ws.getInstance().init(),fe.message=new ZD,fe.user=new iN,fe.login=new Rh,fe.conversation=new sS,au.getInstance().installBuiltInPlugin(DB),RA=Cr.getInstance().exposeApiForClient(),RA._workflowManager=ws.getInstance(),RA._pluginManager=au.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=fe,JA=`instanceID:${kA} SDKAppID:${u} platform:${HA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;fe.ssoLog.info("sdkConstruct",JA)}return Ca.set(EA,RA),RA},TSignaling:qc,EVENT:Dr,VERSION:Zr,TYPES:Lo};return nS})}(z1)),z1.exports}var KoA=qoA();const ig=yW(KoA);var Z1={exports:{}},joA=Z1.exports,a8;function WoA(){return a8||(a8=1,function(t,i){(function(r,l){t.exports=l()})(joA,function(){function r(re,qe){if(!(re instanceof qe))throw new TypeError("Cannot call a class as a function")}function l(re,qe){for(var yt=0;yt"u"&&typeof uni.requireNativePlugin=="function",WA=TA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ue=(TA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||sA||mA||IA||cA||TA),Ce=U!==void 0&&(U.nativeModuleProxy!==void 0||U.ReactNative!==void 0),xe=sA?qq:mA?tt:IA?swan:cA?my:lA?wx:TA?uni:{},Qe=function(re){if(G(re)!=="object"||re===null)return!1;var qe=Object.getPrototypeOf(re);if(qe===null)return!0;for(var yt=qe;Object.getPrototypeOf(yt)!==null;)yt=Object.getPrototypeOf(yt);return qe===yt};function ut(re){if(re==null)return!0;if(typeof re=="boolean")return!1;if(typeof re=="number")return re===0;if(typeof re=="string"||typeof re=="function"||Array.isArray(re))return re.length===0;if(re instanceof Error)return re.message==="";if(Qe(re)){for(var qe in re)if(Object.prototype.hasOwnProperty.call(re,qe))return!1;return!0}return!1}var ft=function(){return I(function re(){r(this,re),this._n="WebRequest"},[{key:"request",value:function(re,qe){var yt=this,Me="".concat(this._n,".request"),Oe=re.downloadUrl||"",gt=(re.method||"PUT").toUpperCase(),Fi=re.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(Me," URL:").concat(Fi)),re.qs){var To=function(ki){var ns=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",jo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ut(ki)?"":Qe(ki)?Object.keys(ki).map(function(Ao){var Zt=encodeURIComponent(Ao)+jo;return Array.isArray(ki[Ao])?ki[Ao].map(function(oo){return Zt+encodeURIComponent(oo)}).join(ns):Zt+encodeURIComponent(ki[Ao])}).filter(Boolean).join(ns):void 0}(re.qs);To&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(To))}var io=new XMLHttpRequest;io.open(gt,Fi,!0),io.responseType=re.dataType||"text";var Eo=re.headers||{};if(re.uploadByIP&&(Eo=w(w({},Eo),{},{host:re.uploadIP})),!ut(Eo))for(var Vs in Eo)Eo.hasOwnProperty(Vs)&&Vs.toLowerCase()!=="content-length"&&Vs.toLowerCase()!=="user-agent"&&Vs.toLowerCase()!=="origin"&&Vs.toLowerCase()!=="host"&&io.setRequestHeader(Vs,Eo[Vs]);return io.onload=function(){if(io.status===200)qe(null,yt._xhrRes(io,yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),Eo));else{if(re.uploadIP&&re.url.indexOf(re.uploadIP)===-1)return re.url=function(ns,jo){return ns.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(jo,"/"))}(re.url,re.uploadIP),re.uploadByIP=!0,yt.request(re,qe);var ki={code:io.status,message:JSON.stringify(io.responseText)};qe(ki,yt._xhrRes(io,yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),Eo))}},io.onerror=function(ki){var ns=yt._xhrBody(io,Oe,re.uploadByIP&&re.uploadIP),jo={code:io.status,message:JSON.stringify(io.responseText)};ns||io.statusText||io.status!==0||(ki.message="CORS blocked or network error"),qe(jo,yt._xhrRes(io,ns)),jo=null},re.onProgress&&io.upload&&(io.upload.onprogress=function(ki){var ns=ki.total,jo=ki.loaded,Ao=Math.floor(100*jo/ns);re.onProgress({total:ns,loaded:jo,percent:(Ao>=100?100:Ao)/100})}),io.send(re.resources),io}},{key:"_xhrRes",value:function(re,qe){var yt={};return re.getAllResponseHeaders().trim().split(` -`).forEach(function(Me){if(Me){var Oe=Me.indexOf(":"),gt=Me.substr(0,Oe).trim().toLowerCase(),Fi=Me.substr(Oe+1).trim();yt[gt]=Fi}}),{statusCode:re.status,statusMessage:re.statusText,headers:yt,data:qe}}},{key:"_xhrBody",value:function(re,qe,yt){return re.status===200&&qe?{location:qe,uploadIP:yt}:{response:re.responseText,uploadIP:yt}}}])}(),je=["unknown","image","video","audio","log"],Mt=["name"],jt=function(){return I(function re(){r(this,re)},[{key:"request",value:function(re,qe){var yt=this,Me=re.resources,Oe=Me===void 0?"":Me,gt=re.headers,Fi=gt===void 0?{}:gt,To=re.url,io=re.downloadUrl,Eo=io===void 0?"":io,Vs=To,ki=null,ns=Eo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),jo=decodeURIComponent(ns[3]),Ao=jo.indexOf("?")>-1?jo.split("?")[0]:jo,Zt={key:re.fileKey?re.fileKey:Ao,success_action_status:200,"Content-Type":""},oo={};if(WA){var bi=To.split("?sign=");if(bi.length>1){var vs=bi[1];Vs="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(vs))),oo.sign=decodeURIComponent(vs),oo.signature=decodeURIComponent(vs)}}var HA={url:Vs,header:Fi,name:"file",filePath:Oe,formData:w(w({},Zt),oo),timeout:re.timeout||3e5};if(cA){var ce=HA;ce.name,HA=w(w({},function(Ve,Ot){if(Ve==null)return{};var nt,It,ei=function(be,Ze){if(be==null)return{};var wt={};for(var Nt in be)if({}.hasOwnProperty.call(be,Nt)){if(Ze.includes(Nt))continue;wt[Nt]=be[Nt]}return wt}(Ve,Ot);if(Object.getOwnPropertySymbols){var ti=Object.getOwnPropertySymbols(Ve);for(It=0;It=3e4&&(this.systemClockOffset=To-Fi,qe=!0)}else Math.floor(re.statusCode/100)===5&&(qe=!0)}return qe}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(Z1)),Z1.exports}var zoA=WoA();const ZoA=yW(zoA);/** +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:Dr,url:r})}send(r){var g,u;try{(g=this._worker)===null||g===void 0||g.postMessage({type:Us,data:r})}catch(E){(u=this._onSendFail)===null||u===void 0||u.call(this,E)}}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;if(this._worker){const M={[fs]:g,[as]:u,[wu]:E,[Wa]:m,[hs]:D};this._onSendFail=D,this._worker.onmessage=T=>{var P;const{type:W}=T?.data||{};typeof M[W]=="function"&&((P=M[W])===null||P===void 0||P.call(M,T?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class qI{}var es,eo=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return Gi?oi?my.getStorageSync({key:s}).data:Ao.getStorageSync(s):this._canUseLocalStorage()?localStorage.getItem(s):{}}set(s,r){const g=this._store.get(s)||{};r instanceof Map?this._store.set(s,r):this._store.set(s,Object.assign(Object.assign({},g),r))}setStorage(s,r){Gi?oi?my.setStorageSync({key:s,data:JSON.stringify(r)}):Ao.setStorageSync(s,JSON.stringify(r)):this._canUseLocalStorage()&&localStorage.setItem(s,JSON.stringify(r))}clear(s){typeof s=="string"?this._store.set(s,{}):this._store.clear()}clearLocalStorage(s){this._canUseLocalStorage()&&(typeof s=="string"?localStorage.setItem(s,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(r){return this._socket=Ao.connectSocket({url:r,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(r){var g;(g=this._socket)===null||g===void 0||g.send({data:r,fail:this._onSendFail})}bindSocketHandlers(r){const{onOpen:g,onMessage:u,onClose:E,onError:m,onSendFail:D}=r;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>u(M?.data)),this._socket.onError(()=>m),this._onSendFail=D)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(s){s[s.CONNECTED=0]="CONNECTED",s[s.CONNECTING=1]="CONNECTING",s[s.DISCONNECTED=2]="DISCONNECTED"})(es||(es={}));class ng{constructor(r){this._url="",this._readyState=es.DISCONNECTED,this._url=r,this._id=L(),this._emitter=new Pn,oi?this._socket=new pc:ct||Co||Dt||Ve||Ni||Pt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new qI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Ml,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this._readyState=es.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(r){this._readyState!==es.CONNECTED?this.reconnect():this._socket.send(r)}reconnect(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(r,g,u){this._emitter.on(r,g,u)}off(r,g,u){this._emitter.off(r,g,u)}isConnected(){return this._readyState===es.CONNECTED}disconnect(){this._readyState=es.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(r){this._readyState===es.CONNECTING&&(this._readyState=es.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:r}))}_onMessage(r){this._emitter.emit("message",r)}_onClose(r){this._readyState=es.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:r})}_onError(r){this._readyState=es.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:r})}_onSendFail(r){this._readyState=es.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:r})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const r=eo.get("cloudConfig")||{};return(n(r.isWorkerEnabled)||r.isWorkerEnabled==="1")&&Go}}const Dg={[gt.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[gt.KOREA]:[[3e7,4e7],[173e7,174e7]],[gt.GERMANY]:[[4e7,5e7],[174e7,175e7]],[gt.IND]:[[5e7,6e7],[175e7,176e7]],[gt.JPN]:[[6e7,7e7],[176e7,177e7]],[gt.USA]:[[7e7,8e7],[177e7,178e7]],[gt.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[gt.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(s){var r;if(!((r=eo.get("instance"))===null||r===void 0)&&r.oversea)return gt.OVERSEA;for(const g of Object.keys(Dg))for(const[u,E]of Dg[g])if(s>=u&&s`${oA}=${W[oA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Hs(s){const r=eo.get("instance"),{sdkAppId:g,testEnv:u,proxyServer:E}=r,m=ua(g);if(u)return Kn(dt.TEST[m].DEFAULT,{isBinary:s});if(!Rs(E))return Kn(E,{isBinary:s});const D=dt.PRODUCTION[m],M=zt&&D.ANYCAST,T=zt,P=!!D.BACKUP_CN;return Kn({[bo.INITIAL]:()=>(To=bo.DEFAULT,D.DEFAULT),[bo.DEFAULT]:()=>(To=bo.IPV6,D.IPV6),[bo.IPV6]:()=>(To=bo.BACKUP,D.BACKUP),[bo.BACKUP]:()=>T?(To=bo.BACKUP_WEB_ONLY,function(W){const oA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(oA))}(D.BACKUP_WEB_ONLY)):P?(To=bo.BACKUP_CN,D.BACKUP_CN):M?(To=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>P?(To=bo.BACKUP_CN,D.BACKUP_CN):M?(To=bo.ANYCAST,D.ANYCAST):D.DEFAULT,[bo.BACKUP_CN]:()=>(To=M?bo.ANYCAST:bo.DEFAULT,D[To]),[bo.ANYCAST]:()=>(To=bo.DEFAULT,D.ANYCAST="",D.DEFAULT)}[To](),{isBinary:s})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(s,r){const g=Date.now(),u=g-s;this._timeOffsetWithServer=r+u-g}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(s){const{id:r}=s;this.removeTask(r),this._tasks.push(s),this._taskMap.set(r,s),this._sort(),this._scheduleNextTask()}_createTask(s){const{id:r,callback:g,context:u,isOnce:E=!1,intervalMs:m=mc}=s,D=Math.max(m,mc);return{id:r,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:u,isOnce:E}}addTask(s){const r=this._createTask(s);this._addTaskToScheduler(r)}addOnceTask(s){const r=this._createTask(Object.assign(Object.assign({},s),{isOnce:!0}));this._addTaskToScheduler(r)}removeTask(s){const r=this._tasks.findIndex(g=>g.id===s);r>-1&&(this._tasks.splice(r,1),this._taskMap.delete(s),this._scheduleNextTask())}updateTaskInterval(s,r){const g=this._taskMap.get(s);g&&(g.intervalMs=r,g.nextExecuteTime=Date.now()+r,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((s,r)=>s.nextExecuteTime-r.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const s=this._tasks[0];if(s){const r=Math.max(0,s.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),r)}}_execute(){const s=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=s;){const r=this._tasks[0];try{r.context?r.callback.call(r.context):r.callback(),r.isOnce?this.removeTask(r.id):(r.nextExecuteTime=s+r.intervalMs,this._sort())}catch(g){console.warn(`Task ${r.id} execution failed:`,g),r.isOnce&&this.removeTask(r.id)}}this._scheduleNextTask()}};function Ga(s){const r=[];for(let g=0;g=55296&&u<=56319){const E=s.charCodeAt(++g)-56320+(u-55296<<10)+65536;r.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else u<=127?r.push(u):u<=2047?r.push(192|u>>6,128|63&u):r.push(224|u>>12,128|u>>6&63,128|63&u)}return new Uint8Array(r)}function In(s){const r=Array.isArray(s)?[]:Object.create(null);for(const g in s)Object.prototype.hasOwnProperty.call(s,g)&&_(g)&&s[g]!=null&&(s[g]===null||typeof s[g]!="object"?r[g]=s[g]:r[g]=In(s[g]));return r}function ys(s,r){if(BA.includes(s))return 0;const g=Ga(JSON.stringify(r));let u=4294967295;const{length:E}=g;for(let m=0;m>>=1:u=u>>>1^3988292384}return(4294967295^u)>>>0}function Ea(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",a2:D.a2Key||void 0,tinyid:D.tinyID||void 0,status_instid:D.statusInstanceId||0,sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.a2Key?void 0:D.userId,usersig:D.a2Key?void 0:D.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}}function yn(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}}let ba=L();function Sa(){return ba=ba<2415919103?ba+1:L(),ba}function $(){var s;const r=eo.get("login")||{},g=eo.get("instance")||{};return{sdk_type:30,sdk_app_id:g.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(r.tinyID),user_id:r.userId||((s=eo.get("webPush"))===null||s===void 0?void 0:s.userId),platform:VA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var j,vA=Object.freeze({__proto__:null,calcBodyCRC:ys,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:r,data:g}=s,u=function(m){const D=eo.get("login")||{},M=eo.get("instance")||{};return{servcmd:m,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:M.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:D.userId,usersig:D.userSig,status_instid:D.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:M.applicationID||0,seq:Sa(),cs:0}}(r),E=In(g);return u.cs=ys(r,E),{head:u,body:E}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(j||(j={}));const jA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class oe{constructor(r){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:g,eventType:u=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=r||{};this.eventType=u,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),Rs(M)||(this.uiPlatform=M)}setMoreMessage(r){this.moreMessage=`${this.moreMessage} ${r}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(r=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),r&&this._ssoLogModule.uploadSSOLogData())}setError(r){var g;return r instanceof Error?this._canSendLog?(!((g=eo.get("netWorkMonitor"))===null||g===void 0)&&g.isNetworkOnline&&(r.errorCode&&(this.code=r.errorCode),r.errorMessage&&this.setMoreMessage(r.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(r){return Object.keys(r).forEach(g=>{Object.keys(jA).includes(g)&&(this[g]=r[g])}),this}setSSOLogModule(r){this._ssoLogModule=r}_convertSSOLogDataKeyToServe(){const r={};return Object.keys(this).forEach(g=>{const u=g;jA[u]&&(r[jA[u]]=this[u])}),r}_getUiPlatform(){var r;const g=(r=eo.get("instance"))===null||r===void 0?void 0:r.scene;if(typeof g=="string"){const u=Number(g);return isNaN(u)?void 0:u}}_getSDKEdition(){var r;return(r=eo.get("instance"))===null||r===void 0?void 0:r.sdkEdition}}var ye;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(ye||(ye={}));var He=ye;const Pe=20,rt=6e4,ht=[4,5,6],_t="report-logger";var Vt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:me,maxCount:ae},single:{throttleTime:ZA,maxCount:KA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:_t,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:r=Pe,evt_rpt_waiting:g=rt,evt_rpt_level:u=ht,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=me,evt_rpt_global_throttle_count:M=ae,evt_rpt_single_throttle_time:T=ZA,evt_rpt_single_throttle_count:P=KA}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=r,this._reportLevel=u,this._tinyIdWhiteList=m.split(","),this._throttleConfig={global:{throttleTime:D,maxCount:M},single:{throttleTime:T,maxCount:P}}}createSSOLogData(s){const r=new oe(s);return r.setSSOLogModule(this),this._ssoLogMap.set(s.method,r),r}getSSOLogData(s){return this._ssoLogMap.get(s)||{}}pushToLogQueue(s){s&&(this._logQueue.push(s),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(s){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(s)&&(this._logLevel=s)}debug(s,r="",g){this._log(IA.DEBUG,s,r,g)}info(s,r="",g){this._log(IA.INFO,s,r,g)}warn(s,r="",g){this._log(IA.WARN,s,r,g)}error(s,r="",g){this._log(IA.ERROR,s,r,g)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const s=this._logQueue.slice();this._logQueue=[];try{const r=this._filterLogs(s);if(r.length===0)return void(this._lastReportAt=Date.now());const g={Header:$(),Event:r};Rs(g.Header.user_id)||(yield function(u){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:u}),D=`${m.head.seq}${E}`;return Se.sendPacket(m,{requestId:D})}(g))}catch(r){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",en(r))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(s){this._logQueue=s.concat(this._logQueue);const r=this._logQueue.length-200;r>0&&(this._logQueue.splice(0,r),this.debug("uploadSSOLogData",`log queue overflow, dropped ${r} oldest logs`))}_savePlatFormInfo(){var s,r;if(ct){const g=(r=(s=wx.getAccountInfoSync)===null||s===void 0?void 0:s.call(wx))===null||r===void 0?void 0:r.miniProgram;if(g){const{appId:u,envVersion:E}=g;eo.set("instance",{appId:u,envVersion:E})}}else zt&&eo.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:r}=eo.get("login")||{},{sdkAppId:g}=eo.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(r)?[]:s.filter(u=>this._reportLevel.includes(u.level))}_checkThrottle(s){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(s)}_checkGlobalThrottle(){const s=Date.now();if(s-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=s;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(s){const r=Date.now(),g=this._singleThrottleMap.get(s);return g?r-g.startTime>=this._throttleConfig.single.throttleTime?(g.count=1,g.startTime=r,!1):g.count>=this._throttleConfig.single.maxCount||(g.count++,!1):(this._singleThrottleMap.set(s,{count:1,startTime:r}),!1)}_shouldLog(s){return s>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(s){return this._reportLevel.includes(HA[s])}_formatLog(s,r,g,u){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return ve||Gi?[`${gA} [${m}] ${D} [${r}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",gA,"",`[${m}] ${D} [${r}] ${g} params: ${en(u)}`]}_log(s,r,g,u){if(this._shouldLog(s)){const E=this._formatLog(s,r,g,u);RA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(r,g,u);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},u),{method:r})).end()}}_getThrottleKey(s,r,g){const u=`${s}${r}${en(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Ga(JSON.stringify(u));let m=4294967295;const{length:D}=E;for(let M=0;M>>=1:m=m>>>1^3988292384}return`${(4294967295^m)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(_t),gn.unSubscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const ui=15e3,It="Channel",Yt="channel_schedule_task",qi="channel_reconnect_task",Wi="connected",qs="connecting",vi="disconnected",zo=1e3,Mg="network_status_change",ar="activity_status_change",Sr="send_fail",Yn="reconnect_failed",vl="socket_error",Ks="socket_close";function gI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Wg(s){return Wg=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(r){return typeof r}:function(r){return r&&typeof Symbol=="function"&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r},Wg(s)}function fc(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _u,Ma={exports:{}},Rl=(_u||(_u=1,function(s){s.exports=function r(g,u,E){function m(T,P){if(!u[T]){if(!g[T]){if(!P&&fc)return fc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var oA=u[T]={exports:{}};g[T][0].call(oA.exports,function(EA){return m(g[T][1][EA]||EA)},oA,oA.exports,r,g,u,E)}return u[T].exports}for(var D=fc,M=0;M>>6:(EA<65536?oA[xA++]=224|EA>>>12:(oA[xA++]=240|EA>>>18,oA[xA++]=128|EA>>>12&63),oA[xA++]=128|EA>>>6&63),oA[xA++]=128|63&EA);return oA},u.buf2binstring=function(W){return P(W,W.length)},u.binstring2buf=function(W){for(var oA=new E.Buf8(W.length),EA=0,wA=oA.length;EA>10&1023,SA[wA++]=56320|1023&kA)}return P(SA,wA)},u.utf8border=function(W,oA){var EA;for((oA=oA||W.length)>W.length&&(oA=W.length),EA=oA-1;0<=EA&&(192&W[EA])==128;)EA--;return EA<0||EA===0?oA:EA+M[W[EA]]>oA?EA:oA}},{"./common":1}],3:[function(r,g,u){g.exports=function(E,m,D,M){for(var T=65535&E,P=E>>>16&65535,W=0;D!==0;){for(D-=W=2e3>>1:m>>>1;D[M]=m}return D}();g.exports=function(m,D,M,T){var P=E,W=T+M;m^=-1;for(var oA=T;oA>>8^P[255&(m^D[oA])];return-1^m}},{}],6:[function(r,g,u){g.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(r,g,u){g.exports=function(E,m){var D,M,T,P,W,oA,EA,wA,kA,xA,LA,SA,OA,qA,Ie,le,bi,ki,Ot,Li,cs,Re,St,UA,ai;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ai=E.output,W=P-(m-E.avail_out),oA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,xA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,qA=D.lencode,Ie=D.distcode,le=(1<>>=Ot=ki>>>24,OA-=Ot,(Ot=ki>>>16&255)==0)ai[P++]=65535&ki;else{if(!(16&Ot)){if(!(64&Ot)){ki=qA[(65535&ki)+(SA&(1<>>=Ot,OA-=Ot),OA<15&&(SA+=UA[M++]<>>=Ot=ki>>>24,OA-=Ot,!(16&(Ot=ki>>>16&255))){if(!(64&Ot)){ki=Ie[(65535&ki)+(SA&(1<>>=Ot,OA-=Ot,(Ot=P-W)>3,SA&=(1<<(OA-=Li<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(Re>>>8&65280)+((65280&Re)<<8)+((255&Re)<<24)}function SA(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new E.Buf16(320),this.work=new E.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function OA(Re){var St;return Re&&Re.state?(St=Re.state,Re.total_in=Re.total_out=St.total=0,Re.msg="",St.wrap&&(Re.adler=1&St.wrap),St.mode=wA,St.last=0,St.havedict=0,St.dmax=32768,St.head=null,St.hold=0,St.bits=0,St.lencode=St.lendyn=new E.Buf32(kA),St.distcode=St.distdyn=new E.Buf32(xA),St.sane=1,St.back=-1,oA):EA}function qA(Re){var St;return Re&&Re.state?((St=Re.state).wsize=0,St.whave=0,St.wnext=0,OA(Re)):EA}function Ie(Re,St){var UA,ai;return Re&&Re.state?(ai=Re.state,St<0?(UA=0,St=-St):(UA=1+(St>>4),St<48&&(St&=15)),St&&(St<8||15=Ui.wsize?(E.arraySet(Ui.window,St,UA-Ui.wsize,Ui.wsize,0),Ui.wnext=0,Ui.whave=Ui.wsize):(ai<(_s=Ui.wsize-Ui.wnext)&&(_s=ai),E.arraySet(Ui.window,St,UA-ai,_s,Ui.wnext),(ai-=_s)?(E.arraySet(Ui.window,St,UA-ai,ai,0),Ui.wnext=ai,Ui.whave=Ui.wsize):(Ui.wnext+=_s,Ui.wnext===Ui.wsize&&(Ui.wnext=0),Ui.whave>>8&255,UA.check=D(UA.check,dg,2,0),Gt=Nt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&Nt)<<8)+(Nt>>8))%31){Re.msg="incorrect header check",UA.mode=30;break}if((15&Nt)!=8){Re.msg="unknown compression method",UA.mode=30;break}if(Gt-=4,Va=8+(15&(Nt>>>=4)),UA.wbits===0)UA.wbits=Va;else if(Va>UA.wbits){Re.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(dg[0]=255&Nt,dg[1]=Nt>>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0,UA.mode=3;case 3:for(;Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>8&255,dg[2]=Nt>>>16&255,dg[3]=Nt>>>24&255,UA.check=D(UA.check,dg,4,0)),Gt=Nt=0,UA.mode=4;case 4:for(;Gt<16;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>8),512&UA.flags&&(dg[0]=255&Nt,dg[1]=Nt>>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;Gt<16;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>8&255,UA.check=D(UA.check,dg,2,0)),Gt=Nt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(Vi<(Qo=UA.length)&&(Qo=Vi),Qo&&(UA.head&&(Va=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ai,Ui,Qo,Va)),512&UA.flags&&(UA.check=D(UA.check,ai,Qo,Ui)),Vi-=Qo,Ui+=Qo,UA.length-=Qo),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(Vi===0)break A;for(Qo=0;Va=ai[Ui+Qo++],UA.head&&Va&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Va)),Va&&Qo>9&1,UA.head.done=!0),Re.adler=UA.check=0,UA.mode=12;break;case 10:for(;Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=7&Gt,Gt-=7&Gt,UA.mode=27;break}for(;Gt<3;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=1)){case 0:UA.mode=14;break;case 1:if(Li(UA),UA.mode=20,St!==6)break;Nt>>>=2,Gt-=2;break A;case 2:UA.mode=17;break;case 3:Re.msg="invalid block type",UA.mode=30}Nt>>>=2,Gt-=2;break;case 14:for(Nt>>>=7&Gt,Gt-=7≫Gt<32;){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>16^65535)){Re.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&Nt,Gt=Nt=0,UA.mode=15,St===6)break A;case 15:UA.mode=16;case 16:if(Qo=UA.length){if(Vi>>=5,Gt-=5,UA.ndist=1+(31&Nt),Nt>>>=5,Gt-=5,UA.ncode=4+(15&Nt),Nt>>>=4,Gt-=4,286>>=3,Gt-=3}for(;UA.have<19;)UA.lens[cS[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,TI={bits:UA.lenbits},Vl=T(0,UA.lens,0,19,UA.lencode,0,UA.work,TI),UA.lenbits=TI.bits,Vl){Re.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=Tr,Gt-=Tr,UA.lens[UA.have++]=_I;else{if(_I===16){for(oE=Tr+2;Gt>>=Tr,Gt-=Tr,UA.have===0){Re.msg="invalid bit length repeat",UA.mode=30;break}Va=UA.lens[UA.have-1],Qo=3+(3&Nt),Nt>>>=2,Gt-=2}else if(_I===17){for(oE=Tr+3;Gt>>=Tr)),Nt>>>=3,Gt-=3}else{for(oE=Tr+7;Gt>>=Tr)),Nt>>>=7,Gt-=7}if(UA.have+Qo>UA.nlen+UA.ndist){Re.msg="invalid bit length repeat",UA.mode=30;break}for(;Qo--;)UA.lens[UA.have++]=Va}}if(UA.mode===30)break;if(UA.lens[256]===0){Re.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,TI={bits:UA.lenbits},Vl=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,TI),UA.lenbits=TI.bits,Vl){Re.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,TI={bits:UA.distbits},Vl=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,TI),UA.distbits=TI.bits,Vl){Re.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,St===6)break A;case 20:UA.mode=21;case 21:if(6<=Vi&&258<=Ir){Re.next_out=Or,Re.avail_out=Ir,Re.next_in=Ui,Re.avail_in=Vi,UA.hold=Nt,UA.bits=Gt,M(Re,ln),Or=Re.next_out,_s=Re.output,Ir=Re.avail_out,Ui=Re.next_in,ai=Re.input,Vi=Re.avail_in,Nt=UA.hold,Gt=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;xg=(Yg=UA.lencode[Nt&(1<>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>ac)])>>>16&255,_I=65535&Yg,!(ac+(Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=ac,Gt-=ac,UA.back+=ac}if(Nt>>>=Tr,Gt-=Tr,UA.back+=Tr,UA.length=_I,xg===0){UA.mode=26;break}if(32&xg){UA.back=-1,UA.mode=12;break}if(64&xg){Re.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&xg,UA.mode=22;case 22:if(UA.extra){for(oE=UA.extra;Gt>>=UA.extra,Gt-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;xg=(Yg=UA.distcode[Nt&(1<>>16&255,_I=65535&Yg,!((Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>ac)])>>>16&255,_I=65535&Yg,!(ac+(Tr=Yg>>>24)<=Gt);){if(Vi===0)break A;Vi--,Nt+=ai[Ui++]<>>=ac,Gt-=ac,UA.back+=ac}if(Nt>>>=Tr,Gt-=Tr,UA.back+=Tr,64&xg){Re.msg="invalid distance code",UA.mode=30;break}UA.offset=_I,UA.extra=15&xg,UA.mode=24;case 24:if(UA.extra){for(oE=UA.extra;Gt>>=UA.extra,Gt-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){Re.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(Ir===0)break A;if(Qo=ln-Ir,UA.offset>Qo){if((Qo=UA.offset-Qo)>UA.whave&&UA.sane){Re.msg="invalid distance too far back",UA.mode=30;break}Qo>UA.wnext?(Qo-=UA.wnext,Il=UA.wsize-Qo):Il=UA.wnext-Qo,Qo>UA.length&&(Qo=UA.length),GC=UA.window}else GC=_s,Il=Or-UA.offset,Qo=UA.length;for(Irbi?(Ot=Il[GC+xA[St]],Li=Gt[iE+xA[St]]):(Ot=96,Li=0),SA=1<>Or)+(OA-=SA)]=ki<<24|Ot<<16|Li,OA!==0;);for(SA=1<>=1;if(SA!==0?(Nt&=SA-1,Nt+=SA):Nt=0,St++,--ln[Re]==0){if(Re===ai)break;Re=W[oA+xA[St]]}if(_s{const M=new Uint8Array(D).slice(4);let T;try{T=Rl.inflate(M,{to:"string"})}catch(P){console.error("inflate error",P)}return T})(s.data):function(D){const M=new Uint8Array(D);let T="",P=0;const{length:W}=M;for(;P0)for(let kA=0;kA{var u;const{uplinkData:E,canResend:m,resolve:D,reject:M,timeout:T}=r;if(m){this._pendingRequests.set(g,{resolve:D,reject:M,timestamp:Date.now(),uplinkData:E,timeout:T,canResend:m});const P=this._isBinarySupported?Ga(E).buffer:E;(u=this._socketAdapter)===null||u===void 0||u.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:r,event:g={}}=s||{};this._connectionId=r,this._connectionEstablishedTime=Date.now();const u=Date.now()-this._connectionStartTime,E=`${It}.onConnect cost:${u} ms. socketID:${r} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${It}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(He.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Wi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const r=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:s}});this.sendPacket(r)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var s;return((s=this._socketAdapter)===null||s===void 0?void 0:s.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var s;const r=Ea({servcmd:"heartbeat.alive",data:{}});try{const g=`${r.head.seq}${r.head.servcmd}`;yield this.sendPacket(r,{requestId:g,timeout:3e3})}catch(g){const u=(s=eo.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${It}.sendHeartbeat failed. isNetWorkOnline:${u} error: ${en(g)}`;this._ssoLog({method:"sendHeartbeatError",message:E}),this._handleConnectStateChange({state:vi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=Co?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const r=`${It}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:r});const{isNetworkOnline:g,networkType:u}=s;g&&u!=="none"?this._handleConnectStateChange({state:Wi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:vi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const s=eo.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:r,shouldAttemptReconnect:g,shouldEmitEvent:u,reason:E}=s,m=`${It}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${u} reason: ${E}`;this._currentConnectState!==r&&(this._ssoLog({method:"handleConnectStateChange",message:m}),u&&(Vt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${r}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:r}}),this._currentConnectState=r,r===vi&&gn.emitInnerEvent(He.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:qi,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var r,g;const u=(g=(r=this._socketAdapter)===null||r===void 0?void 0:r._ws)===null||g===void 0?void 0:g.readyState,E=`${It}.activityStatusChange ${JSON.stringify(s)} readyState: ${u}`;Vt.debug("activityStatusChange",E),u===3&&this._handleConnectStateChange({state:vi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:ar})}_resetReconnectDelay(){var s;Vt.debug(`${It}._resetReconnectDelay`),fn.removeTask(qi);const r=(s=eo.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?zo:1e3}_scheduleReconnectWithBackoff(){var s;const r=(s=eo.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=r?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),u=`${It}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Vt.debug(u),this.reconnect(),fn.updateTaskInterval(qi,this._intendedDelay)}_ssoLog(s){const{method:r,message:g}=s;Vt.info(r,g)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(s){mA(this,void 0,void 0,function*(){const r=s.split("/")[2];if(!r.startsWith("ws"))return;const g=`https://${r}/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:g,data:{}})}catch(u){Vt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${u.message}`)}})}(this._url),function(s){mA(this,void 0,void 0,function*(){const r=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${s.slice(s.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:r,data:{}})}catch(g){Vt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,r]of this._pendingRequests.entries()){const{reject:g,timestamp:u,timeout:E}=r;Date.now()-u>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:mr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=eo.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const r=ds();if((oi||ct&&r==="windows"||ks)&&(this._isBinarySupported=!1),Co){const{uniRuntimeVersion:g=""}=Ao.getSystemInfoSync();(function(u){const E=u.split(".").map(Number),[m=0,D=0,M=0]=E;return m>2||!(m<2)&&(D>2||!(D<2)&&M>=6)})(g)||(this._isBinarySupported=!1)}}_isCompressedData(s){const r=new Uint8Array(s);return r[0]===67&&r[1]===79&&r[2]===77&&r[3]===80}};const De={init:function(s){eo.set("instance",s),Se.init()},destroy:function(){Se.dispose(),eo.clear(),fn.dispose()},notificationCenter:gn,channel:Se,store:eo,ssoLog:Vt,utils:yg,common:vA,constants:lt},vg=s=>typeof s=="function";function rg(s,r,g){const u=g||[];if(!s||!r)return!1;const E=Object.keys(s).filter(D=>!u.includes(D)),m=Object.keys(r).filter(D=>!u.includes(D));return E.length===m.length&&E.every(D=>!!r.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?rg(s[D],r[D],g):s[D]===r[D]))}var Rg;(function(s){s.SDK_READY="sdkStateReady",s.SDK_NOT_READY="sdkStateNotReady",s.SDK_DESTROY="sdkDestroy",s.MESSAGE_RECEIVED="onMessageReceived",s.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",s.MESSAGE_MODIFIED="onMessageModified",s.MESSAGE_REVOKED="onMessageRevoked",s.MESSAGE_READ_BY_PEER="onMessageReadByPeer",s.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",s.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",s.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",s.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",s.CONVERSATION_LIST_UPDATED="onConversationListUpdated",s.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",s.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",s.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",s.GROUP_LIST_UPDATED="onGroupListUpdated",s.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",s.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",s.TOPIC_CREATED="onTopicCreated",s.TOPIC_DELETED="onTopicDeleted",s.TOPIC_UPDATED="onTopicUpdated",s.PROFILE_UPDATED="onProfileUpdated",s.USER_STATUS_UPDATED="onUserStatusUpdated",s.BLACKLIST_UPDATED="blacklistUpdated",s.FRIEND_LIST_UPDATED="onFriendListUpdated",s.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",s.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",s.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",s.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",s.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",s.KICKED_OUT="kickedOut",s.ERROR="error",s.NET_STATE_CHANGE="netStateChange",s.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",s.SERVER_CONFIG_UPDATED="onServerConfigUpdated",s.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",s.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",s.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",s.RICH_STATUS_CHANGED="onRichStatusChanged"})(Rg||(Rg={}));var Dn,Mr=Rg;(function(s){s.LOGOUT="logout",s.DESTROY="destroy",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.PROFILE_UPDATE="profile_updated",s.ERROR="error",s.RECONNECTED="reconnected",s.FORCE_OFFLINE="im_open_status.stat_forceoffline",s.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",s.OVERLOAD_PUSH="OverLoadPush.notify2",s.NEW_MESSAGE="new_message",s.MESSAGE_PUSH="im_open_push.msg_push",s.MESSAGE_DELETED="message_deleted",s.MESSAGE_REVOKED="message_revoked",s.MESSAGE_MODIFIED="message_modified",s.SOCKET_DISCONNECTED="socket_disconnected",s.CONVERSATION_UPDATED="conversation_updated",s.TOPIC_MESSAGE_DELETED="topic_message_deleted",s.TOPIC_MESSAGE_REVOKED="topic_message_revoked",s.TOPIC_MESSAGE_MODIFIED="topic_message_modified",s.TOPIC_NEW_MESSAGE="topic_new_message",s.QUALITY_STAT="quality_stat",s.SYNC_CONVERSATION_LIST="sync_conversation_list",s.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Dn||(Dn={}));var Ei,ro=Dn;(function(s){s.NEW_INVITATION_RECEIVED="newInvitationReceived",s.INVITEE_ACCEPTED="ts_invitee_accepted",s.INVITEE_REJECTED="ts_invitee_rejected",s.INVITATION_CANCELLED="ts_invitation_cancelled",s.INVITATION_TIMEOUT="ts_invitation_timeout",s.INVITATION_MODIFIED="ts_invitation_modified"})(Ei||(Ei={}));var qc=Ei;const zg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),wg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var Yr;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Yr||(Yr={}));const yc={modify:ro.MESSAGE_MODIFIED,delete:ro.MESSAGE_DELETED,revoke:ro.MESSAGE_REVOKED};var Kc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Kc||(Kc={}));const ag=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},wg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:Yr,Direction:Kc}),Tu={[yc.modify]:ro.TOPIC_MESSAGE_MODIFIED,[yc.delete]:ro.TOPIC_MESSAGE_DELETED,[yc.revoke]:ro.TOPIC_MESSAGE_REVOKED},DE={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},_g=Object.assign({},DE),ka={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},Dc=Object.assign(Object.assign(Object.assign(Object.assign({},ka),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),SE=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),La={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},na={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},Tg={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},cI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},La),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:na,GROUP_TIPS_OPERATION_TYPE:Tg}),Bs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Uo=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),ag),_g),Dc),SE),cI),Bs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),da={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},gr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Jt={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Wt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Ng={[Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Wt.USER_STATUS_UPDATE},{stepId:Wt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Wt.UNREAD_MESSAGE_SYNC,dependency:Wt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Wt.CONVERSATION_RECOVER},{stepId:Wt.HISTORY_MESSAGE_RECOVER,dependency:Wt.CONVERSATION_RECOVER},{stepId:Wt.BLACKLIST_RECOVER},{stepId:Wt.FRIEND_RECOVER},{stepId:Wt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Wt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Wt.HISTORY_MESSAGE_RECOVER},{stepId:Wt.GROUP_TIPS_RECOVER,dependency:Wt.HISTORY_MESSAGE_RECOVER},{stepId:Wt.TOPIC_REQUEST_INFO_RESET},{stepId:Wt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_RECOVER]},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Wt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Wt.CONVERSATION_RECOVER},{stepId:Wt.STREAM_MESSAGE_RECOVER}],[Jt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Wt.COMMERCIAL_CONFIG_UPDATE},{stepId:Wt.CLOUD_CONFIG_SYNC},{stepId:Wt.USER_PROFILE_SYNC},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Wt.GROUP_LIST_SYNC},{stepId:Wt.CONVERSATION_LIST_SYNC},{stepId:Wt.SIGNALING_MESSAGE_RECOVER,dependency:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC]},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC,Wt.CONVERSATION_LIST_SYNC]},{stepId:Wt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Wt.GROUP_LIST_SYNC,Wt.CONVERSATION_LIST_SYNC]},{stepId:Wt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Wt.CONVERSATION_GROUP_UPDATE,dependency:[Wt.CONVERSATION_LIST_SYNC,Wt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Wt.QUALITY_REPORT}],[Jt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.UNREAD_MESSAGE_SYNC},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_C2C_NEW_MESSAGE},{stepId:Wt.EMIT_C2C_MESSAGE_EVENT,dependency:[Wt.HANDLE_C2C_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Wt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Wt.UNREAD_MESSAGE_SYNC]}],[Jt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Wt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Wt.HANDLE_GROUP_NEW_MESSAGE,Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Jt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Wt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Wt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Wt.EMIT_GROUP_TIPS_EVENT,dependency:[Wt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Wt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},lI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},cr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},KI=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var za=Object.freeze({__proto__:null,ERROR_CODE:da,InnerEvent:ro,NEED_LOG_API:KI,OuterConstant:Uo,OuterEvent:Mr,PUSH:Bs,QUALITY_METRICS:lI,SDK_EDITION:gr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:cr,SignalingEvent:qc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ng,WORKFLOW_NAME:Jt,WORKFLOW_STEP:Wt}),ra,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(ra||(ra={})),function(s){s[s.multipleAccount=1]="multipleAccount",s[s.multipleDevice=2]="multipleDevice",s[s.restApi=3]="restApi"}(un||(un={})),function(s){s[s.multipleDevice=3002]="multipleDevice",s[s.multipleAccount=3003]="multipleAccount",s[s.usersigExpired=70001]="usersigExpired",s[s.restApi=20002]="restApi"}(Sn||(Sn={}));const Nu={[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[Sn.multipleAccount]:"multipleAccount",[Sn.multipleDevice]:"multipleDevice",[Sn.restApi]:"REST_API_Kick",[Sn.usersigExpired]:"userSigExpired"},Gg="login_online_presence_task",{ERROR:Ua,DESTROY:jc,FORCE_OFFLINE:jI}=ro,{KICKED_OUT_MULT_ACCOUNT:ME,KICKED_OUT_MULT_DEVICE:II,KICKED_OUT_REST_API:Gu,ACCOUNT_A2KEY_EXPIRED:wl,MSG_A2KEY_EXPIRED:Sc}=da;class bu{init(){const{notificationCenter:r}=De;r.subscribeInnerEvent(jI,this._handleForceOfflineFromServerPush,this),r.subscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ua,wl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),r.subscribeInnerEvent(Ua,ME,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ua,II,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(Ua,Gu,this._handleForceOfflineFromResponse,this),r.subscribeInnerEvent(jc,this._dispose,this)}_handleForceOfflineFromServerPush(r){var g;if(((g=De.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:u=[]}=r?.body||{};this._extractKickedOutMessages(u).forEach(E=>{const{KickoutMsgNotify:{KickType:m,NewInstInfo:D,Instid:M}}=E;this._isCurrentInstanceKickedOut(M)&&this._processKickedOutReasonInfo({kickedOutReasonCode:m,newInstanceInfo:D})})}}_extractKickedOutMessages(r){return r.reduce((g,u)=>[...g,...u.C2cNotifyMsgArray||[]],[]).filter(g=>{var u;return this._isKickedOut((u=g?.KickoutMsgNotify)===null||u===void 0?void 0:u.KickType)})}_handleForceOfflineFromResponse(r){const{errorCode:g}=r;this._processKickedOutReasonInfo({kickedOutReasonCode:g})}_processKickedOutReasonInfo(r){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:g}=r,{ssoLog:u,utils:{safeStringify:E}}=De;try{this._logKickedOutEvent(r),this._shouldLogoutAfterKickedOut(g)?yield De.login.loginAction.logout(ra.KICKED_OUT):De.login.loginAction.handleLogoutCompleted()}catch(m){u.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{De.notificationCenter.emitOuterEvent(Mr.KICKED_OUT,{data:{type:Nu[g]},name:Mr.KICKED_OUT})}})}_logKickedOutEvent(r){const{kickedOutReasonCode:g,newInstanceInfo:u={}}=r,E=`type:${Nu[g]} newInstanceInfo: ${JSON.stringify(u)}`;De.ssoLog.warn("kickedOut",E)}_isKickedOut(r){return[un.multipleAccount,un.multipleDevice,un.restApi].includes(r)}_isChatLoginEvent(r){const{requestHead:g}=r||{};return g?.idtype!==1}_shouldLogoutAfterKickedOut(r){return![Sn.usersigExpired,un.restApi].includes(r)}_isCurrentInstanceKickedOut(r){const{isLoggedIn:g,statusInstanceId:u}=De.store.get("login")||{};return g===!0&&r===u}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(jI,this._handleForceOfflineFromServerPush,this),r.unSubscribeInnerEvent(Ua,wl,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,Sc,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,ME,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,II,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(Ua,Gu,this._handleForceOfflineFromResponse,this),r.unSubscribeInnerEvent(jc,this._dispose,this)}}function ku(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.wslogin",g=De.common.generateProtocolData({servcmd:r,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),u=`${g.head.seq}${r}`,E=yield De.channel.sendPacket(g,{timeout:9e4,requestId:u});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:oA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:xA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:oA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:xA}}})}function _l(){const{store:s}=De;return ua(s.get("instance").sdkAppId)!==gt.CHINA}function rs(s){var r;try{const g=eo.getStorage("errorMessage");if(!s||!g)return"";const u=((r=JSON.parse(g))===null||r===void 0?void 0:r.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=_l()?`${E}_en`:`${E}_cn`;let T=u[u[M]?M:E]||"";return T&&(m&&(T=T.replace("$replacement1",m)),D&&(T=T.replace("$replacement2",D))),T}catch(g){return console.warn("Error parsing stored error messages:",g),""}}class gs extends Error{constructor(r={}){r.code=r.code||r.errorCode;let{functionName:g="Unknown",code:u,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=r;M=(u?rs(r):"")||M||E;let T=u?`${g} failed. error: {"message": ${M}, "code": ${u}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=u,this.errorCode=u,this.errorMessage=M,this.message=T,this.data=m}}function ud(s,r){var g;if(s&&((g=De.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new gs({code:da.USER_NOT_LOGGED_IN,functionName:r})}function uI(s,r,g){if(Array.isArray(s))for(let u=0;u{return P===(W=u,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=u;E.apply(m,[g])})}(s)}function Mc(s,r){vE.push({interceptor:s,context:r})}function Wc(s){const{params:r,auth:g}=s;r&&typeof r=="object"&&Object.assign(Tl,r),g&&typeof g=="object"&&Object.assign(Ed,g)}function tn(s){return De.store.get("commercialConfig").get(s)}class ws{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(r,g)=>{const u=Date.now();g?(this._stepStartTimes.set(`${r}-${g}`,u),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} started at ${new Date(u).toISOString()}`)):(this._workflowStartTimes.set(r,u),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] started at ${new Date(u).toISOString()}`))},success:(r,g)=>{const u=Date.now();if(g){const E=this._stepStartTimes.get(`${r}-${g}`),m=E?u-E:0;this._stepStartTimes.delete(`${r}-${g}`),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] Step ${g} completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(r),m=E?u-E:0;this._workflowStartTimes.delete(r),De.ssoLog.debug("_executeWorkflowStep",`[Workflow ${r}] completed successfully at ${new Date(u).toISOString()} (${m}ms)`)}},error:(r,g,u)=>{const{ssoLog:E,utils:{safeStringify:m}}=De,D=Date.now();if(g){const M=this._stepStartTimes.get(`${r}-${g}`),T=M?D-M:0;this._stepStartTimes.delete(`${r}-${g}`),E.error("_executeWorkflowStep",`[Workflow ${r}] Step ${g} failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}else{const M=this._workflowStartTimes.get(r),T=M?D-M:0;this._workflowStartTimes.delete(r),E.error("_executeWorkflowStep",`[Workflow ${r}] failed at ${new Date(D).toISOString()} (${T}ms) ${m(u)}`,{error:u})}}}}static getInstance(){return ws._instance||(ws._instance=new ws),ws._instance}static setInstance(r){ws._instance=r}init(){this._initializeWorkflows()}registerWorkflowStep(r,g,u,E){if(!this._handlers.has(r))return void De.ssoLog.debug("registerWorkflowStep",`Workflow '${r}' not defined in core`);if(!Ng[r].find(D=>D.stepId===g))return void De.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${r}'`);const m=this._handlers.get(r);m.has(g)||m.set(g,E?u.bind(E):u)}executeWorkflow(r,g){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(r))return;De.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Started execution at ${new Date().toISOString()}`);const u=Ng[r],E={},m={cancelled:!1};this._activeWorkflows.set(r,{cancelToken:m});try{const D=new Map;u.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:r,pendingSteps:new Set(u.map(T=>T.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:D,stepResults:E,data:g,cancelToken:m};yield new Promise((T,P)=>{const W=()=>{if(m.cancelled)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:r}).filter(oA=>!M.runningSteps.has(oA)).forEach(oA=>{M.completedSteps.has(oA)||M.runningSteps.has(oA)||this._executeWorkflowStep(oA,M,{onComplete:()=>{if(M.pendingSteps.size===0)return void T();this._getExecutableSteps({pendingSteps:M.pendingSteps,completedSteps:M.completedSteps,stepMap:M.stepMap,workflowName:r}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(De.ssoLog.debug("executeWorkflow",`Workflow ${r} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),De.ssoLog.debug("executeWorkflow",`[Workflow ${r}] Completed execution at ${new Date().toISOString()}`)}catch(D){De.ssoLog.error("executeWorkflow",`[Workflow ${r}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(r)}})}_executeWorkflowStep(r,g,u){return mA(this,void 0,void 0,function*(){const{workflowName:E,runningSteps:m,stepMap:D,stepResults:M,data:T}=g;m.add(r),this._logWorkflowExecution(E,r,"start");try{const P=D.get(r);let W=null;P?.dependency&&(c(P.dependency)?W=M[P.dependency]:Array.isArray(P.dependency)&&(W={},P.dependency.forEach(EA=>{W[EA]=M[EA]})));const oA=this._handlers.get(E).get(r);if(oA){const EA=yield Promise.resolve(oA({data:T,result:W}));M[r]=EA,this._logWorkflowExecution(E,r,"success")}g.completedSteps.add(r)}catch(P){const W=`[Workflow].${E}.${r}`,{errorCode:oA,errorInfo:EA=`${W} failed`}=P||{},wA=new gs({functionName:W,code:oA,message:EA});De.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,r,"error",P),u.onError(P)}finally{m.delete(r),g.pendingSteps.delete(r),u.onStepComplete(),u.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ng).forEach(r=>{this._handlers.has(r)||this._handlers.set(r,new Map)})}_cancelWorkFlow(r){const g=this._activeWorkflows.get(r);if(!g)return;const{cancelToken:u}=g;u.cancelled=!0,this._activeWorkflows.delete(r)}_cancelAllWorkflows(){Object.keys(Ng).forEach(r=>{this._cancelWorkFlow(r)})}_validateWorkflow(r){return Ng[r]?!!this._handlers.get(r):!1}_getExecutableSteps(r){const{pendingSteps:g,completedSteps:u,stepMap:E,workflowName:m}=r;return Array.from(g).filter(D=>{const M=E.get(D)||{},{dependency:T,skipIfDependencyMissing:P=!0}=M;if(!T)return!0;if(c(T))return this._isStepRegistered({workflowName:m,stepId:T})?u.has(T):!P;if(C(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!u.has(W))return!1;return!0}return!1})}_isStepRegistered(r){var g;const{workflowName:u,stepId:E}=r;return(g=this._handlers.get(u))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(r,g,u,E){this._logHandlers[u](r,g)}}const Ca=new Map,$r=({type:s,groupID:r})=>s===Uo.GRP_COMMUNITY||`${r}`.startsWith(na.COMMUNITY)&&!`${r}`.includes(na.TOPIC),zc=(s="")=>{const r=s.startsWith("GROUP")?s.replace("GROUP",""):s;return r.startsWith(na.COMMUNITY)&&`${r}`.includes(na.TOPIC)},dd="openim",Zg="million_group_open_http_svc";function gg(s){return mA(this,void 0,void 0,function*(){const{servcmd:r,data:g}=function(m){const{data:D}=m;return RE(D)||Xg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Xg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:oA=""}=W;const EA=oA;return[oA]=EA.split(na.TOPIC),{servcmd:jn(P),data:Object.assign(Object.assign({},W),{GroupId:oA,TopicId:EA})}}(m):(RE(M)&&(D=jn(D)),{servcmd:D,data:M})}(s):s,u=De.common.generateProtocolData({servcmd:r,data:g}),E=`${u.head.seq}${r}`;return De.channel.sendPacket(u,{requestId:E,timeout:s.timeout})})}function RE(s){const{Type:r,GroupId:g,GroupIdList:u=[]}=s,E=g||u[0]||"";return $r({type:r,groupID:E})}function Xg(s){const{GroupId:r=""}=s;return zc(r)}function jn(s){if(s.includes(dd))return s;const r=s.split(".")[1];return`${Zg}.${r}`}function ir(){var s;return(s=De.store.get("login"))===null||s===void 0?void 0:s.userId}const Fa=s=>C(s)||f(s),Cd=(s,r,g,u)=>{if(!Fa(s)||!Fa(r))return 0;let E=0;const m=Object.keys(r);let D;for(let M=0,T=m.length;M{if(n(r))return"";if(s===Uo.MSG_TEXT)return r.text||"";const g=WI[s];return g?Lu(g):""},Xc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],zI="im_sdk_config_mgr.fetch_config",dI="im_sdk_config_mgr.push_configv2",$c="cloud-config",Al=2996,va=new class{init(s){this.core=s}};function bg(s){return mA(this,void 0,void 0,function*(){const{sdkAppId:r}=va.core.store.get("instance")||{},g=va.core.helper.generateProtocolData({servcmd:zI,data:{uint32_sdkappid:r,uint64_version:s}}),u=`${g.head.seq}${zI}`;return va.core.channel.sendPacket(g,{requestId:u})})}var Ds=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;r.subscribeInnerEvent(dI,this._handlePushedConfig,this),u.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Xc),D.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(s){return mA(this,void 0,void 0,function*(){var r;const g={code:0,data:""};return s&&(g.data=((r=this._core.store.get("cloudConfig"))===null||r===void 0?void 0:r[s])||""),g})}checkMethodCallOverLimit(s){if(!this._cmdFrequencyLimitMap.has(s))return;if(!this._methodCallFrequencyMap.has(s))return void this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});const{count:r,interval:g}=this._cmdFrequencyLimitMap.get(s);let{startTime:u,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-u>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:u,methodCallCounter:E}),E>r)throw new this._core.helper.ChatError({code:Al,replacement1:s})}_handlePushedConfig(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.info("_handlePushedConfig",g(s)),yield this._updateCloudConfig(s)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{if(this._canFetch()){const g=yield bg(this._version);s.info("_fetchCloudConfigIfLogin",r(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:$c,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(g){s.debug("_fetchCloudConfigIfLogin",r(g))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:s,utils:{safeStringify:r}}=this._core;if(this._canFetch())try{const g=yield bg(this._version);s.info("_fetchCloudConfigIfReady",r(g)),yield this._updateCloudConfig(g)}catch(g){s.error("_fetchCloudConfigIfReady",r(g))}})}_updateCloudConfig(s){return mA(this,void 0,void 0,function*(){const r=this._parseCloudConfig(s);r&&(this._core.store.set("cloudConfig",r),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,r),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:r}}))})}_canFetch(){const{isLoggedIn:s}=this._core.store.get("login")||{};return s&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(s){const{int32_error_code:r,str_error_message:g,str_json_config:u,uint32_expired_time:E,uint32_sdkappid:m,uint64_version:D}=s;let M=null;if(r===0){if(this._version!==D)try{M=JSON.parse(u),this._version=D}catch{}this._expirationTime=Date.now()+1e3*E}else this._expirationTime=r===void 0?Date.now()+36e5:Date.now()+12e4;return M}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var s;let r=(s=yield this.getServerConfig("cmd_frequency_limit"))===null||s===void 0?void 0:s.data;const{isEmpty:g}=this._core.utils;if(!g(r))try{r=JSON.parse(r),this._updateCmdFreqLimitMap(r)}catch(u){console.warn(u)}})}_updateCmdFreqLimitMap(s){s.forEach(r=>{this._cmdFrequencyLimitMap.set(r.cmd,{interval:r.interval,count:r.count})})}_reset(){this._core.helper.taskScheduler.removeTask($c),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Xc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(dI,this._handlePushedConfig,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}};class Wn{constructor(r=0,g=0){this.high=r,this.low=g}equal(r){return r!==null&&this.low===r.low&&this.high===r.high}toString(){const r=Number(this.high).toString(16);let g=Number(this.low).toString(16);if(g.length<8){let u=8-g.length;for(;u;)g=`0${g}`,u--}return r+g}}const vc={SEARCH_GRP_SNS:new Wn(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Wn(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Wn(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Wn(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Wn(0,Math.pow(2,6)).toString(),USER_STATUS:new Wn(0,Math.pow(2,7)).toString(),CONV_MARK:new Wn(0,Math.pow(2,9)).toString(),CONV_GROUP:new Wn(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Wn(0,Math.pow(2,11)).toString(),MSG_EXT:new Wn(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Wn(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Wn(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Wn(Math.pow(2,7)).toString(),PLUGIN_CS:new Wn(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Wn(Math.pow(2,9)).toString(),PLUGIN_BOT:new Wn(Math.pow(2,10)).toString(),MSG_REACTION:new Wn(Math.pow(2,16)).toString(),FOLLOW:new Wn(Math.pow(2,20)).toString()},ZI="CommercialConfig",XI="commercial-config";var wE=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(s){this._core=s;const{helper:r,notificationCenter:g,constants:{WORKFLOW_NAME:u,WORKFLOW_STEP:E,InnerEvent:m}}=s;g.subscribeInnerEvent(m.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),g.subscribeInnerEvent(m.LOGOUT,this._handleLogout,this),g.subscribeInnerEvent(m.DESTROY,this._dispose,this),r.registerWorkflowStep(u.SYNC_SERVER_INFO_AFTER_LOGIN,E.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),s.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),s.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(s){return mA(this,void 0,void 0,function*(){const r=parseInt(s,10).toString(2),{length:g}=r;let u,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(r.charAt(m)==="1"&&(u=D<32?new Wn(0,2**D).toString():new Wn(2**(D-32),0).toString(),!this._featureMap.get(u))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${ZI}.isFeatureEnabled decimalNumber:${s} key:${u} ret:${E}`),{code:0,data:{enabled:E}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var s;const{ssoLog:r,utils:{safeStringify:g},common:{buildAndSendPacket:u}}=this._core;try{this._isFetching=!0;const E=yield u({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(s=this._core.store.get("instance"))===null||s===void 0?void 0:s.sdkAppId}});E&&(this._parseCommercialConfig(E),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(E){r.error("_fetchAndParseCommercialConfig",g(E))}finally{this._isFetching=!1}})}_syncCommercialConfig(s){return mA(this,void 0,void 0,function*(){const{purchaseBits:r}=s?.data||{};r&&(this._parsePurchaseBits(r),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:XI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var s;const r=(s=this._core.store.get("login"))===null||s===void 0?void 0:s.isLoggedIn,g=Date.now()>=this._expirationTime;return r&&!this._isFetching&&g}_handlePushedConfig(s){s?.body&&(this._parseCommercialConfig(s.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(s){const{ssoLog:r}=this._core;if(typeof s!="object")return;const{int32_error_code:g,str_error_message:u,str_purchase_bits:E,uint32_expired_time:m}=s;g===0?(this._parsePurchaseBits(E),this._expirationTime=Date.now()+1e3*m):g===void 0?(r.warn("_parseCommercialConfig",`${ZI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(r.warn("_parseCommercialConfig",`${ZI}._parseCommercialConfig errorCode:${g} errorMessage:${u}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(s){return s&&typeof s=="string"&&s.length>=1&&s.length<=64&&/[01]{1,64}/.test(s)}_parsePurchaseBits(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(this._isValidPurchaseBits(s)){this._purchaseBits=s,this._featureMap.clear(),this._methodKeyMap.clear();let u=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(u=m<32?new Wn(0,2**m).toString():new Wn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(u,!0);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(u,!1);const D=this._getKeyByValue(vc,u);D&&this._methodKeyMap.set(D,!1)}}else r.warn("_parsePurchaseBits",`${ZI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,r){const g=Object.entries(s).find(([u,E])=>E===r);return g?g[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(XI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},ch=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,channel:u}=this._core;r.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),u.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(s){if(!this._serverOverloadInfoMap.has(s))return;const{overloadStartTimestamp:r,delaySeconds:g}=this._serverOverloadInfoMap.get(s);if(Date.now()-r<=1e3*g)throw new this._core.helper.ChatError({functionName:s,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(s)}_handleOverLoadPush(s){const{OverLoadServCmd:r,DelaySecs:g}=s;this._serverOverloadInfoMap.set(r,{overloadStartTimestamp:Date.now(),delaySeconds:g})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.OVERLOAD_PUSH,this._handleOverLoadPush,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}},dC=new class{constructor(){this.name="ConfigCenter"}install(s){va.init(s),Ds.install(s),wE.install(s),ch.install(s)}},lh=new class{constructor(){this.name="ErrorMessage",this._core=null}install(s){return mA(this,void 0,void 0,function*(){if(this._core=s,this._canFetch()){const r=yield this._fetchErrorMessage();if(!r)return;const g=this._parseResponse(r);this._saveErrorMessage(g)}})}_canFetch(){const s=this._core.store.getStorage("errorMessage");return!s||this._isExpired(s)}_saveErrorMessage(s){this._core.store.setStorage("errorMessage",{errorMessage:s,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(s){console.error(s)}})}_isExpired(s){if(!s)return!0;const{errorMessageSavedTime:r}=s;return r&&new Date().getTime()-r>=6048e5}_parseResponse(s){if(typeof s=="string"){const r=s.split(`; +`),g={},u=new RegExp(/'/g);for(let E=0;E{var qA,Ie,le;const bi=function(ki,Ot){const{From_Account:Li,From_AccountHeadurl:cs,From_AccountNick:Re,IsNeedReadReceipt:St,MsgBody:UA,MsgClientTime:ai,MsgRandom:_s,MsgSeq:Ui,MsgTimeStamp:Or,SendMsgControl:Vi,SupportMessageExtension:Ir,To_Account:Nt,TinyId:Gt,MsgCheckResult:iE,CloudCustomData:ln,IsPeerRead:Qo,MsgFlagBits:Il,MsgVersion:GC,EventArray:Tr}=ki;return{from:Li,avatar:cs,nick:Re,needReadReceipt:St===1,readReceiptSentByPeer:Qo,clientTime:ai,messageFlagBits:Il,random:_s,sequence:Ui,time:Or,messageControlInfo:Vi,isSupportExtension:Ir,to:Nt,tinyID:Gt,checkResult:iE,cloudCustomData:ln,messageVersion:GC,eventArray:Tr,elements:Ot.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,xA);if(!((le=(Ie=(qA=OA?.EventArray)===null||qA===void 0?void 0:qA[0])===null||Ie===void 0?void 0:Ie.hasOwnProperty)===null||le===void 0)&&le.call(Ie,"C2cNotifyMsgArray"))SA.push(...function(ki){var Ot;const Li=[];return(Ot=ki.EventArray)===null||Ot===void 0||Ot.forEach(cs=>{var Re,St;const{C2cNotifyMsgArray:UA}=cs,ai=(St=(Re=UA?.[0])===null||Re===void 0?void 0:Re.WithdrawC2cMsgNotify)===null||St===void 0?void 0:St.C2cWithdrawInfoArray;Array.isArray(ai)&&Li.push(...ai)}),Li}(OA));else{const ki=xA.message.messageFactory.createMessage(Object.assign(Object.assign({},bi),{conversationType:"C2C",flow:"in"})),{elements:Ot}=bi;ki.setElement(Ot),LA.push(ki)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,r);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:oA}}catch(T){console.warn(T)}})}var kg,ao;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(kg||(kg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(ao||(ao={}));var CC=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(s){this._core=s;const{constants:r}=s;s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),s.helper.registerWorkflowStep(r.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,r.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(s){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:r=!1,isAfterNewMessageReceived:g=!1,isAfterLogin:u=!1}=s||{};let E=kg.START_SYNC;const m=[],D=[],M=[],T=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:E});){const P=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:E,syncTriggerEvent:g?ao.NEW_MESSAGE_RECEIVED:ao.LOGIN_SUCCESS});if(!P)break;const{unreadMessageList:W=[],revokedMessageList:oA=[],overflowUnreadCountList:EA,unreadCountList:wA,groupTipList:kA}=P;if(this._cookie=P?.cookie||"",E=P?.syncFlag,this._parseAndSaveUnreadMessageList(W),M.push(...oA),this._updateConversationUnreadOptions({unreadCountList:wA,overflowUnreadCountList:EA,conversationUpdateFieldList:m}),Array.isArray(kA)&&D.push(...kA),r){const{messages:xA}=this._handleNewMessageList(W);T.push(...xA)}}return r?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!u,isUnreadC2CMessage:!0,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(s){return mA(this,void 0,void 0,function*(){if(s.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(s){const{unreadCountList:r,overflowUnreadCountList:g,conversationUpdateFieldList:u}=s,{constants:{OuterConstant:{CONV_C2C:E,CONV_SYSTEM:m}}}=this._core;r?.forEach(D=>{const{From_Account:M,UnreadCount:T}=D;if(M!==m){const P=u.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:u.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(u.find(({conversationID:P})=>P===`${E}${M}`)||u.push({conversationID:`${E}${M}`,type:E,lastMsgTime:T}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(s){var r;const{messageDataHandler:g}=this._core.message||{},u=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{from:E,nick:m,avatar:D,conversationID:M=""}=s;if(E!==u){const T=g.getLatestMsgSentByPeer(M);if(T){const{nick:P,avatar:W}=T;m&&D?m===P&&D===W||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!1}):(s.nick=P,s.avatar=W)}}else{const T=g.getLatestMsgSentByMe(M);!T||m===T.nick&&D===T.avatar||g.updateNickAndAvatarOfSentMessage({conversationID:M,latestNick:m,latestAvatar:D,isSentByMe:!0})}}_handleNewMessageList(s){const{messageDataHandler:r}=this._core.message||{},g=new Map,u=[];return s.forEach(E=>{this._updateMessageProfile(E);let m=E.isModified===1;if(r.isMessageSentByCurrentInstance(E)?E.isModified=m:m=!1,E.isOnlineMessage())E._onlineOnlyFlag=!0,r.isMessageSentByCurrentInstance(E)||u.push(E);else if(this._shouldStoreUnreadMessage(E)){if(r.storeConversationMessage(E)){const{conversationID:D,conversationType:M,conversationSubType:T,flow:P,_isExcludedFromUnreadCount:W,_isExcludedFromLastMessage:oA}=E,EA=oA?"":E;g.has(D)?(g.get(D).lastMessage=EA,P==="in"&&(W||g.get(D).unreadCount++)):g.set(D,{conversationID:D,type:M,subType:T,unreadCount:W||P!=="in"?0:1,lastMessage:EA})}r.isMessageSentByCurrentInstance(E)&&!m||u.push(E)}}),{messages:u,conversationOptions:g}}_shouldStoreUnreadMessage(s){var r;const{conversationID:g}=s,{message:u,appStore:E,utils:{isEmpty:m}}=this._core||{},D=Array.from(((r=E.conversationStore.getConversationMap())===null||r===void 0?void 0:r.keys())||[]),M=this._getLocalLastMessageTime(g);return!u.messageDataHandler.isInMessageList(s)&&D.includes(g)&&this._localConversationIDListBeforeDisconnect.includes(g)&&!m(M)}_fetchUnreadDBMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;try{r.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${g(s)}`);const E=yield el(s,this._core);if(!E)return null;const{syncFlag:m,unreadMessageList:D,revokedMessageList:M,cookie:T,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}=E;return this._parseAndSaveUnreadMessageList(D),{syncFlag:m,cookie:T,unreadMessageList:D,revokedMessageList:M,unreadCountList:P,overflowUnreadCountList:W,groupTipList:oA}}catch(u){console.log(u)}})}_canContinueSync({cookie:s,syncFlag:r}){var g;return r===kg.START_SYNC||r===kg.SYNCING&&!(!((g=this._core)===null||g===void 0)&&g.helper.isEmpty(s))}_parseAndSaveUnreadMessageList(s){s.forEach(r=>{const{ID:g}=r;this._unreadDBMessageMap.set(g,r)})}_handleDisconnect(){var s;const{appStore:r}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((s=r.conversationStore.getConversationMap())===null||s===void 0?void 0:s.keys())||[])}_getLocalLastMessageTime(s){const{message:r}=this._core,g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},_E=new class{init(s){var r;this._core=s,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var s,r;const g=document?.visibilityState==="visible";(s=this._core)===null||s===void 0||s.store.set("activityMonitor",{isActive:g}),(r=this._core)===null||r===void 0||r.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:g})}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(s){var r;this._core=s,this._bindAppActivityEvent(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var s,r,g,u,E;const{MINI_APP_NAMESPACE:m,IN_TT_MINI_GAME:D,IN_WX_MINI_GAME:M}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};D||M?((r=m?.onShow)===null||r===void 0||r.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(g=m?.onHide)===null||g===void 0||g.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((u=m?.onAppShow)===null||u===void 0||u.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!0}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(E=m?.onAppHide)===null||E===void 0||E.call(m,()=>{var T,P;(T=this._core)===null||T===void 0||T.store.set("activityMonitor",{isActive:!1}),(P=this._core)===null||P===void 0||P.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var s;(s=this._core)===null||s===void 0||s.store.clear("activityMonitor")}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),this._reset()}},hd=new class{init(s){const{IN_MINI_APP:r,IN_WX_MINI_PLUGIN:g}=s.helper;g||(r?TE.init(s):_E.init(s))}};const NE="none",tl="online";var CI=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:tl})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:NE})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uu=new class{init(s){this._core=s,this._activateNetworkMonitoring(),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:s}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),s.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(s){console.error(s)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:s}}=this._core;s.offNetworkStatusChange&&s.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(s){var r,g;const{isConnected:u,networkType:E}=s;(r=this._core)===null||r===void 0||r.store.set("netWorkMonitor",{isNetworkOnline:u,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:u,networkType:E})}_reset(){var s;this._deactivateNetworkMonitoring(),(s=this._core)===null||s===void 0||s.store.clear("netWorkMonitor")}_dispose(){var s,r;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent((r=this._core)===null||r===void 0?void 0:r.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Fu=new class{init(s){const{IN_MINI_APP:r}=s.utils;r?Uu.init(s):CI.init(s)}},hC=new class{constructor(){this.name="SystemStateMonitor"}install(s){hd.init(s),Fu.init(s)}};const wr=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),cg="tui_room_svr.*";var Rc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=wr}install(s){this._core=s;const{notificationCenter:r,InnerEvent:g,helper:u}=s;r.subscribeInnerEvent(g.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),r.subscribeInnerEvent(g.LOGOUT,this._reset,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this),r.subscribeInnerEvent("im_open_push.msg_push",r.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),u.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),u.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return mA(this,void 0,void 0,function*(){const r="transferBusinessCommand";try{const{serviceCommand:g=cg}=s||{};if(!this._isValidTransferredCommand(g))throw new this._core.helper.ChatError({code:2995,functionName:r});return{code:0,data:(yield function(E,m){return mA(this,void 0,void 0,function*(){const{helper:D,channel:M}=m,{serviceCommand:T=cg,data:P}=E||{};let W={};try{W=typeof P=="string"?JSON.parse(P):P}catch(wA){console.warn(wA)}const oA=D.generateProtocolData({servcmd:T,data:W}),EA=`${oA.head.seq}${T}`;return M.sendPacket(oA,{requestId:EA,shouldRejectOnError:!1})})}(s,this._core))||{}}}catch(g){throw console.warn(g),new this._core.helper.ChatError({code:g?.errorCode,message:g?.errorInfo,data:{},functionName:r})}})}_onCloudConfigUpdate(s={}){try{if(typeof s.rtc_cmd!="string")return;const r=JSON.parse(s.rtc_cmd);Array.isArray(r)&&(this._transferredCommands=new Set([...this._transferredCommands,...r]))}catch(r){console.log(r)}}_isValidTransferredCommand(s=""){const r=`${s?.split(".")[0]}.*`;return this._transferredCommands.has(r)}_onServerPushBusinessCommand(s){const{OuterEvent:r,notificationCenter:g}=this._core,{MsgContent:u}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=r;g.emitOuterEvent(E,{name:E,data:u})}_reset(){this._transferredCommands=wr}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;this._reset(),s.unSubscribeInnerEvent(r.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this),s.unSubscribeInnerEvent("im_open_push.msg_push",s.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Ou=1,Nl=2,Bd=3,Aa=4,hI=5,_n="TIMCustomElem",BC="C2C",il="GROUP",Qd="invite",BI="accept",Oa="cancel",QC="reject",Pa="modifyInvitation",hr="signaling",pd=8010,Pu="signaling-timeout";function Br(s){return s.filter(r=>{if(r.type===_n){const{cloudCustomData:g="",payload:{data:u=""}={}}=r,E=g.match(/"type":"tsignaling"/),m=u.match(/inviteID/),D=u.match(/actionType/);return E||m&&D}return!1})}function wc(s){const{data:r}=s.payload;try{return JSON.parse(r)}catch(g){return console.error(g),null}}function ol(s,r){return s.toString(16).padStart(r,"0")}function Lg(s){if(s<0||s>53)throw new Error("Number of digits must be between 0 and 53");if(s<=30)return Math.floor(Math.random()*(1<0;const M=this._core.common.getCurrentUserID();return D.includes(M)}return!0}updateSignaling(s){const r=`${hr}.updateSignaling`,{inviteID:g,inviter:u,inviteeList:E,groupID:m}=s;if(console.log(`${r} inviteID:${g} inviter:${u} groupID:${m}`),m&&this.hasSignaling(g)){const D=E[0],{inviteeList:M}=this._onlineSignalingMap.get(g);M.includes(D)&&(M.splice(M.indexOf(D),1),console.log(`${r} remove ${D}. localInviteeList.length:${M.length}`)),M.length===0&&this.removeSignaling(g)}else this.removeSignaling(g)}setSignalingListenStatus(s){this._isSignalingListening=s}getSignalingListenStatus(){return this._isSignalingListening}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._isSignalingListening=!1}_reset(){this._onlineSignalingMap.clear()}},$g=new class{init(s){this._core=s}createInviteSignaling(s){const r=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:r})),{groupID:u,inviteeList:E}=g,m=u||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const r=this._createAcceptSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const r=this._createCancelSignalingData(s),{groupID:g,inviteeList:u}=r,E=g||u[0];return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const r=this._createRejectSignalingData(s),{groupID:g,inviter:u}=r,E=g||u;return{signaling:this._createSignaling(r,E),signalingData:r,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:r=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:u,inviteeList:E,inviter:m}=g,D=u||(r?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var r,g;const{data:u="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(r=Po.getSignaling(m))===null||r===void 0?void 0:r.signaling)===null||g===void 0?void 0:g._onlineOnlyFlag)||!1;return{onlineUserOnly:E||T,offlinePushInfo:D,messageControlInfo:this._createMessageControlInfo(u,M)}}_createMessageControlInfo(s,r){const g=r===hI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),u=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||u,excludedFromLastMessage:g||u}}_createInviteSignalingData(s){const r=`${hr}._createInviteSignalingData`,{userID:g,timeout:u=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ou,inviter:D,inviteeList:E?m:[g],timeout:u});return console.log(`${r} signalingData:`,M),M}_createAcceptSignalingData(s){const r=`${hr}._createAcceptSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Bd,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createCancelSignalingData(s){const r=`${hr}._createCancelSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Nl,groupID:m,inviter:u,inviteeList:E});return console.log(`${r} signalingData:`,D),D}_createRejectSignalingData(s){const r=`${hr}._createRejectSignalingData`,{inviteID:g}=s,u=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Po.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Aa,groupID:m,inviter:E,inviteeList:[u]});return console.log(`${r} signalingData:`,D),D}_createTimeoutSignalingData(s){const r=`${hr}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:u}=s,{inviteeList:E,inviter:m}=Po.getSignaling(u),D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:hI,inviter:m,inviteeList:g?E:[D]});return console.log(`${r} signalingData:`,M),M}_createSignaling(s,r){var g,u,E;const{groupID:m=""}=s,D={to:r,conversationType:m?il:BC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[ol(Lg(32),8),ol(Lg(16),4),ol(16384|Lg(12),4),ol(32768|Lg(14),4),ol(Lg(48),12)].join("-")}_generateBaseSignalData(s){const{data:r="",inviteID:g="",groupID:u=""}=s;return{businessID:1,timeout:0,data:r,inviteID:g,groupID:u}}},Za=new class{constructor(){this._isProcessingSignaling=!1}init(s){this._core=s,s.helper.registerApi({apiName:"invite",context:this}),s.helper.registerApi({apiName:"accept",context:this}),s.helper.registerApi({apiName:"cancel",context:this}),s.helper.registerApi({apiName:"reject",context:this}),s.helper.registerApi({apiName:"modifyInvitation",context:this}),s.helper.registerApi({apiName:"getSignalingInfo",context:this}),s.helper.registerApi({apiName:"addSignalingListener",context:this}),s.helper.registerApi({apiName:"removeSignalingListener",context:this}),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this)}invite(s){return mA(this,void 0,void 0,function*(){var r;try{this._validateBeforeInvite(s);const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=u;return Po.saveSignaling(D,Object.assign(Object.assign({},u),{signaling:g})),M>0&&((r=this._core)===null||r===void 0||r.helper.taskScheduler.addOnceTask({id:`${Pu}-${D}`,intervalMs:1e3*(M+5),callback:this.handleInvitationExpiryTimer.bind(this,D)})),Object.assign(Object.assign({},m),{inviteID:D})}return m}catch(g){throw g}})}accept(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeAccept(r),this._isProcessingSignaling=!0;const{signaling:g,signalingData:u,signalingExtensionOptions:E}=$g.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Po.updateSignaling(u),Object.assign(Object.assign({},m),{inviteID:r})):m}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}cancel(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeCancel(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createCancelSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Po.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}reject(s){return mA(this,void 0,void 0,function*(){try{const{inviteID:r}=s;this._validateBeforeReject(r),this._isProcessingSignaling=!0;const{signaling:g,signalingExtensionOptions:u}=$g.createRejectSignaling(s),E=yield this._sendSignaling(g,u);return E?.code===0?(Po.removeSignaling(r),Object.assign(Object.assign({},E),{inviteID:r})):E}catch(r){throw r}finally{this._isProcessingSignaling=!1}})}modifyInvitation(s){return mA(this,void 0,void 0,function*(){var r,g;const{inviteID:u,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(u);const D=Po.getSignaling(u),{signaling:M}=D,T=So(D,["signaling"]);m=M.payload.data,T.data=E,M.payload.data=JSON.stringify(T);const P=yield(g=(r=this._core)===null||r===void 0?void 0:r.message.messageAction)===null||g===void 0?void 0:g.modifyMessage(M);return Po.hasSignaling(u)&&Po.saveSignaling(u,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Po.getSignaling(u);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(Br([s]).length===0)return;const u=wc(s),E={businessID:u.businessID||1,inviteID:u.inviteID,groupID:u.groupID||"",inviter:u.inviter||"",inviteeList:u.inviteeList||[],data:u.data||"",actionType:u.actionType||Ou,timeout:u.timeout||0};return r.debug(`${hr} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Po.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,r,g)}removeSignalingListener(s,r,g){var u,E;s===((u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED)&&Po.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,r,g)}handleInvitationExpiryTimer(s){const r=Po.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!r.has(s))return;const u=r.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:u})}_sendSignaling(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;return(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)})}_sendTimeoutNotice(s){return mA(this,void 0,void 0,function*(){var r,g,u;this._core.ssoLog.debug("_sendTimeoutNotice",`${hr}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=$g.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:oA,inviteeList:EA,inviter:wA}=M;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent((g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_TIMEOUT,{name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:oA,inviteID:m,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Po.removeSignaling(m):Po.updateSignaling(M)}})}_validateInviteId(s,r){if(!Po.hasSignaling(r))throw new this._core.helper.ChatError({functionName:s,code:pd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const r=Qd,{userID:g}=s,u=this._core.common.getCurrentUserID();if(g===u)throw new this._core.helper.ChatError({functionName:r,message:`cannot invite yourself, currentUserId:${u}, inviteeId:${g}`})}_validateBeforeAccept(s){const r=BI;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Po.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeCancel(s){const r=Oa;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviter:u}=Po.getSignaling(s);if(u!==g){const E=`unmatched inviter:${u} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeReject(s){const r=QC;this._validateInviteId(r,s),this._validateProcessStatus(r);const g=this._core.common.getCurrentUserID(),{inviteeList:u}=Po.getSignaling(s);if(!u.includes(g)){const E=`userID:${g} not in inviteeList. inviteID:${s}`;throw new this._core.helper.ChatError({functionName:r,message:E})}}_validateBeforeModifyInvitation(s){const r=Pa;this._validateInviteId(r,s)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this)}_reset(){this._isProcessingSignaling=!1}},Gl=new class{constructor(){this._actionProcessor=new Map([[Ou,this._onNewInvitationReceived.bind(this)],[Aa,this._onInviteeRejected.bind(this)],[Bd,this._onInviteeAccepted.bind(this)],[Nl,this._onInvitationCancelled.bind(this)],[hI,this._onInvitationTimeout.bind(this)]])}init(s){this._core=s,s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),s.notificationCenter.subscribeOuterEvent(s.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this._dispose,this)}handleActionSignaling(s){s.forEach(r=>{const g=wc(r);if(g){const u=this._actionProcessor.get(g.actionType);u?.(g,r)}})}_handleMessageReceived(s){if(!Po.getSignalingListenStatus())return;const r=Br(s.data);r.length!==0&&this.handleActionSignaling(r)}_handleMessageModified(s){if(!Po.getSignalingListenStatus())return;const r=Br(s.data);r.length>0&&r.forEach(g=>{const u=wc(g);u&&this._onInvitationModified(u,g)})}_onNewInvitationReceived(s,r){var g,u;const E=`${hr}._onNewInvitationReceived`,{inviteID:m,inviteeList:D,groupID:M}=s,T=this._core.common.getCurrentUserID();if(this._core.ssoLog.debug("_onNewInvitationReceived",`${E} signalingData:${JSON.stringify(s)}}`),M&&!D.includes(T))return;let{timeout:P}=s;const W=Date.now()/1e3-r.time;P>0&&W>0&&P>W&&(P-=W);const oA=Po.getSignaling(m);oA!==s&&(oA||Po.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:r})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${Pu}-${m}`,intervalMs:1e3*P,callback:Za.handleInvitationExpiryTimer.bind(Za,m)})),this._emitEvent({name:(u=this._core)===null||u===void 0?void 0:u.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var r;const g=`${hr}._onInviteeRejected`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Po.hasSignaling(u);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_REJECTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInviteeAccepted(s){var r;const g=`${hr}._onInviteeAccepted`,{inviteID:u,inviter:E,groupID:m,inviteeList:D}=s,M=Po.hasSignaling(u);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${u} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITEE_ACCEPTED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{invitee:D[0]})}))}_onInvitationCancelled(s){var r;const g=`${hr}._onInvitationCancelled`,{inviteID:u,inviter:E,groupID:m}=s,D=Po.hasSignaling(u);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${u} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Po.removeSignaling(u),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_CANCELLED,data:this._generateBaseEmitData(s)}))}_onInvitationTimeout(s){var r;const g=`${hr}._onInvitationTimeout`,{inviteID:u,inviteeList:E}=s,m=Po.hasSignaling(u);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${u} hasInviteID:${m} data:${s.data}`),m&&(Po.updateSignaling(s),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.SignalingEvent.INVITATION_TIMEOUT,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:E,isSelfTimeout:!1})}))}_onInvitationModified(s,r){var g;const u=`${hr}._onInvitationModified`,{inviteID:E,data:m}=s,D=Po.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${u} inviteID:${E} data:${m}`),D&&(Po.saveSignaling(E,Object.assign(Object.assign({},s),{signaling:r})),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.SignalingEvent.INVITATION_MODIFIED,data:{inviteID:E,data:m}}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}_generateBaseEmitData(s){const{inviteID:r,inviter:g,groupID:u,data:E}=s;return{inviteID:r,inviter:g,groupID:u,data:E||""}}_dispose(){var s,r,g;(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_RECEIVED,this._handleMessageReceived,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeOuterEvent(this._core.OuterEvent.MESSAGE_MODIFIED,this._handleMessageModified,this),(g=this._core)===null||g===void 0||g.notificationCenter.unSubscribeOuterEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}},ea=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:r,helper:g,constants:{InnerEvent:u,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;r.subscribeInnerEvent(u.DESTROY,this._dispose,this),r.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_LOGIN,E.SIGNALING_MESSAGE_RECOVER,this._handleC2COfflineMessage,this)}_handleC2COfflineMessage(s){const{result:{unreadMessageMap:r}={}}=s||{};if(!(r?.size!==0&&Po.getSignalingListenStatus()))return;const g=Br([...r.values()]);if(g.length!==0&&(g.forEach(u=>{this._handleC2CActionType(u)}),this._offlineSignalingMap.size>0)){const u=this._sortOfflineSignalingByTime();Gl.handleActionSignaling(u)}}_handleC2CActionType(s){const r=wc(s);if(!r)return;const{actionType:g}=r;g===Ou?this._saveValidOfflineInvite(r,s):this._removeOfflineInvite(r)}_saveValidOfflineInvite(s,r){const{inviteID:g,inviteeList:u=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!u.includes(m))return;const D=Date.now()/1e3-r.time;E>0&&D>E&&E!==0||this._offlineSignalingMap.set(g,Object.assign(Object.assign({},s),{signalingList:[r]}))}_removeOfflineInvite(s){const{inviteID:r=""}=s;this._offlineSignalingMap.has(r)&&this._offlineSignalingMap.delete(r)}_sortOfflineSignalingByTime(){let s=[];return this._offlineSignalingMap.forEach(r=>{s=[...s,...r.signalingList]}),s.sort((r,g)=>r.time-g.time)}_dispose(){var s,r;this._reset(),(s=this._core)===null||s===void 0||s.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(r=this._core)===null||r===void 0||r.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._offlineSignalingMap.clear()}};const Ih={invite:{userID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0},timeout:{required:!1,rules:["number"],allowEmpty:!1},onlineUserOnly:{required:!1,rules:["boolean"],allowEmpty:!1},offlinePushInfo:{required:!1,rules:["object"],allowEmpty:!1}},cancel:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},accept:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},reject:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}},modifyInvitation:{inviteID:{required:!0,rules:["string"],allowEmpty:!1},data:{required:!1,rules:["string"],allowEmpty:!0}}},js={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var $I=new class{constructor(){this.name="Signaling"}install(s){Za.init(s),Gl.init(s),$g.init(s),Po.init(s),ea.init(s),s.helper.registerValidateConfig({auth:js,params:Ih})}};const Fs=new class{init(s){this.core=s}};function _c(s){let r;const{message:g}=Fs.core,{conversationID:u,messageID:E}=s;return r=g.messageDataHandler.getLocalMessageList(u).find(m=>m.ID===E),!r&&(r=g.messageDataHandler.getSparseMessageList(u).find(m=>m.ID===E)),r}function Ac(s){return s.map(r=>{const{from:g,to:u,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:oA,time:EA}=r;return{ClientSeq:T,CloudCustomData:E,From_Account:g,From_AccountHeadurl:m,From_AccountNick:D,Id:M,MsgBody:JSON.parse(JSON.stringify(r.transformElementsToServerFormat())),MsgClientTime:P,MsgRandom:W,Random:W,MsgSeq:oA,MsgTimeStamp:EA,ReceiverId:u,SenderId:g,To_Account:u}})}function Qr(s){var r;const{From_Account:g,From_AccountHeadurl:u,From_AccountNick:E,GroupId:m,MsgClientTime:D,ClientSeq:M,To_Account:T,MsgTimeStamp:P,TinyId:W,MsgRandom:oA,MsgSeq:EA}=s;return{from:g,avatar:u,nick:E,clientTime:D,time:P,tinyID:W,random:oA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(r=s.MsgBody)===null||r===void 0?void 0:r.map(wA=>{const{MsgType:kA}=wA;return Fs.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Vr,Xa;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Vr||(Vr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Xa||(Xa={}));const GE="MSG_REACTION",pC="MSG_EXT",uh=0,go=1,Tc={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},bl="16k_zh",mC="16k_en",fC="16k_yue",kl="16k_ja",Au="16k_zh-PY",QI={[Tc.ZH_CN]:bl,[Tc.EN_US]:mC,[Tc.YUE_HK]:fC,[Tc.JA_JP]:kl,[Tc.ZH_PY]:Au},pI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,bE={READ:0,UNREAD:1},Ll=1,Ul=2,Ug=3;var ec;(function(s){s.IN="in",s.OUT="out"})(ec||(ec={}));const md=16,kE=17;var Nc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Nc||(Nc={}));var eu;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(eu||(eu={}));const Io="StreamMsg.PushStreamHttp";var LE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{MESSAGE_REACTION_UPDATED:E,MESSAGE_REACTION_UPDATED_SYNC:m}}=s;r.registerApi({apiName:"addMessageReaction",context:this}),r.registerApi({apiName:"removeMessageReaction",context:this}),r.registerApi({apiName:"getMessageReactions",context:this}),r.registerApi({apiName:"getAllUserListOfMessageReaction",context:this}),g.subscribeInnerEvent(u,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(u,m,this._handleReactionSync,this)}addMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:u,helper:E}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:m,ID:D,conversationType:M,from:T,to:P,clientSequence:W,random:oA,time:EA,sequence:wA}=s,kA=`conversationID:${m} messageID:${D} reactionID:${r}`;try{return this._recordMessageReactedByMe(D,r),M===g.CONV_C2C?yield function(xA,LA){return mA(this,void 0,void 0,function*(){var SA;const{from:OA,to:qA,clientSequence:Ie,random:le,time:bi,reactionID:ki}=xA,Ot={From_Account:OA,To_Account:qA,MsgKey:`${Ie}_${le}_${bi}`,Reaction:ki,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:Ot})})}({from:T,to:P,clientSequence:W,random:oA,time:EA,reactionID:r},this._core):M===g.CONV_GROUP&&(yield function(xA,LA){return mA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:qA,sequence:Ie}=xA,le={GroupId:OA,MsgSeq:Ie,Reaction:qA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:le})})}({to:P,reactionID:r,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(xA){this._removeMyReactionRecord(D,r);const{errorCode:LA}=xA||{};throw new E.ChatError({functionName:"addMessageReaction",code:LA,moreMessage:kA})}})}removeMessageReaction(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,helper:u}=this._core;this._validateMessageReactionBusinessCapability();const{conversationID:E,ID:m,conversationType:D,from:M,to:T,clientSequence:P,random:W,time:oA,sequence:EA}=s,wA=`conversationID:${E} messageID:${m} reactionID:${r}`;try{return this._removeMyReactionRecord(m,r),D===g.CONV_C2C?yield function(kA,xA){return mA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:qA,random:Ie,time:le,reactionID:bi}=kA,ki={From_Account:SA,To_Account:OA,MsgKey:`${qA}_${Ie}_${le}`,Reaction:bi,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:ki})})}({from:M,to:T,clientSequence:P,random:W,time:oA,reactionID:r},this._core):D===g.CONV_GROUP&&(yield function(kA,xA){return mA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:qA}=kA,Ie={GroupId:SA,MsgSeq:qA,Reaction:OA,Del_Account:[(LA=xA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:Ie},xA)})}({to:T,reactionID:r,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:xA}=kA||{};throw new u.ChatError({functionName:"removeMessageReaction",code:xA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return mA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:r,reactionID:g,nextSeq:u=0}=s,E=s.count>100?100:s.count,{conversationID:m}=r,{ssoLog:D,helper:M,constants:T}=this._core;try{let P=null;if(P=m.startsWith(T.OuterConstant.CONV_C2C)?yield function(W){return mA(this,void 0,void 0,function*(){const{message:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:xA,to:LA,clientSequence:SA,random:OA,time:qA}=oA,Ie={Reaction:wA,NextSeq:EA,Count:kA,From_Account:xA,To_Account:LA,MsgKey:`${SA}_${OA}_${qA}`};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:Ie})})}({message:r,reactionID:g,nextSeq:u,count:E}):yield function(W){return mA(this,void 0,void 0,function*(){const{message:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:xA,to:LA}=oA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:xA};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:r,reactionID:g,nextSeq:u,count:E}),P){const{Reaction_Account:W,NextSeq:oA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:oA,isCompleted:u===0,userList:EA}}}}catch(P){const{errorCode:W}=P||{};throw new M.ChatError({functionName:"getAllUserListOfMessageReaction",code:W})}})}getMessageReactions(s){return mA(this,void 0,void 0,function*(){const{constants:r}=this._core;this._validateMessageReactionBusinessCapability();const{messageList:g,maxUserCountPerReaction:u=10}=s,E=g[0];let m=null;const D=new Map,{from:M,to:T,conversationType:P}=E,W=this._generateMessageKeyList(g,D);P===r.OuterConstant.CONV_C2C?m=yield function(kA){return mA(this,void 0,void 0,function*(){const{from:xA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,qA={From_Account:xA,To_Account:LA,MsgKeyList:SA,Count:OA};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:qA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:u}):P===r.OuterConstant.CONV_GROUP&&(m=yield function(kA){return mA(this,void 0,void 0,function*(){const{groupId:xA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:xA,MsgSeqList:LA,Count:SA};return Fs.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:u}));const{Results:oA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(oA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:oA.map(kA=>{const{ReactionList:xA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:xA.map(OA=>{const{Reaction:qA,Count:Ie,Reaction_Account:le,ReactedByMe:bi}=OA;return{reactionID:qA,totalUserCount:Ie,partialUserList:this._generatePartialUserInfo({userIDList:le,userProfileMap:wA}),reactedByMyself:bi===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const r=[];return s?.forEach(g=>{const{ReactionList:u=[]}=g;u.forEach(E=>{E.Reaction_Account&&r.push(...E.Reaction_Account)})}),r}_getUserProfileList(s){return mA(this,void 0,void 0,function*(){var r;try{const g=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:s});return g?g.data:[]}catch{return[]}})}_getUserProfileMap(s){return mA(this,void 0,void 0,function*(){const r=new Map;return(yield this._getUserProfileList(s)).forEach(g=>{const{nick:u,avatar:E,userID:m}=g;r.set(m,{nick:u,avatar:E,userID:m})}),r})}_recordMessageReactedByMe(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)?this._reactionsMap.get(g).reactedByMe=!0:this._reactionsMap.set(g,{reactedByMe:!0})}_removeMyReactionRecord(s,r){const g=`${s}-${r}`;this._reactionsMap.has(g)&&(this._reactionsMap.get(g).reactedByMe=!1)}_recordMessageReactionInfo(s){const{messageID:r,reactionID:g,reactionInfo:u}=s,E=`${r}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),u))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:r}=this._core;if(!s.checkBusinessCapabilityBits(GE))throw new s.ChatError({functionName:"addMessageReaction",code:r.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:r}=s,{notificationCenter:g,constants:u}=this._core;r.forEach(E=>mA(this,void 0,void 0,function*(){const{C2CMsgInfo:m,GroupMsgInfo:D,MsgReactionSummary:M}=E,{TinyId:T,MsgClientTime:P,MsgRandom:W}=Object.assign(Object.assign({},m),D),oA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),wA=yield this._getUserProfileMap(EA),kA=M.map(xA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=xA,qA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:wA}),Ie=OA?xA.Count:0,le=((LA=this._reactionsMap.get(`${oA}-${SA}`))===null||LA===void 0?void 0:LA.reactedByMe)||!1;return this._recordMessageReactionInfo({messageID:oA,reactionID:SA,reactionInfo:{reactionID:SA,totalUserCount:Ie,partialUserList:qA}}),{reactionID:SA,totalUserCount:Ie,partialUserList:qA,reactedByMyself:le}});g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:kA}})}))}_handleReactionSync(s){var r;const{notificationCenter:g,constants:u}=this._core,{C2CMsgInfo:E={},GroupMsgInfo:m={},Reaction:D,OperateType:M}=s.MsgReactionNotify,{TinyId:T="",MsgClientTime:P=0,MsgRandom:W=0}=Object.assign(Object.assign({},E),m),oA=`${T}-${P}-${W}`,EA=`${oA}-${D}`;if(M===1?this._recordMessageReactedByMe(oA,D):this._removeMyReactionRecord(oA,D),(r=this._reactionsMap.get(EA))===null||r===void 0?void 0:r.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=M===1,g.emitOuterEvent(u.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:u.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:r}){const g=[];return s?.forEach(u=>{r.has(u)&&g.push(r.get(u))}),g}_generateMessageID(s){const{messageSequence:r,messageKey:g,messageIDMap:u}=s;return g?u.get(g):u.get(r)}_generateMessageKeyList(s,r){const{constants:g}=this._core,u=s[0],{conversationType:E}=u;let m=[];return E===g.OuterConstant.CONV_C2C?m=s.map(D=>{const{clientSequence:M,random:T,time:P,ID:W}=D,oA=`${M}_${T}_${P}`;return r.set(oA,W),oA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return r.set(T,M),T})),m}},$a=new class{init(s){this._core=s;const{helper:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:u,GROUP_MESSAGE_READ_RECEIPT:E},notificationCenter:m}=s;r.registerApi({apiName:"sendMessageReadReceipt",context:this}),r.registerApi({apiName:"getMessageReadReceiptList",context:this}),r.registerApi({apiName:"getGroupMessageReadMemberList",context:this}),m.subscribeInnerEvent(g,u,this._handleC2CMessageReadReceipt,this),m.subscribeInnerEvent(g,E,this._handleGroupMessageReadReceipt,this)}sendMessageReadReceipt(s){return mA(this,void 0,void 0,function*(){var r;const{common:g,constants:u}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:u.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===u.OuterConstant.CONV_C2C?yield function(D){return mA(this,void 0,void 0,function*(){const{common:M,constants:T}=Fs.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:xA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:xA,MsgRandom:LA,MsgTime:SA,MsgClientTime:OA}}),oA={Peer_Account:P,C2CMsgInfo:W};return M.buildAndSendPacket({servcmd:"openim.c2c_msg_read_receipt",data:oA})})}(E):yield function(D){return mA(this,void 0,void 0,function*(){const{common:M,constants:T}=Fs.core,P={GroupId:D[0].conversationID.replace(T.OuterConstant.CONV_GROUP,""),MsgSeqList:D.map(W=>({MsgSeq:W.sequence}))};return M.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_receipt",data:P})})}(E),{code:0,data:{}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g.ChatError({code:D,message:M,moreMessage:`peerAccount:${(r=E?.[0])===null||r===void 0?void 0:r.conversationID}`})}})}getMessageReadReceiptList(s){return mA(this,void 0,void 0,function*(){const{common:r,constants:g}=this._core;try{const{conversationType:u}=s[0];if(u===g.OuterConstant.CONV_GROUP){const E=this._filterValidMessageSendByMe(s);if(E?.length>0){const m=yield function(M){return mA(this,void 0,void 0,function*(){const{common:T,constants:P}=Fs.core,W={GroupId:M[0].conversationID.replace(P.OuterConstant.CONV_GROUP,""),MsgSeqList:M.map(oA=>({MsgSeq:oA.sequence}))};return T.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt",data:W})})}(E),{GroupMsgReceiptList:D}=m||{};this._updateGroupMessagesReadReceiptInfo({messageList:s,readReceiptList:D})}}return{code:0,data:{messageList:s}}}catch(u){const{errorCode:E,errorInfo:m}=u;throw new r.ChatError({code:E,message:m})}})}getGroupMessageReadMemberList(s){return mA(this,void 0,void 0,function*(){const{constants:r,common:g}=this._core,{message:u,filter:E=bE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=u,P=D.replace(r.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const oA=yield function(EA){return mA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:xA,cursor:LA,count:SA}=EA,OA={MsgSeq:wA,GroupId:kA,Filter:xA,Cursor:LA,Num:SA};return Fs.core.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_msg_receipt_detail",data:OA})})}({groupID:P,sequence:M,filter:E,cursor:m,count:W});if(oA){const{Cursor:EA,IsFinish:wA,UnreadList:kA,ReadList:xA}=oA,LA={cursor:EA,isCompleted:wA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===bE.READ?LA.readUserIDList=xA.map(SA=>SA.Read_Account):E===bE.UNREAD&&(LA.unreadUserIDList=kA.map(SA=>SA.Unread_Account)),{code:0,data:LA}}}catch(oA){const{errorCode:EA,errorInfo:wA}=oA;throw new g.ChatError({code:EA,message:wA})}})}_handleC2CMessageReadReceipt(s){const r=[],{constants:g,helper:u}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(u.isEmpty(E))return;const M=`${g.OuterConstant.CONV_C2C}${D}`;E?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:oA}=T,EA=`${P}-${W}-${oA}`,wA=_c({conversationID:M,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=m,r.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(r)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:r,readReceiptList:g}=s,u=new Map;r.forEach(E=>{u.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=u.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const r=[],{constants:g}=this._core,{GroupTips:u}=s;u.forEach(E=>{const{MsgBody:{GroupMsgReceiptList:m},GroupInfo:{GroupId:D}}=E,M=`${g.OuterConstant.CONV_GROUP}${D}`;m?.forEach(T=>{const{TinyId:P,MsgClientTime:W,MsgRandom:oA,ReadNum:EA,UnreadNum:wA}=T,kA=`${P}-${W}-${oA}`,xA=_c({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};xA&&(typeof EA=="number"&&(xA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof wA=="number"&&(xA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),r.push(LA))})}),this._emitReadReceiptEventIfNeed(r)}_emitReadReceiptEventIfNeed(s){const{notificationCenter:r,OuterEvent:g}=this._core;s.length>0&&r.emitOuterEvent(g.MESSAGE_READ_RECEIPT_RECEIVED,{name:g.MESSAGE_READ_RECEIPT_RECEIVED,data:s})}_filterValidMessageSendByOther(s){return this._filterNeedReadReceiptMessages(s).filter(r=>{const{from:g}=r;return g!==this._core.common.getCurrentUserID()})}_filterValidMessageSendByMe(s){const{OuterConstant:r}=this._core.constants;return this._filterNeedReadReceiptMessages(s).filter(g=>{const{from:u,status:E}=g;return u===this._core.common.getCurrentUserID()&&E===r.MessageStatus.SUCCESS})}_filterNeedReadReceiptMessages(s){return s.filter(r=>r.needReadReceipt===!0)}dispose(){const{InnerEvent:{MESSAGE_PUSH:s},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:r,GROUP_MESSAGE_READ_RECEIPT:g},notificationCenter:u}=this._core;u.unSubscribeInnerEvent(s,r,this._handleC2CMessageReadReceipt,this),u.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function tu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Fs.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return u({servcmd:"openim_msg_ext_http_svc.set_key_values",data:{From_Account:E,To_Account:m,MsgKey:`${D}_${M}_${T}`,OperateType:g,ExtensionList:r}})})}function xu(s,r,g){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:u}}=Fs.core,{to:E,sequence:m}=s;return u({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:r}})})}var Gc=new class{constructor(){this._messageExtensionsMap=new Map,this._extensionsLatestSequenceMap=new Map,this._completedFetchExtensions=new Set}init(s){this._core=s;const{notificationCenter:r,helper:{registerApi:g},InnerEvent:{MESSAGE_PUSH:u,LOGOUT:E},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:m}}=s;g({apiName:"setMessageExtensions",context:this}),g({apiName:"getMessageExtensions",context:this}),g({apiName:"deleteMessageExtensions",context:this}),r.subscribeInnerEvent(u,m,this._handleMessageExtensionsNotify,this),r.subscribeInnerEvent(E,this.reset,this)}setMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("setMessageExtensions");const{constants:{OuterConstant:g},ssoLog:u}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=r;r.length>20&&(P=r.slice(0,20),u.warn("setMessageExtensions","the length of extensions cannot exceed 20"));const W=this._generateServerExtensions(s,P),oA=`convID:${m} messageID:${E} sequence:${D} time:${M} count:${P.length}`;try{let EA;if(T===g.CONV_C2C?EA=yield tu(s,W,Ll):T===g.CONV_GROUP&&(EA=yield xu(s,W,Ll)),EA){const{resultList:wA,successCount:kA,failureCount:xA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${oA} successCount:${kA} failCount:${xA}`}}}return{code:0,data:{extensions:[]}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"setMessageExtensions",code:wA,moreMessage:oA})}})}getMessageExtensions(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:u,sequence:E,time:m}=s,D=`convID:${g} messageID:${u} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(u)&&(M=this._extensionsLatestSequenceMap.get(u));const T=yield this._fetchMessageExtensions(s,M);return r(M)&&T.length>1&&this._completedFetchExtensions.add(u),{code:0,data:{extensions:T},successLog:{message:D}}}catch(M){const{errorCode:T,errorInfo:P=""}=M||{};throw new this._core.common.ChatError({code:T,message:P,moreMessage:D})}})}deleteMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){this._validateMessageExtensionBusinessCapability("deleteMessageExtensions");const{utils:{isEmpty:g},constants:{OuterConstant:u}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Ug;const W=[];g(r)||(P=Ul,r?.forEach(wA=>{W.push({key:wA,value:"",seq:0})}));const oA=`convID:${m} messageID:${M} sequence:${D} time:${T} operateType:${P}`,EA=this._generateServerExtensions(s,W);try{let wA;if(E===u.CONV_C2C?wA=yield tu(s,EA,P):E===u.CONV_GROUP&&(wA=yield xu(s,EA,P)),wA){const{resultList:kA,successCount:xA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${oA}successCount:${xA} failCount:${LA}`}}}return{code:0,data:{extensions:[]}}}catch(wA){const{errorCode:kA}=wA;throw new this._core.helper.ChatError({functionName:"deleteMessageExtensions",code:kA,moreMessage:oA})}})}reset(){this._messageExtensionsMap.clear(),this._extensionsLatestSequenceMap.clear(),this._completedFetchExtensions.clear()}dispose(){this.reset();const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:u}}=this._core;s.unSubscribeInnerEvent(r,u,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,r){const{ID:g}=s,{Seq:u}=r,E=r.ExtensionList||[],m=[];let D=0,M=0,T=[];return E.forEach(P=>{const{ErrorCode:W,Extension:oA}=P,{Key:EA,Value:wA,Seq:kA}=oA;m.push({code:W,key:EA,value:wA}),W===0?D++:M++,T.push({key:EA,value:wA,seq:kA})}),this._extensionsLatestSequenceMap.set(g,u),T.length>0&&this._updateLocalExtensions(s.ID,T),{resultList:m,successCount:D,failureCount:M}}_updateLocalExtensions(s,r){this._messageExtensionsMap.has(s)||this._messageExtensionsMap.set(s,new Map);const g=this._messageExtensionsMap.get(s);r?.forEach(u=>{const{key:E,seq:m,value:D=""}=u;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,r){return mA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:u}}=this._core;try{let E;const{conversationType:m,ID:D}=s;if(m===g.CONV_C2C?E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Fs.core,{from:W,to:oA,clientSequence:EA,random:wA,time:kA}=M;return P({servcmd:"openim_msg_ext_http_svc.get_key_values",data:{From_Account:W,To_Account:oA,MsgKey:`${EA}_${wA}_${kA}`,StartSeq:T}})}(s,r):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Fs.core,{to:W,sequence:oA}=M;return P({servcmd:"openim_msg_ext_http_svc.group_get_key_values",data:{GroupId:W,MsgSeq:oA,StartSeq:T}})}(s,r)),E){const{LatestSeq:M,ClearSeq:T,CompleteFlag:P}=E,W=(E.ExtensionList||[]).map(EA=>({key:EA.Key,value:EA.Value,seq:EA.Seq}));if(this._updateLocalExtensions(D,W),this._clearLocationExtensions(D,T),this._extensionsLatestSequenceMap.set(D,M),P!==1){const EA=W[W.length-1].seq+1;return this._fetchMessageExtensions(s,EA)}const oA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((wA,kA)=>{const{value:xA}=wA;u(xA)||oA.push({key:kA,value:xA})})}return oA}}catch(E){throw E}})}_clearLocationExtensions(s,r){if(!(r<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((u,E)=>{u.seq<=r&&g.delete(E)})}}_generateServerExtensions(s,r){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const u=this._messageExtensionsMap.get(g);return r.map(E=>{var m;const{key:D,value:M}=E;let T=0;return u?.has(D)&&(T=(m=u.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return r.map(u=>({Key:u.key,Value:u.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:r,constants:g}=this._core;if(!r.checkBusinessCapabilityBits(pC))throw new r.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:r,DeleteKVInfo:g,ClearKVInfo:u,MsgOptType:E,TinyId:m,MsgLastSeq:D,ExtensionC2cMsgInfo:M,ExtensionGroupMsgInfo:T}=s?.MsgExtensionNotify||{},P=M||T||{},{MsgClientTime:W,MsgRandom:oA}=P,EA=`${m}-${W}-${oA}`;this._extensionsLatestSequenceMap.set(EA,D),E===Ll?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:r}):E===Ul?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Ug&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:u})}_handleMessageExtensionsUpdated(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,updateMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push({key:P.Key,value:P.Value}),{key:P.Key,value:P.Value,seq:P.Seq}));this._updateLocalExtensions(u,T)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:u,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:r,OuterEvent:g}=this._core,{messageID:u,deleteMessageExtensionsInfo:E=[]}=s,m=[];E.forEach(D=>{const{MsgKeyValue:M=[]}=D,T=M.map(P=>(m.push(P.Key),{key:P.Key,seq:P.Seq}));this._updateLocalExtensions(u,T)}),r.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:u,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:r,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:u}}=this._core,{messageID:E,clearMessageExtensionsInfo:m=[]}=s,D=[];m.forEach(M=>{const{ClearMsgSeq:T}=M;this._messageExtensionsMap.has(E)&&(this._messageExtensionsMap.get(E)||[]).forEach((P,W)=>{P.seq<=T&&!u(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),r.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const mI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:r}}=Fs.core;return s.status!==r.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},sl={setMessageExtensions:[mI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[mI],deleteMessageExtensions:[mI]},nl=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:[{required:!0,rules:["array"],allowEmpty:!1}],revokeMessage:[{required:!0,rules:["object"],allowEmpty:!1}],resendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],getMessageList:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},nextReqMessageID:{required:!1,rules:["string"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},getMessageListHopping:{conversationID:{required:!0,rules:["string"],allowEmpty:!1},sequence:{required:!1,rules:["number"],allowEmpty:!0},direction:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}},createTextAtMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const r=function(g){var u;return typeof g?.text!="string"||typeof g.text=="string"&&((u=g?.text)===null||u===void 0?void 0:u.length)===0?"payload.text is invalid.":!0}(s);return r!==!0?r:!(s?.atUserList&&!Array.isArray(s.atUserList))||"atUserList should be an array or undefind."}}},findMessage:[{required:!0,rules:["string"],allowEmpty:!1}],translateText:{sourceTextList:{required:!0,rules:["array"],allowEmpty:!1},sourceLanguage:{required:!0,rules:["string"],allowEmpty:!1},targetLanguage:{required:!0,rules:["string"],allowEmpty:!1}},createForwardMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1}},createLocationMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{utils:{isString:r,isNumber:g}}=Fs.core;return r(s?.description)?g(s?.longitude)?!!g(s?.latitude)||"payload.latitude must be a number.":"payload.longitude must be a number.":"payload.description must be a string."}}}},{addMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],removeMessageReaction:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"reactionID",required:!0,rules:["string"],allowEmpty:!1}],getMessageReactions:{messageList:{required:!0,rules:["array"],allowEmpty:!1},maxUserCountPerReaction:{required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s!="number"?"maxUserCountPerReaction is invalid.":!(s<0||s>10)||"maxUserCountPerReaction should between [0, 10]."}},getAllUserListOfMessageReaction:{message:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>s.status==="success"||"message is invalid."},reactionID:{required:!0,rules:["string"],allowEmpty:!1},nextSeq:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0}}}),{sendMessageReadReceipt:[{required:!0,rules:["array"],allowEmpty:!1}],getMessageReadReceiptList:[{required:!0,rules:["array"],allowEmpty:!1}],getGroupMessageReadMemberList:{message:{required:!0,rules:["object"],allowEmpty:!1},filter:{required:!1,rules:["number"],allowEmpty:!0},count:{required:!1,rules:["number"],allowEmpty:!0},cursor:{required:!1,rules:["string"],allowEmpty:!0}}}),sl),{pinGroupMessage:{groupID:{required:!0,rules:["string"],allowEmpty:!1},message:{required:!0,rules:["object"],allowEmpty:!1},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},getPinnedGroupMessageList:[{key:"groupID",required:!0,rules:["string"],allowEmpty:!1}]}),{createQuoteMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"quotedMessage",required:!0,rules:["object"],allowEmpty:!1}]}),xa=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({deleteMessage:!0,revokeMessage:!0,resendMessage:!0,getMessageList:!0,getMessageListHopping:!0,createTextAtMessage:!0,findMessage:!0,translateText:!0,createForwardMessage:!0,createLocationMessage:!0},{addMessageReaction:!0,removeMessageReaction:!0,getMessageReactions:!0,getAllUserListOfMessageReaction:!0}),{sendMessageReadReceipt:!0,getMessageReadReceiptList:!0,getGroupMessageReadMemberList:!0}),{setMessageExtensions:!0,getMessageExtensions:!0,deleteMessageExtensions:!0}),{pinGroupMessage:!0,getPinnedGroupMessageList:!0}),{createQuoteMessage:!0});class UE{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:u};return this._core.common.buildAndSendPacket({servcmd:"openim.delete_c2c_msg_ramble",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,from:u,sequence:E,time:m,random:D}=r,M={MsgInfo:{From_Account:u,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class aa{constructor(r){this._core=r}deleteMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:u}=r,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:u};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_ramble_msg_by_seq",data:E})})}revokeMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,sequence:u}=r,E={GroupId:g,MsgSeqList:[{MsgSeq:u}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class kr{constructor(r){this._core=r}generateRevokeMessage(r){const{conversationID:g,sequence:u,random:E,tinyID:m,clientTime:D,revokeReason:M,revoker:T}=r;let P={};const{messageDataHandler:W}=this._core.message;return P=W.revokeMessage({conversationID:g,sequence:u,random:E,revoker:T}),P||(P={conversationID:g,sequence:u},m&&D&&E&&(P.ID=`${m}-${D}-${E}`)),P.revoker=T,P.revokeReason=M,P.revokerInfo={userID:T,nick:"",avatar:""},P}updateRevokerInfo(r){return mA(this,void 0,void 0,function*(){const g=r.map(u=>u.revoker);try{const u=yield this._fetchUserInfos(g);u&&r.forEach(E=>{const{revoker:m}=E;u[m]&&(E.revokerInfo.nick=u[m].nick||"",E.revokerInfo.avatar=u[m].avatar||"",E.revokerInfo.userID=m)})}catch(u){console.debug(u)}})}_fetchUserInfos(r){return mA(this,void 0,void 0,function*(){var g,u;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:r});return E?.data?(u=E.data)===null||u===void 0?void 0:u.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var rl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new aa(s),this._c2cMessageAction=new UE(s),this._messageHelper=new kr(s);const{helper:r}=s;r.registerApi({apiName:"deleteMessage",context:this}),r.registerApi({apiName:"revokeMessage",context:this}),r.registerApi({apiName:"resendMessage",context:this}),r.registerApi({apiName:"findMessage",context:this}),r.registerApi({apiName:"createQuoteMessage",context:this})}deleteMessage(s){return mA(this,void 0,void 0,function*(){let r=[],g=[];const{conversationID:u,conversationType:E}=s[0],m=u.replace(E,"");if(E==="@TIM#SYSTEM")throw new this._core.helper.ChatError({code:Mn});if(s.forEach(D=>{const{conversationID:M,conversationType:T,status:P,_onlineOnlyFlag:W,sequence:oA,random:EA,time:wA}=D||{};if(P==="success"&&M===u&&T===E){if(!W){const kA=T==="C2C"?`${oA}_${EA}_${wA}`:String(oA);r.push(kA)}g.push(D)}}),r.length===0)return this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}};r.length>30&&(r=r.slice(0,30),g=g.slice(0,30));try{return E==="C2C"?yield this._c2cMessageAction.deleteMessage({to:m,messageIdentifiers:r}):yield this._groupMessageAction.deleteMessage({to:m,messageIdentifiers:r}),this._handleDeleteMessageSuccess(g),{code:0,data:{messageList:g}}}catch(D){const{utils:{safeStringify:M}}=this._core,{errorCode:T,errorInfo:P}=D;throw new this._core.helper.ChatError({functionName:"deleteMessage",code:T,message:P,moreMessage:`messageIdentifiers: ${M(r)}`})}})}revokeMessage(s){return mA(this,void 0,void 0,function*(){var r;const{conversationType:g,isRevoked:u,ID:E,type:m,from:D,to:M}=s;let T=null;const P=`type:${m} from:${D} to:${M} ID:${E}`;if(g==="@TIM#SYSTEM")throw new this._core.helper.ChatError({message:"system message cannot be revoked"});if(u)throw new this._core.helper.ChatError({message:"message has been revoked",moreMessage:P});try{if(T=g==="C2C"?yield this._c2cMessageAction.revokeMessage(s):yield this._groupMessageAction.revokeMessage(s),T){const{RecallRetList:W}=T,oA=((r=W?.[0])===null||r===void 0?void 0:r.RetCode)||0;if(oA!==0)throw new this._core.helper.ChatError({code:oA,moreMessage:P});return s.isRevoked=!0,yield this._handleRevokeMessageSuccess(s),{code:0,data:{message:s},successLog:{message:P}}}}catch(W){const{errorCode:oA}=W;throw new this._core.helper.ChatError({functionName:"revokeMessage",code:oA,moreMessage:P})}})}resendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u;return s.isResend=!0,s.status="unSend",(u=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||u===void 0?void 0:u.sendMessage(s,r)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,r){const{ID:g,time:u,sequence:E}=r;return s.quoteInfo={msgID:g,messageTime:u,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:r},common:{isTopic:g},notificationCenter:u,InnerEvent:E}=this._core;s.forEach(D=>{D.isDeleted=!0;const M=r.getLocalMessageList(D.conversationID);M?.forEach(T=>{T.ID===D.ID&&(T.isDeleted=!0)})});const{conversationID:m=""}=s[0];g(m)?u.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):u.emitInnerEvent(E.MESSAGE_DELETED,m)}_handleRevokeMessageSuccess(s){return mA(this,void 0,void 0,function*(){var r;const g=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,{conversationID:u,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:u,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class Fl{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Index:u,Data:E}=g;return new Fl({index:u,data:E})}constructor(r){this.type=Vr.MSG_FACE;const{index:g,data:u}=r;this.content={index:g,data:u}}validateBeforeSend(){var r,g;return typeof((r=this.content)===null||r===void 0?void 0:r.index)=="number"&&typeof((g=this.content)===null||g===void 0?void 0:g.data)=="string"?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{index:E,data:m}=u;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class bc{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Desc:u,Longitude:E,Latitude:m}=g;return new bc({description:u,longitude:E,latitude:m})}constructor(r){this.type=Vr.MSG_LOCATION;const{description:g,longitude:u,latitude:E}=r;this.content={description:g,longitude:u,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=u;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class FE{static parseServerPushElement(r){const{MsgContent:g={}}=r,{StreamMsgID:u,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new FE({streamMessageID:u,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(r){this.type=Vr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:u,markdown:E,binaryData:m,errorCode:D=0,errorMessage:M="",isStreamEnded:T=!1,chunks:P=[],latestIndex:W=0}=r;this.content.streamMessageID=g,this.content.compatibleText=u,this.content.markdown=E,this.content.binaryData=m,this.content.errorCode=D,this.content.errorMessage=M,this.content.isStreamEnded=T,this.content.chunks=P,this.content.latestIndex=W}updateChunks(r){if(!r||r.length===0)return;const g=r.sort((m,D)=>m.index-D.index),u=this._getMaxRevokedChunkIndex(g);u>=0&&(this._chunks=[],this._latestIndex=u,this._updateContent());const E=this._getValidChunks(g);if(E.length!==0&&(this._mergeAndSortChunks(E),this._chunks.length>0)){const m=this._chunks[this._chunks.length-1];this._latestIndex=m.index,this._updateContent(),this.content.isStreamEnded=m.isLast}}getLatestIndex(){return this._latestIndex}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{streamMessageID:E,chunks:m}=u,D=m?.map(M=>({EventType:M.eventType||"data",Index:M.index,Markdown:M.markdown,IsLast:M.isLast}));return{MsgType:this.type,MsgContent:{StreamMsgID:E,Chunks:D}}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.chunks)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content is invalid"}}}_filterContinuousChunks(r,g){if(r.length===0)return[];const u=[];let E=g;for(const m of r){if(m.index>E)break;m.index===E&&(u.push(m),E++)}return u}_mergeAndSortChunks(r){const g=new Map;this._chunks.forEach(u=>{g.set(u.index,u)}),r.forEach(u=>{g.set(u.index,u)}),this._chunks=Array.from(g.values()).sort((u,E)=>u.index-E.index)}_updateContent(){this.content.markdown=this._chunks.map(g=>g.markdown).join("");const r=this._chunks.map(g=>g.binaryData).filter(g=>g?.length>0);if(r.length===0)this.content.binaryData=new Uint8Array(0);else if(r.length===1)this.content.binaryData=r[0];else{const g=r.reduce((m,D)=>m+D.length,0),u=new Uint8Array(g);let E=0;for(const m of r)u.set(m,E),E+=m.length;this.content.binaryData=u}}_getMaxRevokedChunkIndex(r){let g=-1;for(let u=0;ug&&(g=E.index)}return g}_getValidChunks(r){const g=r.filter(u=>u.eventType===Nc.DATA&&u.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var kc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Vr.MSG_FACE,Fl),s.message.messageFactory.registerElementClass(Vr.MSG_LOCATION,bc),s.message.messageFactory.registerElementClass(Vr.MSG_STREAM,FE),s.helper.registerApi({apiName:"createFaceMessage",context:this}),s.helper.registerApi({apiName:"createTextAtMessage",context:this}),s.helper.registerApi({apiName:"createForwardMessage",context:this}),s.helper.registerApi({apiName:"createLocationMessage",context:this})}createFaceMessage(s){if(!s)return null;const{index:r,data:g}=s?.payload||{},u=new Fl({index:r,data:g}),E=this._core.common.getCurrentUserID(),m=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}createTextAtMessage(s){const{atUserList:r}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:u}=this._core;if(!g)return null;if(Array.isArray(r)){const E=[],m=[];r.forEach(D=>{D!==u.MSG_AT_ALL?(E.push({GroupAtAllFlag:uh,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:go}),m.push(u.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:r,OuterConstant:g}=this._core,{to:u,conversationType:E,priority:m,payload:D,needReadReceipt:M,receiverList:T,cloudCustomData:P="",isSupportExtension:W=!1}=s;if(!Array.isArray(D._elements))throw new r.ChatError({functionName:"createForwardMessage",code:2454});if(D.type===g.MSG_GRP_TIP)throw new r.ChatError({functionName:"createForwardMessage",code:2453});const oA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:u,from:oA,conversationType:E,isPlaceMessage:0,priority:m,payload:D,needReadReceipt:M,isSupportExtension:W,cloudCustomData:P,receiverList:T});return EA.setRelayFlag(!0),EA.setElement(D._elements[0]),EA}createLocationMessage(s){if(!s)return null;const{description:r,longitude:g,latitude:u}=s?.payload||{},E=new bc({description:r,longitude:g,latitude:u}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Yu=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:u},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(g,u,this._handleC2CNotifyMessage,this),E(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,this._handleC2CRevokeMessagesFromUnreadMessageSync,this)}_handleC2CNotifyMessage(s){const{C2cNotifyMsgArray:r}=s;r?.forEach(g=>{Object.keys(g).includes("WithdrawC2cMsgNotify")&&this._handleC2CRevokeMessage(g)})}_handleC2CRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{WithdrawC2cMsgNotify:{C2cWithdrawInfoArray:r}}=s;yield this._parseAndEmitC2CRevokedMessages(r)}catch(r){console.debug(r)}})}_parseAndEmitC2CRevokedMessages(s){return mA(this,void 0,void 0,function*(){const r=[],{notificationCenter:g,OuterEvent:u,common:{getCurrentUserID:E}}=this._core;s.forEach(m=>{var D;const{MsgRand:M,MsgSeq:T,To_Account:P,From_Account:W,RevokerInfo:{Revoker_Account:oA,Revoke_Reason:EA}}=m,wA=E()===W?`C2C${P}`:`C2C${W}`,kA=((D=m?.RevokerInfo)===null||D===void 0?void 0:D.Reason)||EA,xA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:T,random:M,revoker:oA,revokeReason:kA});r.push(xA)}),r.length>0&&(yield this._messageHelper.updateRevokerInfo(r),g.emitOuterEvent(u.MESSAGE_REVOKED,{name:u.MESSAGE_REVOKED,data:r}))})}_handleC2CRevokeMessagesFromUnreadMessageSync(s){return mA(this,void 0,void 0,function*(){const{revokedMessageList:r}=s.result;yield this._parseAndEmitC2CRevokedMessages(r)})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{C2C_REVOKED_MESSAGE:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleC2CNotifyMessage,this)}},yC=class{init(s){this._messageHelper=new kr(s),this._core=s;const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:u}}=s;r.subscribeInnerEvent(g,u,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:r}=s;r?.forEach(g=>{var u;Array.isArray((u=g?.MsgBody)===null||u===void 0?void 0:u.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return mA(this,void 0,void 0,function*(){try{const{RevokerInfo:r,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:u}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;u&&(W=P({groupID:u.GroupId})||!T(u.TopicId)),g.forEach(oA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:xA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=r?.Revoker_Account||"",Reason:qA=r?.Reason||""}}=oA,Ie=SA?`GROUP${SA}`:`GROUP${kA}`,le=this._messageHelper.generateRevokeMessage({conversationID:Ie,sequence:wA,random:EA,tinyID:LA,clientTime:xA,revoker:OA,revokeReason:qA});W?(le.revokerInfo.nick=u.From_AccountNick,le.revokerInfo.avatar=u.From_AccountHeadurl,E.push(le)):m.push(le)}),m.length>0&&(yield this._messageHelper.updateRevokerInfo(m),E.push(...m)),E.length!==0&&D.emitOuterEvent(M.MESSAGE_REVOKED,{name:M.MESSAGE_REVOKED,data:E})}catch(r){console.debug(r)}})}dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r},InnerEventSubType:{GROUP_MESSAGE_REVOKED:g}}=this._core;s.unSubscribeInnerEvent(r,g,this._handleGroupNotifyMessage,this)}};var iu=new class{constructor(){this._c2cMessageReceiver=new Yu,this._groupMessageReceiver=new yC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},Eh=new class{constructor(){this._core=null}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"translateText",context:this})}translateText(s){return mA(this,void 0,void 0,function*(){try{const{sourceLanguage:r,sourceTextList:g,targetLanguage:u}=s,E=yield function(m,D){return mA(this,void 0,void 0,function*(){var M,T;const{sourceTextList:P,sourceLanguage:W,targetLanguage:oA}=m,{store:EA,common:wA}=D,kA={SourceText:P,Source:W,Target:oA,FromAccount:(M=EA.get("login"))===null||M===void 0?void 0:M.tinyID,SDKAppID:(T=EA.get("instance"))===null||T===void 0?void 0:T.sdkAppId},xA=yield wA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(xA){const{CmdErrorCode:LA,TargetText:SA}=xA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:r,sourceTextList:g,targetLanguage:u},this._core);if(E){const{cmdErrorCode:{ErrorCode:m,ErrorInfo:D},translatedTextList:M}=E;if(m===0)return{code:0,data:{translatedTextList:M}};throw{errorCode:m,errorInfo:D,message:D}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:u})}})}},Vu=new class{init(s){this._core=s,s.helper.registerApi({apiName:"convertVoiceToText",context:this})}convertVoiceToText(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,language:u=Tc.ZH_PY}=s;let{url:E}=g.payload||{};const m=this._core.common.getCurrentUserID();g.from===m&&g.flow==="out"&&(E=g.payload.remoteAudioUrl),this._validateVoiceFormat(E);const D=((r=pI.exec(E))===null||r===void 0?void 0:r[1])||"mp3",M=QI[u]||Au;try{const T=yield function(P){var W;const{store:oA,common:EA}=Fs.core,{url:wA,format:kA,serverLanguageType:xA}=P,LA={BytesUrl:wA,BytesEngServiceType:xA,BytesVoiceFormat:kA,Uint32Sdkappid:(W=oA.get("instance"))===null||W===void 0?void 0:W.sdkAppId,Uint64SourceType:0};return EA.buildAndSendPacket({servcmd:"im_open_speech.ws_sentence_recognition",data:LA})}({url:E,format:D,serverLanguageType:M});if(T){const{CmdErrorCode:P,BytesResult:W}=T;if(P.ErrorCode===0)return{code:0,data:{result:W}};throw{code:P.ErrorCode,message:P.ErrorInfo}}}catch(T){const{code:P,message:W}=T||{};throw new this._core.common.ChatError({functionName:"convertVoiceToText",code:P,message:W})}})}_validateVoiceFormat(s){if(!pI.test(s))throw new this._core.common.ChatError({code:2119})}};class fI{constructor(r){const{constants:g,common:u,utils:E}=Fs.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:oA=u.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:xA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:qA,_elements:Ie,time:le}=r;this.ID=M||`${T}-${oA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=le,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=oA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=xA;const bi=E.deepCopyWithMethods(Ie);bi.forEach(ki=>{ki.payload=ki.content,delete ki.content}),this.messageBody=bi,M?OA.startsWith(m)?this.receiverUserID=W:OA.startsWith(D)&&(this.receiverGroupID=W):qA?(this.receiverGroupID=qA,this.messageReceiver=qA):W&&(this.receiverUserID=W,this.messageReceiver=W)}transformElementsToServerFormat(){return this.messageBody?Array.isArray(this.messageBody)?this.messageBody.map(r=>r.transformToServerFormat({isMergerMessage:!0})):this.messageBody.transformToServerFormat({isMergerMessage:!0}):null}}class al{static parseServerPushElement(r){const{MsgContent:g}=r,{MsgList:u=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=u.map(W=>Qr(W));return new al({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(r){this.type=Fs.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:u,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=r,W=[];g.forEach(oA=>{if(oA){const EA=new fI(oA);W.push(EA)}}),this.content={messageList:W,title:u,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:r}=Fs.core.helper;return r(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:oA}=u;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:Ac(oA)}}}}var DC=new class{init(s){this._core=s;const{message:r,helper:g,constants:{OuterConstant:u}}=s;r.messageFactory.registerElementClass(u.MSG_MERGER,al),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===u.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:r}=this._core;if(!s)return null;const g=new al(s.payload),u=r.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:u}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{const m=function(P){let W="utf-8";Fs.core.helper.IN_BROWSER&&document&&(W=document.charset.toLowerCase());let oA,EA=0,wA=0;if(wA=P.length,W==="utf-8"||W==="utf8")for(let kA=0;kA11264){D=this._core.utils.deepCopyWithMethods(s);try{const{JsonMsgKey:P,PbMsgKey:W}=yield function(EA){return mA(this,void 0,void 0,function*(){const{payload:{messageList:wA}}=EA,kA={MsgList:Ac(wA)};return Fs.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:oA}=D;M=new al(Object.assign(Object.assign({},oA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(D,r);return M&&T.setElement(s._elements),{code:0,data:{message:T}}}catch(m){const{errorCode:D}=m;throw new this._core.helper.ChatError({code:D})}})}downloadMergerMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,g=s.payload,{downloadKey:u,pbDownload:E,type:m,messageList:D}=g,M=So(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(oA){return mA(this,void 0,void 0,function*(){return Fs.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:oA}})})}(u),{MsgList:P}=T||{},W=P?.map(oA=>{const EA=Qr(oA);return new fI(EA)});return typeof s.isOnlineMessage=="function"?s.setElement({type:s.type,content:Object.assign({messageList:W},M)}):(s.payload.messageList=W,s.payload.downloadKey="",s.payload.pbDownloadKey=""),r.info("downloadMergerMessage",` success downloadKey:${u}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:u})}})}},ga=new class{init(s){this._core=s,this._core.helper.registerExperimentalAPI("sendComboMessage",this)}sendComboMessage(s){return mA(this,void 0,void 0,function*(){const{appStore:r,message:g,common:{getCurrentUserID:u},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||u();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=r.userStore.getUserProfile(u());M.level=T?.level||0,E(D)&&D.length>0&&(M._receiverList=D)}else D&&(M=this._generateC2CMessage(s));return g.messageSender.sendMessage(M,s)})}_generateC2CMessage(s){const{message:r,OuterConstant:{CONV_C2C:g}}=this._core,u=g,E=r.messageHelper.parseServerPushMessage(s),m=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:r,OuterConstant:{CONV_GROUP:g}}=this._core,u=g,E=r.messageHelper.parseServerGroupMessage(s),m=r.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:u,flow:ec.OUT})),{elements:D}=E;return m.setElement(D),m}},tc=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:u},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(u,E,this._handleGroupMessagePinned,this),r.registerApi({apiName:"pinGroupMessage",context:this}),r.registerApi({apiName:"getPinnedGroupMessageList",context:this})}pinGroupMessage(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,common:{isTopic:g},OuterConstant:{GROUP_ID_PREFIX:u},helper:{ChatError:E}}=this._core;let{groupID:m,message:D,isPinned:M}=s;const{sequence:T}=D;try{return yield function(P){return mA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:W,getCurrentUserID:oA}}=Fs.core,{groupID:EA,sequence:wA,isPinned:kA}=P,xA=oA(),LA=kA?"group_open_http_svc.pin_message":"group_open_http_svc.unpin_message",SA={GroupId:EA,MsgSeq:wA};return kA?SA.Pinner_Account=xA:SA.UnPinner_Account=xA,W({servcmd:LA,data:SA})})}({groupID:m,sequence:T,isPinned:M}),{code:0,data:{}}}catch(P){const{errorCode:W,errorInfo:oA}=P||{};throw new E({code:W,message:oA})}})}getPinnedGroupMessageList(s){return mA(this,void 0,void 0,function*(){let r=[];try{const g=yield function(u){return mA(this,void 0,void 0,function*(){const{groupID:E}=u,{common:{buildAndSendPacket:m}}=Fs.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:u=[]}=g;r=yield this._updatePinnedMessageInfo({serverPinnedMessageList:u,groupID:s})}return{code:0,data:{messageList:r}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:r,messageFactory:g},notificationCenter:u,OuterEvent:E,OuterConstant:m}=this._core;s.GroupTips.forEach(D=>{const{ToGroupId:M,MsgBody:{PinnedMsg:T,OpType:P,MsgOperatorMemberExtraInfo:W,SdkGroupMessageId:oA}}=D,{UserId:EA,NickName:wA="",ImageUrl:kA=""}=W;let xA=null,LA=!1;if(P===md){LA=!0;const SA=r.parseServerGroupMessage(T);xA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),xA.setElement(SA.elements),xA.pinnerInfo={userID:EA,nick:wA,avatar:kA}}else if(P===kE){const{ClientTime:SA,Random:OA,SenderTinyId:qA,ServerTime:Ie,MsgSeq:le}=oA;xA={ID:`${qA}-${SA}-${OA}`,sequence:le,random:OA,time:Ie,clientTime:SA}}xA&&u.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:xA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,r){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(u=>u.sequence===r)}_updatePinnedMessageInfo(s){return mA(this,arguments,void 0,function*({serverPinnedMessageList:r,groupID:g}){const{OuterConstant:{CONV_GROUP:u},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${u}${g}`;for(let oA=0;oA{const{sequence:kA}=wA,xA=T.get(kA),LA=oA[xA]||{userID:xA,nick:"",avatar:""};wA.pinnerInfo=LA}),m.sort((wA,kA)=>wA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return mA(this,void 0,void 0,function*(){var r,g;const{message:{messageHistory:u},user:{userProfile:E},utils:{isArray:m}}=this._core,{conversationID:D,messageSequenceList:M,pinnerIDList:T}=s,P=yield Promise.all([this._fetchMessageBySequence({conversationID:D,messageSequenceList:M}),E?.getUserProfile({userIDList:T})]);if(m(P)){const W={};return(((r=P[1])===null||r===void 0?void 0:r.data)||[]).forEach(oA=>{const{userID:EA,nick:wA="",avatar:kA=""}=oA;W[EA]={userID:EA,nick:wA,avatar:kA}}),{messageList:((g=P[0])===null||g===void 0?void 0:g.messageList)||[],pinnerInfoMap:W}}})}_fetchMessageBySequence(s){return mA(this,void 0,void 0,function*(){const{utils:{isEmpty:r},message:{messageHistory:g}}=this._core,{conversationID:u,messageSequenceList:E}=s;return r(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:u,messageSequenceList:E,getType:3})})}};class lg{constructor(r){this.eventType=Nc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:u,Markdown:E,IsLast:m,BinaryData:D}=r;this.eventType=g,this.index=u,this.markdown=E,this.isLast=m,this.binaryData=D}}var yI=new class{constructor(){this._messageMap=new Map,this._retryCountMap=new Map}init(s){this._core=s;const{notificationCenter:r,OuterEvent:{MESSAGE_RECEIVED:g},InnerEvent:{HISTORY_MESSAGE_FETCHED:u},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;r.subscribeInnerEvent(Io,this._handleStreamMessageChunkPush,this),r.subscribeOuterEvent(g,this._handleMessageReceived,this),r.subscribeInnerEvent(u,this.processHistoryMessage,this),E.registerWorkflowStep(m.SYNC_SERVER_INFO_AFTER_RE_ONLINE,D.STREAM_MESSAGE_RECOVER,this._recoverStreamMessage,this)}processHistoryMessage(s){const{utils:{isEmpty:r,safeStringify:g},ssoLog:u}=this._core;try{s?.forEach(E=>{var m;if(this._isValidStreamMessage(E)){const D=(m=E?._elements)===null||m===void 0?void 0:m[0],{streamMessageID:M,markdown:T,binaryData:P}=D?.content||{};r(T)&&r(P)?(this._messageMap.set(M,E),this._fetchStreamMessageChunks(E)):D.content.isStreamEnded=!0}})}catch(E){u.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const r=s.data;r?.forEach(g=>{var u,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(u=g?._elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.content)||{};m&&(this._messageMap.set(m,g),this._fetchStreamMessageChunks(g))}})}_isValidStreamMessage(s){var r,g;const{utils:{isEmpty:u}}=this._core,{streamMessageID:E}=((g=(r=s?._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g.content)||{};return s.type===Vr.MSG_STREAM&&!u(E)}_fetchStreamMessageChunks(s){return mA(this,void 0,void 0,function*(){var r,g;const{constants:{ERROR_CODE:u},ssoLog:E,utils:{safeStringify:m}}=this._core,D=(r=s._elements)===null||r===void 0?void 0:r[0],M=(g=D?.content)===null||g===void 0?void 0:g.streamMessageID;try{const{from:T,to:P}=s,W=D.getLatestIndex();if(D.content.isStreamEnded)return;const oA=yield function(EA){return mA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:xA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:xA,AckIndex:LA};return Fs.core.common.buildAndSendPacket({servcmd:"StreamMsg.GetStreamHttp",data:SA,timeout:5e3})})}({from:T,to:P,streamMessageID:M,index:W});if(oA){const{ErrorCode:EA,ErrorInfo:wA}=oA;if(EA!==0)throw D.content.errorCode=EA,D.content.errorMessage=wA,{errorCode:EA,errorMessage:wA}}}catch(T){if(T.errorCode===u.NETWORK_TIMEOUT&&this._shouldRetryFetch(M)){const P=this._retryCountMap.get(M)||0;E.debug("_fetchStreamMessageChunks.timeout",`error: ${m(T)} retried: ${P}`),this._retryCountMap.set(M,P+1),this._fetchStreamMessageChunks(s)}else E.error("_fetchStreamMessageChunks.error",m(T))}})}_shouldRetryFetch(s){const{utils:{isNumber:r}}=this._core;if(!this._retryCountMap.has(s))return this._retryCountMap.set(s,1),!0;const g=this._retryCountMap.get(s);return!!(r(g)&&g<=3)}_onStreamEnded(s,r,g){const{ssoLog:u}=this._core;g.content.isStreamEnded=!0,g.stopReason=r,this._messageMap.delete(s),u.debug("_onStreamEnded",`streamMessage end, StopReason: ${r}`)}_handleStreamMessageChunkPush(s){var r;const{ssoLog:g}=this._core,{StopReason:u,Chunks:E,StreamID:m}=s?.body||{},D=this._messageMap.get(m);if(!D)return void g.warn(`_handleStreamMessageChunkPush, unfounded message: ${m}`);const M=(r=D._elements)===null||r===void 0?void 0:r[0];if(M&&this._validateExpectedChunk(M,E)){if(E.length>0){const T=E.map(P=>new lg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){mA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:oA},ssoLog:EA,channel:wA}=Fs.core,kA={StreamMsgID:T,AckIndex:P};try{const xA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(xA)}catch(xA){EA.debug("sendStreamChunkAck",oA(xA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,u,M)}}_emitMessageModify(s){const{notificationCenter:r,OuterEvent:{MESSAGE_MODIFIED:g}}=this._core;r.emitOuterEvent(g,{name:g,data:[s]})}_validateExpectedChunk(s,r){const g=s.getLatestIndex()+1;let u=!1;for(let E=0;Em.Index).join(", ")}]`),!1}return!0}_recoverStreamMessage(){this._retryCountMap.clear();const{ssoLog:s,utils:{safeStringify:r}}=this._core;try{const g=Array.from(this._messageMap.entries());for(let u=Math.max(0,g.length-300);u{const LA=this._getResponseBody(kA,E,oA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)r(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,EA),s.uploadByIP=!0,this.request(s,r);r({code:kA.status,message:JSON.stringify(kA.responseText)},SA)}},kA.onerror=()=>{const LA=this._getResponseBody(kA,E,oA&&EA),SA=this._buildResponse(kA,LA),OA={code:kA.status,message:kA.status===0?"CORS blocked or network error":JSON.stringify(kA.responseText)};r(OA,SA)},s.onProgress&&kA.upload&&(kA.upload.onprogress=LA=>{const{total:SA,loaded:OA}=LA,qA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:qA/100})}),kA.send(P),kA})}_buildResponse(s,r){const g={};return s.getAllResponseHeaders().trim().split(` +`).forEach(u=>{if(u){const[E,m]=u.split(":").map(D=>D.trim());g[E.toLowerCase()]=m}}),{statusCode:s.status,statusMessage:s.statusText,headers:g,data:r}}_getResponseBody(s,r,g){return s.status===200&&r?{location:r,uploadIP:g}:{response:s.responseText,uploadIP:g}}_queryString(s,r="&",g="="){var u;const{isEmpty:E,isPlainObject:m}=(u=this._core)===null||u===void 0?void 0:u.utils;return E(s)?"":m(s)?Object.keys(s).map(D=>{const M=encodeURIComponent(D)+g;return Array.isArray(s[D])?s[D].map(T=>M+encodeURIComponent(T)).join(r):M+encodeURIComponent(s[D])}).filter(Boolean).join(r):void 0}_domainName2IP(s,r){return s.replace(/^http(s)?:\/\/(.*?)\//,`https://${r}/`)}};const Hu=["unknown","image","video","audio","log"];var DI=new class{init(s){this._core=s}request(s,r){var g;const{MINI_APP_NAMESPACE:u,IN_ALIPAY_MINI_APP:E,isUniIOSApp:m}=(g=this._core)===null||g===void 0?void 0:g.utils,{resources:D="",headers:M={},url:T,downloadUrl:P=""}=s;let W=T,oA=null;const EA=P?P.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/):null;if(!EA)return void console.warn("message Invalid download URL format");const wA=decodeURIComponent(EA[3]),kA=wA.includes("?")?wA.split("?")[0]:wA||"",xA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,qA]=T.split("?sign=");qA&&(W=`${OA}?sign=${encodeURIComponent(qA)}`,LA.sign=decodeURIComponent(qA),LA.signature=decodeURIComponent(qA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},xA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,qA=So(SA,["name"]);SA=Object.assign(Object.assign({},qA),{fileName:"file",fileType:s.fileType?Hu[s.fileType]:"image"})}return oA=u.uploadFile(Object.assign(Object.assign({},SA),{success:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:r})},fail:OA=>{this._handleResponse({response:OA,downloadUrl:P,callback:r})}})),oA.onProgressUpdate&&oA.onProgressUpdate(OA=>{s.onProgress&&s.onProgress({total:OA.totalBytesExpectedToSend||0,loaded:OA.totalBytesSent||0,percent:OA.progress?Math.floor(OA.progress)/100:0})}),oA}_handleResponse(s){const{downloadUrl:r,response:g,callback:u}=s,E={};if(g.header)for(const D in g.header)g.header.hasOwnProperty(D)&&(E[D.toLowerCase()]=g.header[D]);const m=+g.statusCode;m===200?u(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:r})}):u({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function gl(s){return function(r){return Object.prototype.toString.call(r).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Lr(s){const r=s||99999999;return Math.round(Math.random()*r)}function Ur(s,r=!0,g=!0){const u=Date.now();return r?g?u-s+" ms":`${Math.round((u-s)/1e3)} s`:g?u-s:Math.round((u-s)/1e3)}function Ig(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function lr(s,r){return Math.round(Number(s)*10**r)/10**r}function _r(s){return s<=1048576?`${lr(s/1024,1)}KB/s`:`${lr(s/1048576,1)}MB/s`}const ic="TIMImageElem",Fg="TIMSoundElem",Ya="TIMFileElem",Ol="TIMVideoFileElem",ha="RichMediaMessagePlugin",SI=["rich.my-imcloud.com","imrich.qcloud.com"],ou=1,Ba=2,cl=3,PE=255;var su;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(su||(su={}));const xE={wechat:/^(wxfile:\/\/tmp_|http:\/\/temp\/|cloud:\/\/temp-)/,alipay:/^(https:\/\/resource\/|alipayfile:\/\/tmp\/)/,baidu:/^(http:\/\/tmp\/|swanfile:\/\/tmp_)/,bytedance:/^(ttfile:\/\/tmp_|\/(var|tmp)\/|tttemp:\/\/)/,qq:/^(qqfile:\/\/tmp_|http:\/\/qtemp\/)/},Jr=Symbol("isCustomUpload");var nu,xt=new class{init(s){this._core=s}addAuthToUrl(s=""){if(this._isMiniProgramTempFile(s))return s;const r=function(g){return g?g.startsWith("https://")?g:g.startsWith("http://")?g.replace("http://","https://"):g:""}(s);return this.processResourceUrl(r)}removeAuthToUrl(s){return function(r,g){const[u,E]=r.split("?");if(!E)return u;const m=E.split("&").reduce((M,T)=>{const[P,W]=T.split("=");return P&&P!==g&&(M[P]=W||""),M},{}),D=Object.keys(m).map(M=>`${M}${m[M]?`=${m[M]}`:""}`).join("&");return D?`${u}?${D}`:u}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(xE).some(r=>r.test(s))}extractFileFromInput(s){const{utils:{isArray:r}}=this._core;return gl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const u=Object.getPrototypeOf(g);if(u===null)return!0;let E=u;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return u===E}(s)&&typeof uni<"u"?r(s.tempFiles)&&s.tempFiles.length>0?s.tempFiles[0]:r(s.files)?s.files[0]:s.tempFile?s.tempFile:null:s instanceof HTMLInputElement&&s.files&&s.files.length>0?s.files[0]:null}probeImageWidthHeight(s){return mA(this,void 0,void 0,function*(){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:u?this._probeImageDimensionsWeb(s):g?this._probeImageDimensionsMiniApp(s):void 0})}isSimpleCos(){var s;const r=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{simple_cos:g}=r;return g!=="0"}getFileDNList(){var s;let r=SI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:u}=g;if(u===void 0)return r;try{JSON.parse(u).forEach(E=>{r.includes(E)||r.push(E)})}catch(E){console.warn(E),r=SI}return r}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,r){var g;let u=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(r)return`${u}.${r}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(u=`${u}.${m}`),u}processResourceUrl(s){if(!s)return"";let r=s;const g=this.getFileDownloadProxy(),u=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?r=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(r=s.replace(/^https:\/\/[^/]+/,g))),u&&r.indexOf("authKey=")===-1&&function(D,M){let T=!1;if(D){const P=D.match(/:\/\/([0-9]?\.)?(.[^/:]+)/),W=P&&P[2]||"";if(W.includes("rich-dev"))return!0;for(let oA=0;oA-1?`${r}&authKey=${u}`:`${r}?authKey=${u}`),r}getCurrentUserID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.userId}getSDKAppID(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.sdkAppId}getFileDownloadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileDownloadProxy)||""}getFileUploadProxy(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.fileUploadProxy)||""}getAuthKey(){var s,r;return((r=(s=this._core)===null||s===void 0?void 0:s.store.get("login"))===null||r===void 0?void 0:r.authKey)||""}isPrivateNetWork(){var s,r;return(r=(s=this._core)===null||s===void 0?void 0:s.store.get("instance"))===null||r===void 0?void 0:r.proxyServer}getPlatformFlags(){var s;const{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}=(s=this._core)===null||s===void 0?void 0:s.utils;return{IN_BROWSER:r,IN_MINI_APP:g,IN_RN_APP:u,IN_UNI_NATIVE_APP:E}}isEmpty(s){var r;const{isEmpty:g}=(r=this._core)===null||r===void 0?void 0:r.utils;return g(s)}generateURL(s,r){const{needAddAuthToUrl:g=!0}=r||{};return g?this.addAuthToUrl(s):s}_probeImageDimensionsMiniApp(s){var r;const{MINI_APP_NAMESPACE:g}=((r=this._core)===null||r===void 0?void 0:r.utils)||{};return new Promise(u=>{g.getImageInfo({src:s,success:E=>u({width:E.width,height:E.height}),fail:()=>u({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:r,IS_IE:g,IE_VERSION:u,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return r||g&&u===9||E}_probeImageDimensionsWeb(s){return new Promise(r=>{const g=new Image,u=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{r({width:g.width,height:g.height}),u()},g.onerror=()=>{r({width:0,height:0}),u()},g.src=s})}},qu={exports:{}},Ku=(nu||(nu=1,function(s){s.exports=function(r){var g=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];function u(LA,SA){var OA=LA[0],qA=LA[1],Ie=LA[2],le=LA[3];qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[0]-680876936|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[1]-389564586|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[2]+606105819|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[3]-1044525330|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[4]-176418897|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[5]+1200080426|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[6]-1473231341|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[7]-45705983|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[8]+1770035416|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[9]-1958414417|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[10]-42063|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[11]-1990404162|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&Ie|~qA&le)+SA[12]+1804603682|0)<<7|OA>>>25)+qA|0)&qA|~OA&Ie)+SA[13]-40341101|0)<<12|le>>>20)+OA|0)&OA|~le&qA)+SA[14]-1502002290|0)<<17|Ie>>>15)+le|0)&le|~Ie&OA)+SA[15]+1236535329|0)<<22|qA>>>10)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[1]-165796510|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[6]-1069501632|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[11]+643717713|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[0]-373897302|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[5]-701558691|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[10]+38016083|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[15]-660478335|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[4]-405537848|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[9]+568446438|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[14]-1019803690|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[3]-187363961|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[8]+1163531501|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA&le|Ie&~le)+SA[13]-1444681467|0)<<5|OA>>>27)+qA|0)&Ie|qA&~Ie)+SA[2]-51403784|0)<<9|le>>>23)+OA|0)&qA|OA&~qA)+SA[7]+1735328473|0)<<14|Ie>>>18)+le|0)&OA|le&~OA)+SA[12]-1926607734|0)<<20|qA>>>12)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[5]-378558|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[8]-2022574463|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[11]+1839030562|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[14]-35309556|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[1]-1530992060|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[4]+1272893353|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[7]-155497632|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[10]-1094730640|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[13]+681279174|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[0]-358537222|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[3]-722521979|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[6]+76029189|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((Ie=((Ie+=((le=((le+=((OA=((OA+=(qA^Ie^le)+SA[9]-640364487|0)<<4|OA>>>28)+qA|0)^qA^Ie)+SA[12]-421815835|0)<<11|le>>>21)+OA|0)^OA^qA)+SA[15]+530742520|0)<<16|Ie>>>16)+le|0)^le^OA)+SA[2]-995338651|0)<<23|qA>>>9)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[0]-198630844|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[7]+1126891415|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[14]-1416354905|0)<<15|Ie>>>17)+le|0)|~OA))+SA[5]-57434055|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[12]+1700485571|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[3]-1894986606|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[10]-1051523|0)<<15|Ie>>>17)+le|0)|~OA))+SA[1]-2054922799|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[8]+1873313359|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[15]-30611744|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[6]-1560198380|0)<<15|Ie>>>17)+le|0)|~OA))+SA[13]+1309151649|0)<<21|qA>>>11)+Ie|0,qA=((qA+=((le=((le+=(qA^((OA=((OA+=(Ie^(qA|~le))+SA[4]-145523070|0)<<6|OA>>>26)+qA|0)|~Ie))+SA[11]-1120210379|0)<<10|le>>>22)+OA|0)^((Ie=((Ie+=(OA^(le|~qA))+SA[2]+718787259|0)<<15|Ie>>>17)+le|0)|~OA))+SA[9]-343485551|0)<<21|qA>>>11)+Ie|0,LA[0]=OA+LA[0]|0,LA[1]=qA+LA[1]|0,LA[2]=Ie+LA[2]|0,LA[3]=le+LA[3]|0}function E(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA.charCodeAt(SA)+(LA.charCodeAt(SA+1)<<8)+(LA.charCodeAt(SA+2)<<16)+(LA.charCodeAt(SA+3)<<24);return OA}function m(LA){var SA,OA=[];for(SA=0;SA<64;SA+=4)OA[SA>>2]=LA[SA]+(LA[SA+1]<<8)+(LA[SA+2]<<16)+(LA[SA+3]<<24);return OA}function D(LA){var SA,OA,qA,Ie,le,bi,ki=LA.length,Ot=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=ki;SA+=64)u(Ot,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,qA=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],SA=0;SA>2]|=LA.charCodeAt(SA)<<(SA%4<<3);if(qA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ot,qA),SA=0;SA<16;SA+=1)qA[SA]=0;return Ie=(Ie=8*ki).toString(16).match(/(.*?)(.{0,8})$/),le=parseInt(Ie[2],16),bi=parseInt(Ie[1],16)||0,qA[14]=le,qA[15]=bi,u(Ot,qA),Ot}function M(LA){var SA,OA,qA,Ie,le,bi,ki=LA.length,Ot=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=ki;SA+=64)u(Ot,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(qA[SA>>2]|=128<<(SA%4<<3),SA>55)for(u(Ot,qA),SA=0;SA<16;SA+=1)qA[SA]=0;return Ie=(Ie=8*ki).toString(16).match(/(.*?)(.{0,8})$/),le=parseInt(Ie[2],16),bi=parseInt(Ie[1],16)||0,qA[14]=le,qA[15]=bi,u(Ot,qA),Ot}function T(LA){var SA,OA="";for(SA=0;SA<4;SA+=1)OA+=g[LA>>8*SA+4&15]+g[LA>>8*SA&15];return OA}function P(LA){var SA;for(SA=0;SA"u"||ArrayBuffer.prototype.slice||function(){function LA(SA,OA){return(SA=0|SA||0)<0?Math.max(SA+OA,0):Math.min(SA,OA)}ArrayBuffer.prototype.slice=function(SA,OA){var qA,Ie,le,bi,ki=this.byteLength,Ot=LA(SA,ki),Li=ki;return OA!==r&&(Li=LA(OA,ki)),Ot>Li?new ArrayBuffer(0):(qA=Li-Ot,Ie=new ArrayBuffer(qA),le=new Uint8Array(Ie),bi=new Uint8Array(this,Ot,qA),le.set(bi),Ie)}}(),xA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},xA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)u(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},xA.prototype.end=function(LA){var SA,OA,qA=this._buff,Ie=qA.length,le=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=qA.charCodeAt(SA)<<(SA%4<<3);return this._finish(le,Ie),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},xA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},xA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},xA.prototype._finish=function(LA,SA){var OA,qA,Ie,le=SA;if(LA[le>>2]|=128<<(le%4<<3),le>55)for(u(this._hash,LA),le=0;le<16;le+=1)LA[le]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),qA=parseInt(OA[2],16),Ie=parseInt(OA[1],16)||0,LA[14]=qA,LA[15]=Ie,u(this._hash,LA)},xA.hash=function(LA,SA){return xA.hashBinary(W(LA),SA)},xA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},xA.ArrayBuffer=function(){this.reset()},xA.ArrayBuffer.prototype.append=function(LA){var SA,OA=wA(this._buff.buffer,LA),qA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=qA;SA+=64)u(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=qA[SA]<<(SA%4<<3);return this._finish(le,Ie),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},xA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},xA.ArrayBuffer.prototype.getState=function(){var LA=xA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},xA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=oA(LA.buff,!0),xA.prototype.setState.call(this,LA)},xA.ArrayBuffer.prototype.destroy=xA.prototype.destroy,xA.ArrayBuffer.prototype._finish=xA.prototype._finish,xA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},xA}()}(qu)),qu.exports),SC=gI(Ku),K=new class{constructor(){this.uploadFileTryCount=0,this.maxRetries=1,this.systemClockOffset=0,this.httpRequest=null,this.uploadFileType="",this.duration=900,this.fetchCosTryCount=0}init(s){var r;this._core=s;const{IN_MINI_APP:g}=s.utils;this.httpRequest=g?DI:Ju,(r=this.httpRequest)===null||r===void 0||r.init(s)}uploadToCOS(s){return mA(this,void 0,void 0,function*(){const r=`${ha} uploadToCOS`,{ssoLog:g,utils:{safeStringify:u}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${r} options:${u(s)}`);try{const m=Date.now(),D=yield this._createCosOptions(s),M=D.fileExistsInCOS?{data:{location:D.downloadUrl}}:yield this._uploadFile(D);this._handleUploadError(M,s);const T=this._createUploadResult(E,M),P=Date.now()-m,W=function(EA){return EA<1024?`${EA}B`:EA<1048576?`${Math.floor(EA/1024)}KB`:`${Math.floor(EA/1048576)}MB`}(E.size),oA=`size:${W} time:${P}ms speed:${_r(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${r} ok. name:${E.name} ${oA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${r} failed, error:${u(m)}`),m}})}_handleUploadError(s,r){var g,u;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw r.url,!((u=s?.data)===null||u===void 0)&&u.uploadIP&&s.data.uploadIP,new E({message:"Upload failed with status 403"})}_createUploadResult(s,r){return{fileName:s.name,fileSize:s.size,fileType:s.type.slice(s.type.indexOf("/")+1).toLowerCase(),location:r.data.location||"",uploadTime:Ur(Date.now(),!1),uploadSpeed:_r(1e3*s.size/Ur(Date.now(),!1))}}_createCosOptions(s){return mA(this,void 0,void 0,function*(){const{fileName:r,resources:g,uploadMethod:u}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:r,uploadMethod:u,duration:this.duration,userID:s.message.from,conversationType:E}),{uploadUrl:D,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:oA,existFlag:EA}=m,wA=!xt.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:r,resources:g,downloadUrl:M,requestSnapshotUrl:T,thumbUrl:P,largeUrl:W,fileKey:oA,uploadIP:wA||"",fileExistsInCOS:EA===1,onProgress:kA=>this._handleUploadProgress(kA,s)}}catch(m){throw console.error("Failed to create COS pre-signed URL options:",m),m}})}_prepareUploadParams(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core;r.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=xt.getPlatformFlags(),M=m||D,T=M&&s.message.type!==Ya,{name:P}=E,W=P.slice(P.lastIndexOf(".")),oA=`${Lr(999999)}${W}`,EA=T?E.name:oA,wA=yield this._generateHashFileName(E);return{fileName:u(wA)?Ig(EA):`${wA}${W}`,resources:M?E.url:E,uploadMethod:M?1:0}})}_generateHashFileName(s){return mA(this,void 0,void 0,function*(){const{utils:{IN_MINI_APP:r,IN_BROWSER:g,IN_UNI_NATIVE_APP:u,isArray:E},ssoLog:m}=this._core,D=Date.now();let M="";return g&&(M=yield this._generateHashFileNameInWeb(s)),r&&(E(s.tempFiles)&&(s=s.tempFiles[0]),u||(M=yield this._generateFileNameInMiniProgram(s)),u&&(M=yield this._generateFileNameInUNINativeApp(s))),m.info("_generateHashFileName",`hashFileName:${M} costTime:${Date.now()-D}`),M})}_generateHashFileNameInWeb(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;let u="";try{u=yield new Promise((E,m)=>{const D=File.prototype.slice||File.prototype.mozSlice||File.prototype.webkitSlice;D||(r.warn("_generateHashFileNameInWeb","Browser does not support file slicing"),E(""));const M=10485760,T=Math.ceil(s.size/M);let P=0;const W=new SC.ArrayBuffer,oA=new FileReader,EA=setTimeout(()=>{oA.abort(),r.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*M,xA=kA+M>=s.size?s.size:kA+M;oA.readAsArrayBuffer(D.call(s,kA,xA))}oA.onload=kA=>{r.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},wA()})}catch(E){r.warn("_generateHashFileNameInWeb",g(E))}return u})}_generateFileNameInMiniProgram(s){return mA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:r,safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInMiniProgram","file.url is empty"),m;if(typeof r?.getFileSystemManager!="function")return E.warn("_generateFileNameInUNINativeApp","getFileSystemManager is not a function"),m;try{m=yield new Promise((D,M)=>{r.getFileSystemManager().getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_generateFileNameInUNINativeApp(s){return mA(this,void 0,void 0,function*(){var r;const{utils:{safeStringify:g,isEmpty:u},ssoLog:E}=this._core;let m="";if(u(s.url))return E.warn("_generateFileNameInUNINativeApp","file.url is empty"),m;if(typeof((r=plus==null?void 0:plus.io)===null||r===void 0?void 0:r.getFileInfo)!="function")return E.warn("_generateFileNameInUNINativeApp","plus.io.getFileInfo is not a function"),m;try{m=yield new Promise((D,M)=>{plus.io.getFileInfo({filePath:s.url,success:T=>{D(T.digest)},fail:T=>{M(T)}})})}catch(D){E.warn("_generateFileNameInMiniProgram",g(D))}return m})}_handleUploadProgress(s,r){if(typeof r.onProgress=="function")try{r.onProgress(s.percent)}catch(g){throw console.warn("Upload progress callback error:",g),g}}_fetchCosSignatureUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core,u=xt.isSimpleCos(),E=this._prepareCosRequestData(s),m=u?"im_cos_msg.simple_sig":"im_cos_msg.pre_sig";try{const D=yield function(T,P,W){return mA(this,void 0,void 0,function*(){try{const{helper:oA,channel:EA}=W,wA=oA.generateCosSpecifiedData({servcmd:T,data:P}),kA=`${wA.head.seq}${T}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(oA){throw console.warn("getCosSig error:",oA),oA}})}(m,E,this._core);this.fetchCosTryCount=0;const M=this._processResponse(D);return r.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${u} data:${g(M)}`),M||{}}catch(D){if(this.fetchCosTryCount<1)return this.fetchCosTryCount++,this._fetchCosSignatureUrl(s);throw this.fetchCosTryCount=0,D}})}_processResponse(s){var r;const g=xt.isSimpleCos(),u=g?(r=s?.rpt_pre_sig)===null||r===void 0?void 0:r[0]:s;if(!u)return{};if(g){const{str_final_ip:W,rpt_pre_sig:oA,uint32_file_id:EA,uint32_exist_flag:wA,str_download_url:kA,str_upload_url:xA,str_snapshot_url:LA,str_file_key:SA}=u;return{uploadIP:W,preSig:oA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:xA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=u;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return xt.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:xt.getPlatform(),uint32_sdkappid:xt.getSDKAppID(),str_user_id:s.userID,uint32_scene:s.conversationType,rpt_upload_object:[{uint32_file_id:1,uint32_file_type:s.fileType,str_file_name:s.fileName}]}:{file_type:s.fileType,file_name:s.fileName,upload_method:s.uploadMethod,Duration:s.duration}}_uploadFile(s){return mA(this,void 0,void 0,function*(){return new Promise((r,g)=>{this.httpRequest.request(s,(u,E)=>{u&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var r,g,u;const E=((r=s.headers)===null||r===void 0?void 0:r.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((u=s.error)===null||u===void 0?void 0:u.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const r=xt.getFileUploadProxy();let g=s;return r&&(g=s.replace(/^https:\/\/[^/]+/,r)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const U=2108,sA=2251,b=2252,x=2253,iA=["jpg","jpeg","gif","png","bmp","image","webp"],uA={JPG:1,JPEG:1,GIF:2,PNG:3,BMP:4,UNKNOWN:255},_A=1,ee=2;class fe{constructor(r,g){this.instanceID=Lr(9999999),this.sizeType=r.type||0,this.type=0,this.size=r.size||0,this.width=r.width||0,this.height=r.height||0,this.imageUrl=xt.addAuthToUrl(r.imageUrl||r.url||""),this.url=xt.addAuthToUrl(r.url||g)}setSizeType(r){this.sizeType=r}setType(r){this.type=r}setImageUrl(r){r&&(this.imageUrl=xt.addAuthToUrl(r))}getImageUrl(){return this.imageUrl}}function p(s){const{originUrl:r,originWidth:g,originHeight:u,min:E=198}=s,m=parseInt(g)||0,D=parseInt(u)||0,M={url:void 0,width:0,height:0};if((m<=D?m:D)<=E)M.url=r,M.width=m,M.height=D;else{D<=m?(M.width=Math.ceil(m*E/D),M.height=E):(M.width=E,M.height=Math.ceil(D*E/m));const T=r&&r.indexOf("?")>-1?`${r}&`:`${r}?`;M.url=E===198?`${T}imageView2/3/w/198/h/198`:`${T}imageView2/3/w/720/h/720`}if(r===void 0){const{url:T}=M;return So(M,["url"])}return M}class B{constructor(r){this._imageMemoryURL="",this._percent=0,this.type=ic;const{uuid:g,file:u,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=r;this._imageMemoryURL=this.createImageDataAsURL(u),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[Jr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(r){const{MsgContent:g}=r,{ImageFormat:u,ImageInfoArray:E,UUID:m}=g,D=function(M){return M.map(T=>({size:T.Size,type:T.Type,width:T.Width,height:T.Height,url:T.URL}))}(E);return new B({imageFormat:u,imageInfoArray:D,uuid:m})}createImageDataAsURL(r){let g="";const{IN_MINI_APP:u,IN_RN_APP:E,IN_BROWSER:m}=xt.getPlatformFlags();return r&&((u||E)&&(g=r.url),m&&(g=window.URL.createObjectURL(r))),g}initImageInfoArray(r=[]){const g={type:0,size:0,width:0,height:0,url:""};for(let u=0;u<3;u++){const E=r[u]||Object.assign({},g),m=new fe(E,this._imageMemoryURL);m.setSizeType(u+1),m.setType(u),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const r=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[u,...E]=g.imageUrl.split("://"),m=E.join("://");r.includes(u)||g.setImageUrl(`https://${m}`)})}updatePercent(r){this._percent=Math.min(r,1)}updateImageFormat(r){this.content.imageFormat=uA[r.toUpperCase()]||uA.UNKNOWN}addImageInfo(r){this.content.imageInfoArray.length>=3||this.content.imageInfoArray.push(r)}updateImageInfoArray(r){const g=this.content.imageInfoArray.length;let u;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:xt.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},G={[ou]:"i",[cl]:"a",[Ba]:"v",[PE]:"f"};let O=null,z=null;function X(s){var r;const{store:g,utils:{isNumber:u,safeStringify:E},ssoLog:m}=v.core;try{const D=((r=g.get("cloudConfig"))===null||r===void 0?void 0:r.upload_size_limit)||"";D!==z&&(z=D,O=JSON.parse(D)||{});const M=O?.[G[s]];if(u(M))return 1024*M*1024}catch(D){m.debug("getCloudControlUploadSizeLimit",E(D))}return null}var rA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createImageMessage",context:this}),u.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(ic,B),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var r,g,u;try{const E=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,m=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:xt.generateUUID(D),file:D,imageInfoArray:[]},T=new B(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var r,g,u,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(r=m.get("login"))===null||r===void 0?void 0:r.userId,T=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:oA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:xA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:qA,thumbFileSize:Ie,thumbImageWidth:le,thumbImageHeight:bi,thumbImageUrl:ki}=((E=s?.payload)===null||E===void 0?void 0:E.file)||{};if(D(OA)||D(kA))throw new Error("createImageMessageExperimental originImageUrl or originImageUuid is empty");const Ot=new B({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:xA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:oA,height:EA,imageUrl:wA,url:wA},{instanceID:qA,size:Ie,width:le,height:bi,imageUrl:ki,url:ki}],isCustomUpload:!0});return T.setElement(Ot),this._messageOptionsMap.set(T.clientSequence,s),T._skipUpload=!0,T}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadImage(g);const u=yield this._performImageUpload(r,s,g),E=this._generateImageInfo(u);return r.updateImageFormat(u?.fileType),r.updateImageInfoArray(E),this._updateImageType(r.content.imageInfoArray),s})}_performImageUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:ou,file:g,to:u,message:r,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(r.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{uploadOptions:m,response:D}=yield K.uploadToCOS(E);return this._parseResponse(m,D)})}_generateImageInfo(s){const{location:r,fileSize:g,width:u,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:oA}=s,EA=xt.addAuthToUrl(r),wA={size:g,url:EA,width:u,height:E};return oA?.length>0?this._processImageInfoArray(oA,g):m&&T?[Object.assign({},wA),{largeImageUrl:T,largeImageWidth:P,largeImageHeight:W},{smallImageUrl:m,smallImageWidth:D,smallImageHeight:M}]:[Object.assign({},wA),this._generateThumbInfo(EA,u,E,720),this._generateThumbInfo(EA,u,E,198)]}_generateThumbInfo(s,r,g,u){return p({originUrl:s,originWidth:r,originHeight:g,min:u})}_processImageInfoArray(s,r){let g,u,E;for(const m of s)m.type===1?(u=m,u.size=r):m.type===2?(E=m,E.size=r):(g=m,g.size=r);return[Object.assign({},g),Object.assign({},E),Object.assign({},u)]}_parseResponse(s,r){return mA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:u,downloadUrl:E}=s;if(g&&u&&(yield this._getImageInfoByUrl(g,r,"thumb"),yield this._getImageInfoByUrl(u,r,"large")),xt.isSimpleCos()&&!xt.isPrivateNetWork()&&(yield this._getImageInfoArray(E,r),r?.uploadIP)){const m=this._extractDomainFromUrl(E);m&&(yield this._getDownloadIP(m,r))}return r}catch(g){throw g}})}_extractDomainFromUrl(s){var r;try{const g=s.match(/:\/\/([^\/]+)/);return g?g[1]:null}catch(g){return(r=this._core)===null||r===void 0||r.ssoLog.warn("_extractDomainFromUrl",`Failed to extract domain from URL:${g.message}`),null}}_getImageInfoByUrl(s,r,g){return mA(this,void 0,void 0,function*(){var u;try{const E=xt.addAuthToUrl(s),{width:m=0,height:D=0}=yield xt.probeImageWidthHeight(E);r.width=m,r.height=D,g==="thumb"?(r.smallImageUrl=s,r.smallImageWidth=m,r.smallImageHeight=D):(r.largeImageUrl=s,r.largeImageWidth=m,r.largeImageHeight=D)}catch(E){(u=this._core)===null||u===void 0||u.ssoLog.warn("_getImageInfoByUrl",`Failed to get ${g} image info:${E.message}`)}})}_validateBeforeUploadImage(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper;if(!s)throw new g({code:sA});this._checkImageType(s),this._checkImageSize(s)}_processImage(s){var r;try{const{IN_MINI_APP:g}=(r=this._core)===null||r===void 0?void 0:r.utils;let{file:u}=s.payload;return u=g?this._processMiniAppImageFile(u):this._processWebImageFile(u),u}catch(g){throw g}}_processMiniAppImageFile(s){gl(s)&&console.warn("FileUnsupportedInMiniApp","createImageMessage");const r=s.tempFiles[0].path||s.tempFiles[0].tempFilePath;return{url:r,name:r.slice(r.lastIndexOf("/")+1),size:s.tempFiles&&s.tempFiles[0].size||1,type:r.slice(r.lastIndexOf(".")+1).toLowerCase()}}_processWebImageFile(s){var r;const{ChatError:g}=(r=this._core)===null||r===void 0?void 0:r.helper,u=xt.extractFileFromInput(s);if(!u)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return u}_getDownloadIP(s,r){return mA(this,void 0,void 0,function*(){const g=`${ha} getDownloadIP domainName: ${s}`;try{const u=yield function(m,D){return mA(this,void 0,void 0,function*(){try{const{helper:M,channel:T}=D,P="im_cos_msg.get_final_ip",W={str_domain:m},oA=M.generateProtocolData({servcmd:P,data:W}),EA=`${oA.head.seq}${P}`;return yield T.sendPacket(oA,{requestId:EA})}catch(M){throw console.warn("getFinalIP error:",M),M}})}(s,this._core);if(!u||!u.str_final_ip)return;console.log(`${g} ok. downloadIP:${u}`);const E=r.location.split("/");E[0]=u.str_final_ip,r.location=E.join("/")}catch(u){console.warn(u)}})}_getImageInfoArray(s,r){return mA(this,void 0,void 0,function*(){try{const g=yield function(u,E){return mA(this,void 0,void 0,function*(){try{const{helper:m,channel:D}=E,M="im_cos_msg.get_imageinfo",T={str_image_url:u},P=m.generateProtocolData({servcmd:M,data:T}),W=`${P.head.seq}${M}`;return yield D.sendPacket(P,{requestId:W})}catch(m){throw console.warn("getImageInfo error:",m),m}})}(s,this._core);return r.imageInfoArray=this._processImageInfoResponse(g),r}catch(g){throw r.imageInfoArray=void 0,g}})}_processImageInfoResponse(s){if(!s)return[];const{rpt_msg_image_info:r}=s;return r.map(g=>({type:g.uint32_image_type,url:g.str_url,width:g.uint32_width,height:g.uint32_height,imageFormat:g.str_image_format}))}_checkImageType(s){const{utils:r,helper:g}=this._core;let u="";if(r.IN_MINI_APP&&(u=s.url.slice(s.url.lastIndexOf(".")+1)),r.IN_BROWSER&&(u=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(u.toLowerCase())<0)throw new g.ChatError({code:b})}_checkImageSize(s){const{utils:r,helper:g,store:u}=this._core;let E=0;if(E=(r.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:U});if(E>=(X(ou)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=ee,s[2].type=_A}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const DA=2108,GA=2401,JA=2402,ne="2.5.0",he="1.18.0";function Ze(s,r){const g=s.split("."),u=r.split("."),E=Math.max(g.length,u.length);for(;g.lengthM)return 1;if(D0;return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=u;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:xt.removeAuthToUrl(D),FileName:M,FileSize:T,UUID:E}}}_getFileInfo(r){const{utils:{IN_UNI_NATIVE_APP:g}}=v.core;if(r.fileName&&r.fileSize)return{size:r.fileSize,name:r.fileName};const{file:u}=r;return u?(g&&this._processNativeAppFile(u),{size:u.size,name:u.name}):{size:0,name:""}}_processNativeAppFile(r){if(r.path&&r.path.includes(".")){const g=r.path.slice(r.path.lastIndexOf(".")+1).toLowerCase();r.type=g,r.name||(r.name=`${Lr(999999)}.${g}`)}r.name||(r.type="",r.name=r.path.slice(r.path.lastIndexOf("/")+1).toLowerCase()),r.suffix&&(r.type=r.suffix),r.url||(r.url=r.path)}}st=Jr;var Ft=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createFileMessage",context:this}),u.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Ya,at),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var r,g,u;try{this._checkVersion();const E=this._processFile(s.payload.file);s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:xt.generateUUID(E),file:E},T=new at(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var r,g,u;try{const{store:E,message:m,utils:{isEmpty:D}}=this._core,M=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:T,uuid:P,fileSize:W,fileName:oA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:M})),wA=new at({url:T,uuid:P,file:{size:W,name:oA},isCustomUpload:!0});return EA.setElement(wA),EA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{file:r}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadFile(r);const g=s.getElements()[0],u=yield this._performFileUpload(g,s,r),E=xt.addAuthToUrl(u?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:r}}=this._core;if(!s)throw new r({code:GA});const g=X(PE)||104857600;if(s.size>g)throw new r({code:JA});if(s.size===0)throw new r({code:DA})}_performFileUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:PE,file:g,to:u,message:r,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(r.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield K.uploadToCOS(E);return m})}_processFile(s){var r,g;const{IN_BROWSER:u,IN_RN_APP:E,IN_WX_MINI_APP:m,IN_QQ_MINI_APP:D,IN_UNI_NATIVE_APP:M}=(r=this._core)===null||r===void 0?void 0:r.utils,{ChatError:T}=(g=this._core)===null||g===void 0?void 0:g.helper;if(u||M){const P=xt.extractFileFromInput(s);if(!P)throw new T({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return P}if(m||D){const{tempFiles:P}=s;return Object.assign(Object.assign({},P[0]),{url:P[0].path})}return E?Object.assign(Object.assign({},s),{url:s.uri}):s}_checkVersion(){var s,r;const{MINI_APP_NAMESPACE:g,IN_MINI_APP:u,IN_WX_MINI_APP:E,IN_QQ_MINI_APP:m,IN_UNI_NATIVE_APP:D}=(s=this._core)===null||s===void 0?void 0:s.utils,{ChatError:M}=(r=this._core)===null||r===void 0?void 0:r.helper;if(u){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&Ze(T,ne)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ne} or higher`});if(m&&Ze(T,he)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${he} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ht=2108,Pi=2351,co=2352,Xi=["mp4","quicktime","mov","video"];var di;class xo{constructor(r){this.type=Ol,this.uploadProgress=0,this[di]=!1;const g=typeof r?.videoSecond=="number"?r?.videoSecond:0;this[Jr]=r.isCustomUpload||!1,this.content={remoteVideoUrl:xt.addAuthToUrl(r.remoteVideoUrl||r.videoUrl||""),videoFormat:r.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:r.videoSize,videoUrl:xt.addAuthToUrl(r.videoUrl),videoDownloadFlag:2,videoUUID:r.videoUUID,thumbUUID:r.thumbUUID,thumbFormat:r.thumbFormat,thumbWidth:r.thumbWidth,snapshotWidth:r.thumbWidth,thumbHeight:r.thumbHeight,snapshotHeight:r.thumbHeight,thumbSize:r.thumbSize,snapshotSize:r.thumbSize,thumbDownloadFlag:2,thumbUrl:xt.addAuthToUrl(r.thumbUrl),snapshotUrl:xt.addAuthToUrl(r.thumbUrl)}}static parseServerPushElement(r){const{MsgContent:g}=r,{VideoUrl:u,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:oA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:xA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:qA}=g;return new xo({videoUrl:u,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:oA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:xA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:qA})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateVideoUrl(r){r&&(this.content.remoteVideoUrl=r)}updateSnapshotInfo(r){const{snapshotUrl:g,snapshotWidth:u,snapshotHeight:E}=r;xt.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),xt.isEmpty(u)||(this.content.thumbWidth=this.content.snapshotWidth=Number(u)),xt.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[Jr])return{isValid:!0};const r=this.content.remoteVideoUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{remoteVideoUrl:E,videoFormat:m,videoSecond:D,videoSize:M,videoDownloadFlag:T,videoUUID:P,thumbUUID:W,thumbFormat:oA,thumbWidth:EA,snapshotWidth:wA,thumbHeight:kA,snapshotHeight:xA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:qA,snapshotUrl:Ie}=u;return{MsgType:this.type,MsgContent:{VideoUrl:xt.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:oA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:xA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:xt.removeAuthToUrl(qA),SnapshotUrl:xt.removeAuthToUrl(Ie)}}}}di=Jr;var ts,mi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createVideoMessage",context:this}),u.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Ol,xo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var r,g,u;try{const E=this._processVideo(s);s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:lr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:xt.generateUUID(E.videoFile),thumbUUID:xt.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new xo(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var r,g,u;try{const{store:E,message:m}=this._core;this._validateCustomUploadVideoMessage(s);const D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{videoUrl:M,videoUuid:T,duration:P,snapshotUrl:W,snapshotUuid:oA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:xA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),qA=new xo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:oA,thumbWidth:kA||200,thumbHeight:xA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(qA),this._messageOptionsMap.set(OA.clientSequence,s),OA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const r=s.getElements()[0],{file:g}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadVideo(g);const u=yield this._performVideoUpload(r,s,g),{location:E,snapshotInfo:m}=u,D=xt.addAuthToUrl(E);return r.updateVideoUrl(D),xt.isEmpty(m)||r.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:r}}=this._core,g=X(Ba)||104857600;if(s.videoFile.size>g)throw new r({code:Pi});if(s.videoFile.size===0)throw new r({code:Ht});if(Xi.indexOf(s.videoFile.type)===-1)throw new r({code:co})}_validateCustomUploadVideoMessage(s){var r;const{utils:{isEmpty:g,isNumber:u}}=this._core,{videoUrl:E,videoUuid:m,duration:D,snapshotUrl:M,snapshotUuid:T}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(E)||g(m)||!u(D)||g(M)||g(T))throw new Error("Invalid video message options: missing required fields (videoUrl, videoUuid, duration, snapshotUrl, snapshotUuid)")}_performVideoUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:Ba,file:g,to:u,message:r,onProgress:M=>{var T,P;s.updatePercent(M),(P=(T=this._messageOptionsMap.get(r.clientSequence))===null||T===void 0?void 0:T.onProgress)===null||P===void 0||P.call(T,M)}},{response:m,uploadOptions:D}=yield K.uploadToCOS(E);return{snapshotInfo:yield this._getSnapshotInfoByUrl(D.requestSnapshotUrl),location:m.location}})}_processVideo(s){var r,g;try{const{ChatError:u}=(r=this._core)===null||r===void 0?void 0:r.helper,{IN_MINI_APP:E,IN_BROWSER:m}=(g=this._core)===null||g===void 0?void 0:g.utils;let{file:D}=s.payload,M={};if(E&&(M=this._processMiniVideoFile(D),D.name=M.name,D.url=M.url,D.type=M.type),m){const T=xt.extractFileFromInput(D);if(!T)throw new u({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});D=T,M=this._processWebVideoFile(D)}return D.videoFile=M,D.thumbUrl="",D.thumbSize=0,D}catch(u){throw console.warn(`${ha} _processFile error:`,u),u}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:r},helper:{ChatError:g}}=this._core;if(gl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let u=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return r&&(u=s.fileType||u),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:u}}_processWebVideoFile(s){const{name:r,size:g=1,duration:u=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:r,size:g,second:u,type:m}}_getSnapshotInfoByUrl(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core;try{r.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:xt.getPlatform(),cover_name:Ig(Lr(99999)),snapshot_url:s},u=yield function(T,P){return mA(this,void 0,void 0,function*(){try{const W="im_cos_msg.video_cover",{helper:oA,channel:EA}=P,wA=oA.generateCosSpecifiedData({servcmd:W,data:T}),kA=`${wA.head.seq}${W}`;return yield EA.sendPacket(wA,{requestId:kA})}catch(W){throw console.warn("getSnapshotInfo error:",W),W}})}(g,this._core),{download_url:E}=u||{};if(r.debug("_getSnapshotInfoByUrl",`${ha} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),xt.isEmpty(E))return{};const m=xt.addAuthToUrl(E),{width:D=0,height:M=0}=yield xt.probeImageWidthHeight(m);return{snapshotUrl:m,snapshotWidth:D,snapshotHeight:M}}catch(g){throw g}})}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};class zi{constructor(r){this.uploadProgress=0,this.type=Fg,this[ts]=!1,this[Jr]=r.isCustomUpload||!1,this.content={downloadFlag:2,second:r.second,size:r.size,url:xt.generateURL(r.url,{needAddAuthToUrl:!this[Jr]}),remoteAudioUrl:xt.addAuthToUrl(r.url||""),uuid:r.uuid}}static parseServerPushElement(r){const{MsgContent:g}=r,{Url:u,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new zi({url:u,downloadFlag:E,second:m,size:D,uuid:M})}updatePercent(r){this.uploadProgress=Math.min(r,1)}updateAudioUrl(r){this.content.remoteAudioUrl=r}validateBeforeSend(){if(this[Jr])return{isValid:!0};const r=this.content.remoteAudioUrl!=="";return{isValid:r,error:r?null:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=u;return{MsgType:this.type,MsgContent:{Url:xt.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}ts=Jr;const Ws=2108,Ne=2300,Tt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var r;this._core=s;const{notificationCenter:g,helper:u,InnerEvent:E,message:m}=s;u.registerApi({apiName:"createAudioMessage",context:this}),u.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(r=m?.messageFactory)===null||r===void 0||r.registerElementClass(Fg,zi),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var r,g,u;try{let{file:E}=s.payload;E=this._processAudioFile(s.payload.file),s.payload.file=E;const m=(r=this._core.store.get("login"))===null||r===void 0?void 0:r.userId,D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:m})),M={second:Math.max(1,Math.round((E.duration||E.second)/1e3)),size:E.fileSize||E.size||1,url:E.tempFilePath||E.uri||E.url,uuid:xt.generateUUID(E)},T=new zi(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var r,g,u;try{this._validateCustomUploadOptions(s);const{store:E,message:m}=this._core,D=(r=E.get("login"))===null||r===void 0?void 0:r.userId,{url:M,uuid:T,duration:P,fileSize:W}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},oA=(u=m.messageFactory)===null||u===void 0?void 0:u.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new zi({second:P,size:W||1,url:M,uuid:T,isCustomUpload:!0});return oA.setElement(EA),this._messageOptionsMap.set(oA.clientSequence,s),oA}catch(E){throw E}}upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;r.debug("upload",`${ha} uploadAudio message:${g(s)}`);const{file:u}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(u);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,u),D=xt.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:r},store:g}=this._core;if(!s)throw new r({code:Ne});const u=X(cl)||20971520;if(s.size>u)throw new r({code:Tt});if(s.size===0)throw new r({code:Ws})}_performAudioUpload(s,r,g){return mA(this,void 0,void 0,function*(){const{to:u}=r,E={uploadFileType:cl,file:g,to:u,message:r,onProgress:D=>{var M,T;s.updatePercent(D),(T=(M=this._messageOptionsMap.get(r.clientSequence))===null||M===void 0?void 0:M.onProgress)===null||T===void 0||T.call(M,D)}},{response:m}=yield K.uploadToCOS(E);return m})}_processAudioFile(s){var r;const{IN_MINI_APP:g,IN_BROWSER:u}=(r=this._core)===null||r===void 0?void 0:r.utils;return g?this._processMiniFile(s):u?this._processWebFile(s):void 0}_processMiniFile(s){return{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.fileSize,second:s.duration,type:s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase()}}_processWebFile(s){if(s.tempFilePath||s.uri)return s;const r=URL.createObjectURL(s);return s.tempFilePath=r,s}_validateCustomUploadOptions(s){var r;const{utils:{isEmpty:g}}=this._core,{url:u,uuid:E,duration:m}=((r=s?.payload)===null||r===void 0?void 0:r.file)||{};if(g(u)||g(E)||g(m))throw new Error("Invalid audio message options")}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ai={to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1},onProgress:{required:!1,rules:["function"],allowEmpty:!1}},En={createImageMessage:Ai,createAudioMessage:Ai,createVideoMessage:Ai,createFileMessage:Ai},ii={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},us={[ic]:rA,[Ya]:Ft,[Ol]:mi,[Fg]:FA};var wi=new class{constructor(){this.name="RichMediaMessage"}install(s){this._core=s;const{constants:{OuterConstant:{MSG_AUDIO:r,MSG_FILE:g,MSG_IMAGE:u,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Ft.init(s),mi.init(s),FA.init(s),K.init(s),xt.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[r,g,u,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:ii,params:En})}sendMessage(s,r){return mA(this,void 0,void 0,function*(){var g,u,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageSender)===null||E===void 0?void 0:E.sendMessage(s,r)}catch(m){throw m}})}_upload(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=this._core;if(r.debug("_upload",` uploadFile message:${g(s)}`),s._relayFlag!==!0)try{const u=us[s.type];u&&(yield u.upload(s),r.info("_upload",` type:${s.type}`))}catch(u){throw s.status=su.FAIL,u instanceof Error&&(u.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),u}})}_isCustomUpload(s){var r,g;return((g=(r=s._elements)===null||r===void 0?void 0:r[0])===null||g===void 0?void 0:g[Jr])===!0}};const Bo=new class{init(s){this.core=s}};class Bt{constructor(r){this.conversationID=r.conversationID||"",this.unreadCount=r.unreadCount||0,this.type=r.type||"",this.lastMessage=Bo.core.common.buildLastMessage(r.lastMessage),this.peerReadTime=r.peerReadTime||0,this.groupAtInfoList=[],this.remark=r.remark||"",this.isPinned=r.isPinned||!1,this.messageRemindType=r.messageRemindType,this.markList=r.markList||[],this.customData=r.customData||"",this.conversationGroupList=r.conversationGroupList||[],this.draftText=r.draftText||"",this.userProfile=r.userProfile,this.groupProfile=r.groupProfile,this.subType=r.subType||"",this._isInfoCompleted=!1,this._init()}_init(){var r;const{core:{OuterConstant:g,utils:{isUndefined:u}}}=Bo;u(this.userProfile)&&this.type===g.CONV_C2C?this.userProfile={userID:this.conversationID.replace(g.CONV_C2C,"")}:this.type===g.CONV_GROUP&&(!this.subType&&(!((r=this.groupProfile)===null||r===void 0)&&r.type)&&(this.subType=this.groupProfile.type),u(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(r){var g;const{core:{OuterConstant:u,utils:{isUndefined:E},store:m}}=Bo,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=r;if(E(D))return;if(this.subType===u.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===u.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===u.CONV_C2C)return void(this.unreadCount=D);const P=((g=m.get("cloudConfig"))===null||g===void 0?void 0:g.support_unread_count_for_meeting)==="1";this.subType!==u.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(r){this.lastMessage=Bo.core.common.buildLastMessage(r)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(r){const{core:{OuterConstant:g}}=Bo,{sequence:u,time:E}=r;return this.type===g.CONV_C2C&&u===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&u===this.lastMessage.lastSequence}setLastMessageRevoked(r){this.lastMessage.isRevoked=r}setLastMessageRevoker(r){this.lastMessage.revoker=r}setDraftText(r){this.draftText=r}updateGroupAtInfoList(r){const{core:{common:{updateGroupAtInfo:g}}}=Bo;g(r,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const mt=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s.slice(0,3)===r.CONV_C2C},ug=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s.slice(0,5)===r.CONV_GROUP},Ls=s=>{const{core:{OuterConstant:r,utils:{isString:g}}}=Bo;return g(s)&&s===r.CONV_SYSTEM};function Zi(s){const{OuterConstant:r}=Bo.core;let g="";return s===0?g=r.MSG_REMIND_ACPT_AND_NOTE:s===1?g=r.MSG_REMIND_DISCARD:s===2?g=r.MSG_REMIND_ACPT_NOT_NOTE:s===3&&(g=r.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}function Hr(s){const{OuterConstant:r}=Bo.core;let g;return s.startsWith(r.CONV_C2C)&&(g=s.replace(r.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function oc(s,r){const{helper:g}=Bo.core,u=new g.ChatError({functionName:s,code:r?.errorCode||r?.code,message:r?.errorInfo||r?.message});throw console.error(`${s} fail:`,u),u}var os,ca;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(os||(os={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(ca||(ca={}));var Qa;(function(s){s[s.CONV_NOT_FOUND=2500]="CONV_NOT_FOUND",s[s.USER_OR_GRP_NOT_FOUND=2501]="USER_OR_GRP_NOT_FOUND",s[s.CONV_UN_RECORDED_TYPE=2502]="CONV_UN_RECORDED_TYPE"})(Qa||(Qa={}));const ta=0,H=1;var QA=new class{constructor(){this._name="GetC2CMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){try{const{common:r}=this._core,g=yield function(E,m){return mA(this,void 0,void 0,function*(){const{toAccount:D,userIDList:M}=E,T={To_Account:D,Peer_Account:M};return m.common.buildAndSendPacket({servcmd:"openim.get_c2c_peer_mute_notifications",data:T})})}({toAccount:r.getCurrentUserID(),userIDList:s},this._core),{MuteNotificationsList:u=[]}=g||{};u.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=Zi(D);NA.patchMessageRemindType([M],T)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},yA=new class{constructor(){this._name="GetGroupMessageRemindType"}init(s){this._core=s}get(s){return mA(this,void 0,void 0,function*(){if(s.length!==0)try{const r=yield function(u,E){return mA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=u,M={GroupIdList:m,ResponseFilter:D};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:M})})}({groupIDList:s,responseFilter:{MemberInfoFilter:["MsgFlag"]}},this._core),{GroupInfo:g=[]}=r||{};g.forEach(u=>{var E;const{GroupId:m,MemberList:D}=u,M=((E=D[0])===null||E===void 0?void 0:E.MsgFlag)||"",T=`${this._core.OuterConstant.CONV_GROUP}${m}`;NA.patchMessageRemindType([T],M)})}catch(r){console.error(`${this._name}.get fail:`,r)}})}},NA=new class{constructor(){this._name="ConversationDataHandler",this._totalUnreadCount=0,this._groupAtTipsList=[]}init(s){this._core=s;const{helper:r,notificationCenter:g,appStore:{conversationStore:u},constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},InnerEvent:{SYNC_CONVERSATION_LIST:D,MESSAGE_PUSH:M,NEW_MESSAGE:T,MESSAGE_DELETED:P,MESSAGE_REVOKED:W,MESSAGE_MODIFIED:oA,CONVERSATION_UPDATED:EA,LOGOUT:wA,DESTROY:kA},InnerEventSubType:{C2C_MESSAGE_PEER_READ:xA}}=s;this._conversationStore=u,r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_LOGIN,m.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,this._handleGroupListSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.RECEIVE_C2C_NEW_MESSAGE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_NEW_MESSAGE,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this),r.registerWorkflowStep(E.SYNC_SERVER_INFO_AFTER_RE_ONLINE,m.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,this._handleUnreadSyncFinished,this),r.registerWorkflowStep(E.RECEIVE_GROUP_TIPS_NOTIFICATION,m.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,this._handleNewMessage,this);const{InnerEventSubType:{GROUP_AT_TIPS:LA}}=g;g.subscribeInnerEvent(D,this._handleConversationSynced,this),g.subscribeInnerEvent(T,this._handleNewMessage,this),g.subscribeInnerEvent(M,LA,this._handleNewGroupAtTips,this),g.subscribeInnerEvent(P,this._handleMessageDeleted,this),g.subscribeInnerEvent(W,this._handleMessageRevoked,this),g.subscribeInnerEvent(oA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,xA,this._handleMessageRead,this),g.subscribeInnerEvent(wA,this._reset,this),g.subscribeInnerEvent(kA,this._dispose,this),s.ssoLog.debug(`${this._name}.init`)}_handleConversationSynced(s){this.updateLocalConversationList({conversationUpdateFieldList:s.conversationUpdateFieldList||[],isFromGetConversations:!0,updateUnreadCount:!0}),this.emitConversationListUpdate()}_handleUnreadSyncFinished(s){const{constants:{WORKFLOW_STEP:r}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:u=[],isUnreadC2CMessage:E}=s.result[r.UNREAD_MESSAGE_SYNC]||{};let m=!1;g.forEach(D=>{const{conversationID:M,unreadCount:T}=D,P=this.getLocalConversation(M);P&&P.unreadCount!==T&&(P.updateUnreadCount({nextUnreadCount:T,isUnreadC2CMessage:E}),m=!0)}),m&&this.emitConversationListUpdate(),this._handleGroupAtTipsSynced(u)}_handleGroupAtTipsSynced(s){var r;for(let g=0;g0&&this._handleNewGroupAtTips({GroupTips:M._groupAtInfoList}),m=!0}m&&this.emitConversationListUpdate()}_handleNewMessage(s){const{conversationUpdateFieldList:r=[],isInstantMessage:g=!0,isUnreadC2CMessage:u=!1,updateUnreadCount:E=!0}=s.result||{};if(r.length===0)return;const{common:{isTopic:m}}=this._core;m(r[0].conversationID)||(this.updateLocalConversationList({conversationUpdateFieldList:r,isInstantMessage:g,isUnreadC2CMessage:u,isFromGetConversations:!1,updateUnreadCount:E}),r.filter(D=>this._isConversationNeedShow(D.conversationID)).length>0&&this.emitConversationListUpdate())}_handleNewGroupAtTips(s){const{GroupTips:r=[]}=s;r.forEach(g=>{const{GroupAtTips:u,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};u?M=this._convertGroupAtTipsKey(u):E?M=Object.assign({},this._convertGroupAtTipsKey(E)):g.groupAtType&&(M=Object.assign({},g)),M.__random=m,M.__sequence=D,this._groupAtTipsList.push(M)}),console.log(`${this._name}._handleNewGroupAtTips groupAtTipsList: ${JSON.stringify(this._groupAtTipsList)}`),this._updateGroupAtInfoList()}_convertGroupAtTipsKey(s){const{From_Account:r,GroupId:g,MsgSeq:u,GroupAtType:E}=s;return{from:r,groupID:g,sequence:u,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:r}=this._core,g=s.getCurrentUserID();let u=!1;this._groupAtTipsList.forEach(E=>{const{groupID:m,from:D}=E;if(D!==g){const M=this.getLocalConversation(`${r.CONV_GROUP}${m}`);M&&(M.updateGroupAtInfoList(E),u=!0)}}),u&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var r,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:u},OuterConstant:E}=this._core,m=u?.getLocalMessageList(s)||[];let D={};for(let P=(m.length||0)-1;P>=0;P--)if(!m[P].isDeleted&&m[P]._isExcludedFromLastMessage!==!0){D=m[P];break}const M=this.getLocalConversation(s);if(!M)return;let T=!1;M.lastMessage.lastSequence===D.sequence&&M.lastMessage.lastTime===D.time||(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D)&&(D=void 0),M.updateLastMessage(D),T=!0),s.startsWith(E.CONV_C2C)&&this.updateUnreadCount(s),T&&(this.emitConversationListUpdate(),console.log(`${this._name}._handleMessageDeleted. update conversationID:${s} with lastMessage:`,M.lastMessage))}_handleMessageRevoked(s){const{messageList:r=[],updateUnreadCount:g=!0}=s;if(console.log(`${this._name}._handleMessageRevoked messageList:${r.length}`),r.length===0)return;let u=null,E=!1;r.forEach(m=>{u=this.getLocalConversation(m.conversationID),u&&(g&&u.reduceUnreadCount()&&(E=!0),u.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(u.setLastMessageRevoked(!0),u.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:r},common:{getMessagePreviewText:g},ssoLog:u}=this._core;u.debug(`${this._name}._handleMessageModified`,JSON.stringify(s));const{conversationID:E,messageList:m}=s,D=this.getLocalConversation(E);if(r(D))return;const{lastMessage:M}=D;if(M){const T=m?.[0]||{};M.lastTime===T.time&&M.lastSequence===T.sequence&&M.version!==T.version&&(M.type=T.type,M.payload=T.payload,M.messageForShow=g(T.type,T.payload),M.cloudCustomData=T.cloudCustomData,M.version=T.version,this.emitConversationListUpdate(),console.log(`${this._name} conversationID:${E} lastMessage updated`))}}_handleConversationUpdated(s){this.emitConversationListUpdate(s?.needSort)}updateLocalConversationList(s){const{isFromGetConversations:r}=s,{newConversationList:g}=this._getTmpConversationListMapping(s);this._sortConversationList(),r||this._updateNewConversationProfile(g),this._core.ssoLog.debug("updateLocalConversationList",` newConversationList: ${g.length}`)}_getTmpConversationListMapping(s){const{OuterConstant:r}=this._core,{conversationUpdateFieldList:g,isFromGetConversations:u,isInstantMessage:E,isUnreadC2CMessage:m=!1,updateUnreadCount:D}=s,M=[],T=g?.length;for(let P=0;P{M[1].isPinned===!0?s(M[1].lastMessage.lastTime)?u.push(M):g.push(M):s(M[1].lastMessage.lastTime)?m.push(M):E.push(M)});const D=g.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime).concat(u).concat(E.sort((M,T)=>T[1].lastMessage.lastTime-M[1].lastMessage.lastTime)).concat(m);this._updateConversationMapFromList(D)}_updateNewConversationProfile(s){if(s.length===0)return;const r=[],g=[],{OuterConstant:{CONV_GROUP:u,CONV_C2C:E}}=this._core;s.forEach(m=>{const{conversationID:D,type:M}=m;if(M===E){const T=D.replace(E,"");r.push(T)}else if(M===u){const T=D.replace(u,"");g.push(T)}}),r.length>0&&this._updateC2CConversation(r),g.length>0&&this._updateGroupConversation(g)}_updateC2CConversation(s){var r;const{OuterConstant:{CONV_C2C:g},appStore:{userStore:u},user:E}=this._core;let m=!1;(r=E.userProfile)===null||r===void 0||r.getUserProfile({userIDList:s}).then(D=>{(D?.data||[]).forEach(M=>{var T;const{userID:P}=M,W=this.getLocalConversation(`${g}${P}`);if(W){const oA=((T=u.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=oA,W.userProfile=M,m=!0}}),m&&this.emitConversationListUpdate()}).catch(D=>{}),QA.get(s)}_updateGroupConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g},utils:{safeStringify:u},ssoLog:E,apiMap:{getGroupProfile:m}}=this._core;let D=!1;try{yield Promise.all(s.map(M=>mA(this,void 0,void 0,function*(){const T=g.getGroup(M),P=this.getLocalConversation(`${r}${M}`);T&&P&&(P.groupProfile=T,D=!0),P&&!P.getProfileCompleted()&&typeof m=="function"&&(yield m({groupID:M}))}))),yA.get(s),D&&this.emitConversationListUpdate()}catch(M){E.debug("_updateGroupConversation",u(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:r}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(u=>{const{To_Account:E,UinPairReadArray:m=[]}=u?.C2cReadedReceipt||{};m?.forEach(D=>{const{LastReadTime:M}=D,T=`${r}${E}`;this._updateConversationReadInfo({conversationID:T,peerReadTime:M}),this._updateMessageListPeerRead({conversationID:T,peerReadTime:M})})})}_updateConversationReadInfo(s){const{appStore:r,utils:{isEmpty:g},common:{getCurrentUserID:u}}=this._core,{conversationID:E,peerReadTime:m}=s,D=r.conversationStore.getConversationMap();if(D.has(E)){const M=D.get(E);M.peerReadTime=m;const T=M?.lastMessage;g(T)||T.fromAccount===u()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,r.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:r,OuterEvent:g,message:u}=this._core,{conversationID:E,peerReadTime:m}=s,D=u.messageDataHandler.getLocalMessageList(E),M=u.messageDataHandler.getSparseMessageList(E),T=[];D.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),M.forEach(P=>{P.time<=m&&!P.isPeerRead&&P.flow==="out"&&(P.isPeerRead=!0,T.push(P))}),r.emitOuterEvent(g.MESSAGE_READ_BY_PEER,{name:g.MESSAGE_READ_BY_PEER,data:T})}_isConversationNeedShow(s){var r,g;const{OuterConstant:{CONV_GROUP:u,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===u&&((r=M.groupProfile)===null||r===void 0?void 0:r.type)===E,P=M.type===u&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,r=!0){var g,u;let E=!1;const m=this.getLocalConversation(s),D=(u=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||u===void 0?void 0:u.getLocalMessageList(s);if(!m)return E;const M=m.unreadCount,T=D?.filter(P=>!P.isRead&&!P._onlineOnlyFlag&&!P.isDeleted).length;return console.log(`${this._name}._updateUnreadCount conversationID:${s} currentUnreadCount:${M} newUnreadCount:${T}`),M!==T&&(m.unreadCount=T,E=!0,r===!0&&this.emitConversationListUpdate()),E}emitConversationListUpdate(s=!1){var r,g;s&&this._sortConversationList();const{OuterEvent:{CONVERSATION_LIST_UPDATED:u},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:u,data:m,isSyncCompleted:(g=(r=E?.syncConversationHandler)===null||r===void 0?void 0:r.isSyncCompleted)===null||g===void 0?void 0:g.call(r)}),this._emitTotalUnreadCountUpdate()}_emitTotalUnreadCountUpdate(){var s;const r=this.getTotalUnreadMessageCount();this._totalUnreadCount!==r&&(this._core.ssoLog.debug("_emitTotalUnreadCountUpdate",` from ${this._totalUnreadCount} to ${r}`),this._totalUnreadCount=r,this._emitEvent({name:(s=this._core)===null||s===void 0?void 0:s.OuterEvent.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED,data:r}))}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}getTotalUnreadMessageCount(){const{OuterConstant:s,utils:{isEmpty:r}}=this._core,g=this.getLocalConversationList();let u=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(r(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(u+=E.unreadCount)}),u}getLocalConversationList(){return[...this._conversationStore.getConversationMap().values()].filter(s=>this._isConversationNeedShow(s.conversationID))}hasLocalConversation(s){return this._conversationStore.getConversationMap().has(s)}getLocalConversation(s){return this._conversationStore.getConversationMap().get(s)}setLocalConversation(s,r){return this._conversationStore.getConversationMap().set(s,r)}deleteLocalConversation(s){this._conversationStore.getConversationMap().delete(s)}_updateConversationMapFromList(s){this._clearConversationMap();for(const[r,g]of s)this.setLocalConversation(r,g)}_clearConversationMap(){this._conversationStore.getConversationMap().clear()}patchMessageRemindType(s,r){let g=!1;s.forEach(u=>{const E=this.getLocalConversation(u);E?.messageRemindType!==r&&(E.messageRemindType=r,g=!0)}),console.log(`${this._name}.patchMessageRemindType conversationIDList:${s} messageRemindType:${r} hasUpdated:${g}`),g&&this.emitConversationListUpdate()}markMessageAsRead(s){const{message:{messageDataHandler:r}}=this._core,{conversationID:g,lastReadTime:u=0,lastReadSequence:E=0}=s,m=r?.getLocalMessageList(g);if(m.length===0)return;const{length:D}=m;for(let M=D-1;M>=0;M--){const T=m[M],P=u&&T.time>u,W=E&&T.sequence>E;if(!P&&!W){if(T.flow==="in"&&T.isRead)break;T.setIsRead(!0)}}}appendToPinnedConversation(s){const r=[...this._conversationStore.getConversationMap().entries()],g=r.findIndex(u=>u[1].isPinned===!1);r.splice(g,0,[s.conversationID,s]),this._updateConversationMapFromList(r),this.emitConversationListUpdate()}_reset(){this._clearConversationMap(),this._totalUnreadCount=0,this._groupAtTipsList=[]}_dispose(){const{notificationCenter:s,InnerEvent:{NEW_MESSAGE:r,MESSAGE_DELETED:g,MESSAGE_REVOKED:u,MESSAGE_MODIFIED:E,CONVERSATION_UPDATED:m,LOGOUT:D,DESTROY:M,SYNC_CONVERSATION_LIST:T}}=this._core,{InnerEventSubType:{GROUP_AT_TIPS:P}}=s;s.unSubscribeInnerEvent(r,this._handleNewMessage,this),s.unSubscribeInnerEvent(r,P,this._handleNewGroupAtTips,this),s.unSubscribeInnerEvent(g,this._handleMessageDeleted,this),s.unSubscribeInnerEvent(u,this._handleMessageRevoked,this),s.unSubscribeInnerEvent(E,this._handleMessageModified,this),s.unSubscribeInnerEvent(m,this._handleConversationUpdated,this),s.unSubscribeInnerEvent(T,this._handleConversationSynced,this),s.unSubscribeInnerEvent(D,this._reset,this),s.unSubscribeInnerEvent(M,this._dispose,this)}},XA=new class{constructor(){this._name="GetConversationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationList",context:this})}getConversationList(s){return mA(this,void 0,void 0,function*(){return{code:0,data:{conversationList:this._getConversationList(s),isSyncCompleted:this._core.conversation.syncConversationHandler.isSyncCompleted()}}})}_getConversationList(s){const{utils:{isUndefined:r,isArray:g,isPlainObject:u}}=this._core;if(r(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(u(s)){const{type:E,markType:m,groupName:D,hasUnreadCount:M,hasGroupAtInfo:T}=s;return NA.getLocalConversationList().filter(P=>this._filterType(P,E)&&this._filterMarkType(P,m)&&this._filterGroupName(P,D)&&this._filterUnreadCount(P,M)&&this._filterGroupAtInfo(P,T))}return[]}_filterType(s,r){const{OuterConstant:g}=this._core;return r!==g.CONV_C2C&&r!==g.CONV_GROUP||s.type===r}_filterGroupName(s,r){const{utils:{isString:g}}=this._core;return!g(r)||(r===""?s.conversationGroupList.length===0:s.conversationGroupList.includes(r))}_filterMarkType(s,r){const{utils:{isNumber:g}}=this._core;return!g(r)||(r===0?s.markList.length===0:s.markList.includes(r))}_filterUnreadCount(s,r){let g=!0;return r===!0?g=s.unreadCount>=1:r===!1&&(g=s.unreadCount===0),g}_filterGroupAtInfo(s,r){let g=!0;return r===!0?g=s.groupAtInfoList.length>=1:r===!1&&(g=s.groupAtInfoList.length===0),g}},Te=new class{constructor(){this._name="GetConversationProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getConversationProfile",context:this})}getConversationProfile(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,GRP_AVCHATROOM:u},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(Ls(s))return D.data.conversation=M,D;let T=!1;const P=mt(s)?r:g;if(m(M)&&(T=!0,M=new Bt({conversationID:s,type:P})),console.log(`${this._name}.getConversationProfile conversationID:${s} isNewConversation:${T}`),D.data.conversation=M,M?.getProfileCompleted())return D;if(P===r){const W=s.replace(r,"");yield this._handleC2CConversation(M,W),T&&(yield QA.get([W]))}if(P===g){const W=s.replace(g,"");if(!E.getGroup(W))return D;yield this._handleGroupConversation(M,W),T&&M.groupProfile.type!==u&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,r){return mA(this,void 0,void 0,function*(){var g,u;const{user:E,helper:m,utils:{isEmpty:D},appStore:{conversationStore:M,userStore:T}}=this._core,{conversationID:P}=s,W=yield(g=E.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:[r]});if(W?.data.length===0)throw new m.ChatError({code:Qa.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const oA=(u=T.getFriend(r))===null||u===void 0?void 0:u.remark;D(oA)||s.remark===oA||(s.remark=oA),s.setProfileCompleted();const EA=NA.hasLocalConversation(P);console.log(`${this._name}._handleC2CConversation conversationID:${P} hasLocalConversation: ${EA}`),EA?M.updateConversation(P,s):NA.appendToPinnedConversation(s)})}_handleGroupConversation(s,r){return mA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:u}}=this._core,{conversationID:E}=s,m=yield g({groupID:r});s.groupProfile=m?.data.group,s.setProfileCompleted();const D=NA.hasLocalConversation(E);console.log(`${this._name}._handleGroupConversation conversationID:${E} hasLocalConversation: ${D}`),D?u.updateConversation(E,s):NA.appendToPinnedConversation(s)})}},de=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"getTotalUnreadMessageCount",context:this})}getTotalUnreadMessageCount(){return NA.getTotalUnreadMessageCount()}},ke=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:r,common:{isTopic:g},notificationCenter:u,InnerEvent:{MESSAGE_PUSH:E},InnerEventSubType:{ALL_MESSAGE_READ:m}}=s;r.registerApi({apiName:"setMessageRead",context:this,matcher:D=>!g(D[0].conversationID)}),r.registerApi({apiName:"setAllMessageRead",context:this}),u.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:r},OuterConstant:g}=this._core;s.forEach(u=>{const{ReadC2cMsgNotify:E}=u;if(!r(E)){const{UinPairReadArray:m=[]}=E;m.forEach(D=>{const{From_Account:M,LastReadTime:T}=D,P=`${g.CONV_C2C}${M}`;console.log(`${this._name}.handleC2CMessageReadSync conversationID:${P} lastReadTime:${T}`),NA.markMessageAsRead({conversationID:P,lastReadTime:T}),NA.updateUnreadCount(P)})}})}handleGroupMessageReadSync(s){const{OuterConstant:r,utils:{isUndefined:g}}=this._core;s.forEach(u=>{const{GroupReadInfoArray:E}=u.MsgBody;g(E)||E.forEach(m=>{const{GroupId:D,LastReadMsgSeq:M}=m,T=`${r.CONV_GROUP}${D}`;console.log(`${this._name}.handleGroupMessageReadSync conversationID:${T} lastReadSequence:${M}`),NA.markMessageAsRead({conversationID:T,lastReadSequence:M}),NA.updateUnreadCount(T),this._clearGroupAtInfoList(T)})})}setMessageRead(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:u}=this._core,{conversationID:E}=s,m={code:0,data:{}},D=NA.getLocalConversation(E);let M=`${this._name}.setMessageRead conversationID:${E} unreadCount:${D?.unreadCount||0}`;if(m.successLog={message:M},!D)return m;const T=!(!((g=(r=this._core)===null||r===void 0?void 0:r.helper)===null||g===void 0)&&g.isEmpty(D.groupAtInfoList));if(D.type===u.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===u.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===u.CONV_GROUP){const W=this._getLocalMessageMaxSequence(D);M+=`lastMessageSequence:${W}`,yield this._setGroupMessageRead(E,W)}}catch(W){const{errorCode:oA,errorInfo:EA}=W;throw new P({functionName:"setMessageRead",code:oA,message:EA,moreMessage:M})}return D.type===u.CONV_SYSTEM&&(D.unreadCount=0),NA.emitConversationListUpdate(),Object.assign(Object.assign({},m),{successLog:{message:M}})})}setAllMessageRead(){return mA(this,arguments,void 0,function*(s={}){const{OuterConstant:{READ_ALL_MSG:r},utils:{safeStringify:g}}=this._core;let u=`scope:${s.scope}`;s.scope||(s.scope=r);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===ta&&m.groupMessageReadInfoList.length===0)return{code:0};try{const D=yield function(M){return mA(this,void 0,void 0,function*(){const{allC2CMessageReadStatus:T,groupMessageReadInfoList:P}=M,W={C2CReadAllMsg:T,GroupReadInfo:P};return Bo.core.common.buildAndSendPacket({servcmd:"openim.read_all_unread_msg",data:W})})}(m);if(D){const{GroupReadInfoArray:M,C2CReadAllMsg:T}=D,P=this._parseGroupReadInfo(M);this._updateAllConversationReadStatus({allC2CMessageReadStatus:T})>0&&NA.emitConversationListUpdate(),u+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:u}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:u})}})}_handleAllMessageRead(s){const{GroupReadInfoArray:r,C2CReadAllMsg:g}=s;this._parseGroupReadInfo(r),this._updateAllConversationReadStatus({allC2CMessageReadStatus:g})>0&&NA.emitConversationListUpdate()}_updateAllConversationReadStatus(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g},appStore:u}=this._core,E=u.conversationStore.getConversationMap(),{allC2CMessageReadStatus:m}=s;let D=0;for(const[M,T]of E)if(T.unreadCount>=1){if(m===H&&T.type===r){const P=this._getLocalMessageMaxTime(T);NA.markMessageAsRead({conversationID:M,lastReadTime:P})}else if(T.type===g){const P=M.replace(g,"");if(this._serverGroupConversationLastReadSeqMap.has(P)){const W=this._serverGroupConversationLastReadSeqMap.get(P);NA.markMessageAsRead({conversationID:M,lastReadSequence:W})}}NA.updateUnreadCount(M,!1)&&(D+=1)}return D}_generateSetAllMessageReadRequestData(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_C2C_MSG:u},appStore:E}=this._core,m={allC2CMessageReadStatus:ta,groupMessageReadInfoList:[]},D=E.conversationStore.getConversationMap();for(const[,M]of D){const{type:T,unreadCount:P}=M;if(this._shouldSetAllMessageRead({scope:s,type:T,unreadCount:P})){if(T===r&&m.allC2CMessageReadStatus===ta){if(m.allC2CMessageReadStatus=H,s===u)break}else if(T===g){const W=this._getLocalMessageMaxSequence(M),{groupID:oA}=M.groupProfile;m.groupMessageReadInfoList.push({GroupId:oA,MsgSeq:W})}}}return m}_parseGroupReadInfo(s){const{utils:{isUndefined:r}}=this._core,g=[];return s?.forEach(u=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=u;r(D)?this._serverGroupConversationLastReadSeqMap.set(E,M):(this._serverGroupConversationLastReadSeqMap.set(E,m),D!==0&&g.push(`${E}-${m}-${D}`))}),g}_deleteGroupAtTips(s){return mA(this,void 0,void 0,function*(){console.log(`${this._name}._deleteGroupAtTips conversationID:${s}`);const r=NA.getLocalConversation(s);if(!r)return;const g=r?.groupAtInfoList||[];if(g.length!==0)try{const{common:{getCurrentUserID:u,isCommunity:E},OuterConstant:{CONV_GROUP:m,CONV_AT_ALL:D}}=this._core;let M=[...g];if(E({groupID:s.replace(m,"")})&&(M=g.filter(P=>!P.atTypeArray.includes(D)),M.length===0))return void this._clearGroupAtInfoList(s,!1);const T=M.map(P=>({From_Account:P.from,To_Account:u(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return mA(this,void 0,void 0,function*(){const{messageListToDelete:oA}=P,EA={DelMsgList:oA};return W.common.buildAndSendPacket({servcmd:"openim.deletemsg",data:EA})})}({messageListToDelete:T},this._core),console.log(`${this._name}._deleteGroupAtTips ok. count:${g.length}`),this._clearGroupAtInfoList(s)}catch(u){console.error(`${this._name}._deleteGroupAtTips fail:`,u)}})}_clearGroupAtInfoList(s,r=!0){const g=NA.getLocalConversation(s);g&&(g.groupAtInfoList.length>0&&(g.clearGroupAtInfoList(),console.log(`${this._name}._clearGroupAtInfoList conversationID:${s} needEmitConversationUpdate:${r}`)),r&&NA.emitConversationListUpdate())}_getLocalMessageMaxTime(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.time));let m=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastTime)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxTime update lastMessageTime from ${m} to ${E}`),m=E),m}_getLocalMessageMaxSequence(s){var r;const{conversationID:g}=s,u=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...u.map(D=>D.sequence));let m=((r=s?.lastMessage)===null||r===void 0?void 0:r.lastSequence)||0;return E>m&&(console.log(`${this._name}._getLocalMessageMaxSequence update lastMessageSequence from ${m} to ${E}`),m=E),m}_setC2CMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){return u.common.buildAndSendPacket({servcmd:"openim.msgreaded",data:g})})}({C2CMsgReaded:{Cookie:"",C2CMsgReadedItem:[{To_Account:s.replace("C2C",""),LastedMsgTime:r,Receipt:1}]}},this._core),console.log(`${this._name}._setC2CMessageRead ok, lastReadTime:${r}`),NA.markMessageAsRead({conversationID:s,lastReadTime:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setC2CMessageRead fail:`,g),g}})}_setGroupMessageRead(s,r){return mA(this,void 0,void 0,function*(){try{yield function(g,u){return mA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return u.common.buildAndSendPacket({servcmd:"group_open_http_svc.msg_read_report",data:D})})}({groupID:s.replace("GROUP",""),lastMessageSequence:r},this._core),console.log(`${this._name}._setGroupMessageRead ok, lastReadSequence:${r}`),NA.markMessageAsRead({conversationID:s,lastReadSequence:r}),NA.updateUnreadCount(s)}catch(g){throw console.warn(`${this._name}._setGroupMessageRead fail:`,g),g}})}_shouldSetAllMessageRead(s){const{OuterConstant:{CONV_C2C:r,CONV_GROUP:g,READ_ALL_MSG:u,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==r||![u,E].includes(M))||!(D!==g||![u,m].includes(M)))}},ue=new class{constructor(){this._name="PinConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"pinConversation",context:this})}handleConversationPinned(s,r){const{utils:{isArray:g}}=this._core;if(!g(s))return;const{OuterConstant:u}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${u.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${u.CONV_GROUP}${T}`)),P&&(console.log(`${this._name}.handleConversationPinned conversationID:${P.conversationID} localPinned:${P.isPinned} remotePinned:${r}`),r&&!P.isPinned&&(P.isPinned=!0,E=!0),!r&&P.isPinned&&(P.isPinned=!1,E=!0))}),E&&NA.emitConversationListUpdate(!0)}pinConversation(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,common:g,helper:{ChatError:u}}=this._core,{conversationID:E,isPinned:m}=s,D={code:0,data:{conversationID:E}},M=NA.getLocalConversation(E);if(M&&M.isPinned===m)return D;if(Ls(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(mt(E)?P={Type:1,To_Account:E.replace(r.CONV_C2C,"")}:ug(E)&&(P={Type:2,GroupId:E.replace(r.CONV_GROUP,"")}),yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:xA}=oA,LA={From_Account:wA,OperationType:kA,RecentContactItem:xA};return EA.common.buildAndSendPacket({servcmd:"recentcontact.top",data:LA})})}({fromAccount:g.getCurrentUserID(),operationType:m===!0?1:2,itemList:[P]},this._core)){if(M)M.isPinned!==m&&(M.isPinned=m);else{const oA=new Bt({conversationID:E,type:mt(E)?r.CONV_C2C:r.CONV_GROUP,isPinned:m});NA.setLocalConversation(E,oA)}NA.emitConversationListUpdate(!0)}return Object.assign(Object.assign({},D),{successLog:{message:T}})}catch(P){const{errorCode:W,errorInfo:oA}=P;throw new u({functionName:"pinConversation",code:W,message:oA,moreMessage:T})}})}},Oe=new class{constructor(){this._name="DeleteConversation"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteConversation",context:this})}handleConversationDeleted(s){const{utils:{isArray:r}}=this._core;if(!r(s))return;const{OuterConstant:g}=this._core,u=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&u.push(`${g.CONV_C2C}${D}`),m===2&&u.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${u}`),this._deleteLocalConversationList(u)}deleteConversation(s){return mA(this,void 0,void 0,function*(){const{utils:{isString:r}}=this._core;if(r(s))return this._deleteConversation({conversationIDList:[s],flag:ca.ONLY_CONVERSATIONID});const g=Object.assign({},s);return g.conversationIDList.length>100&&(g.conversationIDList=g.conversationIDList.slice(0,100)),this._deleteConversation(g)})}_deleteConversation(s){return mA(this,void 0,void 0,function*(){const{conversationIDList:r,clearHistoryMessage:g=!0,flag:u=0}=s,{helper:{ChatError:E}}=this._core,m=`conversationIDList:${r} clearHistoryMessage:${g}`;try{const D=yield Promise.all([this._deleteConversationFromLocal(r),this._deleteConversationFromServer(r,g)]),M=[...D[0],...D[1]];if(M.length===0)throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});return{code:0,data:u===ca.ONLY_CONVERSATIONID?{conversationID:M[0]}:{conversationIDList:M},successLog:{message:m}}}catch(D){const{errorCode:M,errorInfo:T}=D;throw new E({code:M,message:T,moreMessage:m})}})}_deleteConversationFromLocal(s){const{OuterConstant:r}=this._core;return s.filter(g=>{var u;if(!NA.hasLocalConversation(g))return!1;const E=(u=NA.getLocalConversation(g))===null||u===void 0?void 0:u.type;return E!==r.CONV_GROUP||this._hasLocalGroup(g)?E===r.CONV_SYSTEM&&(this._deleteLocalConversation(g),!0):(this._deleteLocalConversation(g),!0)})}_deleteConversationFromServer(s,r){return mA(this,void 0,void 0,function*(){const{OuterConstant:g,common:u}=this._core,E={fromAccount:u.getCurrentUserID(),conversationList:[],clearHistoryMessage:r?1:0};if(s.forEach(D=>{var M;if(NA.hasLocalConversation(D)){const T=((M=NA.getLocalConversation(D))===null||M===void 0?void 0:M.type)||"",P=D.replace(T,"");T===g.CONV_C2C?E.conversationList.push({To_Account:P,Type:1}):T===g.CONV_GROUP&&this._hasLocalGroup(D)&&E.conversationList.push({ToGroupid:P,Type:2})}}),E.conversationList.length===0)return[];const m=yield function(D,M){return mA(this,void 0,void 0,function*(){const{fromAccount:T,conversationList:P,clearHistoryMessage:W}=D,oA={From_Account:T,ContactItem:P,ClearRamble:W};return M.common.buildAndSendPacket({servcmd:"recentcontact.batch_delete",data:oA})})}(E,this._core);if(m){const{ResultItem:D=[]}=m,M=[];return D.length>0&&D.forEach(T=>{if(T.ResultCode===0){const P=T.Type===1?`${g.CONV_C2C}${T.To_Account}`:`${g.CONV_GROUP}${T.ToGroupid}`;M.push(P)}}),this._deleteLocalConversationList(M),M}return[]})}_deleteLocalConversationList(s){let r=!1;s.forEach(g=>{NA.hasLocalConversation(g)&&(this._deleteLocalConversation(g,!1),r=!0)}),console.log(`${this._name}._deleteLocalConversationList isUpdate:${r}`),r&&NA.emitConversationListUpdate()}_deleteLocalConversation(s,r=!0){const g=NA.hasLocalConversation(s);console.log(`${this._name}._deleteLocalConversation conversationID:${s} has:${g}`),g&&(NA.deleteLocalConversation(s),this._deleteConversationLocalMessage(s),r&&NA.emitConversationListUpdate())}_hasLocalGroup(s){const{OuterConstant:{CONV_GROUP:r},appStore:{groupStore:g}}=this._core,u=s.replace(r,"");return!!g.getGroup(u)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},Rt=new class{constructor(){this._name="SetConversationDraft"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setConversationDraft",context:this})}setConversationDraft(s){return mA(this,void 0,void 0,function*(){const{conversationID:r,draftText:g}=s;if(console.log(`${this._name} conversationID:${r} draftText:${g}`),!NA.hasLocalConversation(r))throw new this._core.helper.ChatError({code:Qa.CONV_NOT_FOUND});const u=NA.getLocalConversation(r);return u?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:u}}})}},Xt=new class{constructor(){this._name="SetC2CMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){s.length>30&&(console.warn(`${this._name}.set userIDList length:${s.length} exceeds limit 30`),s.splice(30));const g=function(){const{MSG_REMIND_ACPT_AND_NOTE:P,MSG_REMIND_DISCARD:W,MSG_REMIND_ACPT_NOT_NOTE:oA}=Bo.core.OuterConstant;return{[P]:0,[W]:1,[oA]:2}}()[r],u=yield function(P,W){return mA(this,void 0,void 0,function*(){const{userIDList:oA,receiveMessageOption:EA}=P,wA={Peer_Account:oA,Mute_Notifications:EA};return W.common.buildAndSendPacket({servcmd:"openim.set_c2c_peer_mute_notifications",data:wA})})}({userIDList:s,receiveMessageOption:g},this._core),{ErrorList:E=[]}=u||{},m=[];E.forEach(P=>{const{Peer_Account:W,ErrorCode:oA}=P;m.push({userID:W,code:oA});const EA=s.indexOf(W);EA>-1&&s.splice(EA,1)});const D=[],M=[],{OuterConstant:T}=this._core;return s.forEach(P=>{M.push(`${T.CONV_C2C}${P}`),D.push({userID:P})}),NA.patchMessageRemindType(M,r),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},li=new class{constructor(){this._name="SetGroupMessageRemindType"}init(s){this._core=s}set(s,r){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:g,isTopic:u},OuterConstant:E}=this._core;if(yield function(m,D){return mA(this,void 0,void 0,function*(){const{groupID:M,userID:T,receiveMessageOption:P}=m,W={GroupId:M,Member_Account:T,MsgFlag:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:W})})}({groupID:s,userID:g(),receiveMessageOption:r},this._core),!u(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],r)}return{code:0,data:{groupID:s,messageRemindType:r}}})}},Mt=new class{constructor(){this._name="SetMessageRemindType"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setMessageRemindType",context:this})}handleC2CMessageRemindTypeSync(s){const{helper:{isEmpty:r},OuterConstant:g,ssoLog:u}=this._core;s.forEach(E=>{const{MuteNotificationsSync:m}=E;if(!r(m)){const{To_Account:D,MuteNotifications:M}=m,T=D.map(W=>`${g.CONV_C2C}${W}`),P=Zi(M);u.debug(`${this._name}.handleC2CMessageRemindTypeSync conversationIDList:${T} messageRemindType:${P}`),NA.patchMessageRemindType(T,P)}})}setMessageRemindType(s){return mA(this,void 0,void 0,function*(){const r="setMessageRemindType",{groupID:g,userIDList:u,messageRemindType:E}=s,{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;try{if(!D(g))return M.debug(`${this._name}.${r} groupID:${g} messageRemindType:${E}`),yield li.set(g,E);if(!D(u))return M.debug(`${this._name}.${r} userIDList:${u} messageRemindType:${E}`),yield Xt.set(u,E);throw new m.ChatError({functionName:r,message:"userIDList or groupID is required"})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo,moreMessage:`groupID:${g} userIDList:${u} messageRemindType:${E}`})}})}},pi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,XA.init(s),Te.init(s),de.init(s),ke.init(s),ue.init(s),Oe.init(s),Rt.init(s),Mt.init(s);const{notificationCenter:r,InnerEvent:{MESSAGE_PUSH:g,DESTROY:u}}=this._core,{InnerEventSubType:{CONV_MODIFIED:E,C2C_MESSAGE_READ_SYNC:m,GROUP_MESSAGE_READ_SYNC:D,C2C_REMIND_TYPE_SYNC:M}}=r;r.subscribeInnerEvent(g,E,this._onConversationModified,this),r.subscribeInnerEvent(g,m,this._onC2CMessageReadSync,this),r.subscribeInnerEvent(g,M,this._onC2CMessageRemindTypeSync,this),r.subscribeInnerEvent(g,D,this._onGroupMessageReadSync,this),r.subscribeInnerEvent(u,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:r}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(u=>{const{PushType:E}=u;if(E===r.CONV_DELETED){const{RecentContactList:m}=u.RecentContactDeleteItem;Oe.handleConversationDeleted(m)}if(E===r.CONV_PINED){const{RecentContactList:m}=u.RecentContactTopItem;ue.handleConversationPinned(m,!0)}if(E===r.CONV_UNPINED){const{RecentContactList:m}=u.RecentContactTopItem;ue.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:r=[]}=s;ke.handleC2CMessageReadSync(r)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:r=[]}=s;Mt.handleC2CMessageRemindTypeSync(r)}_onGroupMessageReadSync(s){const{GroupTips:r=[]}=s;ke.handleGroupMessageReadSync(r)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:r,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:u,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(r,u,this._onConversationModified,this),s.unSubscribeInnerEvent(r,E,this._onC2CMessageReadSync,this),s.unSubscribeInnerEvent(r,D,this._onC2CMessageRemindTypeSync,this),s.unSubscribeInnerEvent(r,m,this._onGroupMessageReadSync,this),s.unSubscribeInnerEvent(g,this._dispose,this)}},io=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setAllReceiveMessageOpt",context:this})}setAllReceiveMessageOpt(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:{MSG_REMIND_ACPT_NOT_NOTE:r}}=this._core,{messageRemindType:g=r,isRepeated:u=!0}=s,{startTime:E=0,endTime:m=0}=this._calcStartAndEndTime(s),D=yield function(M){return mA(this,void 0,void 0,function*(){const{common:T}=Bo.core,{startTime:P,endTime:W,isRepeated:oA,messageRemindType:EA}=M,wA={StartTime:P,EndTime:W,IsRepeated:oA,Level:EA};return T.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_set_do_not_disturb",data:wA})})}({messageRemindType:this._getType(g),startTime:E,endTime:m,isRepeated:u?os.ON:os.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(r){oc("setAllReceiveMessageOpt",r)}})}_calcStartAndEndTime(s){const{startHour:r=0,startMinute:g=0,startSecond:u=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),r,g,u),T=Math.round(M.getTime()/1e3);let P=T+E;return m&&E>=86400&&(P=T+86400),{startTime:T,endTime:P}}_getType(s){const{OuterConstant:r}=this._core;return{[r.MSG_REMIND_ACPT_AND_NOTE]:0,[r.MSG_REMIND_DISCARD]:1,[r.MSG_REMIND_ACPT_NOT_NOTE]:2}[s]}},Is=new class{init(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:u}=s;r.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(u.MESSAGE_PUSH,g.InnerEventSubType.ALL_RECEIVE_MESSAGE_OPTION,this.onAllReceiveMsgOptionNotify,this)}onAllReceiveMsgOptionNotify(s){const r=this._handleResult(s),{notificationCenter:g,OuterEvent:{ALL_RECEIVE_MESSAGE_OPT_UPDATED:u}}=this._core;g.emitOuterEvent(u,{name:u,data:r})}getAllReceiveMessageOpt(){return mA(this,void 0,void 0,function*(){try{const s=yield function(){return mA(this,void 0,void 0,function*(){const{common:r}=Bo.core,g={To_Account:r.getCurrentUserID()};return r.buildAndSendPacket({servcmd:"im_msg_db_logic.ws_get_do_not_disturb",data:g})})}();return{code:0,data:this._handleResult(s)}}catch(s){oc("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:r}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:u,MSG_REMIND_ACPT_NOT_NOTE:E}=r,m={0:g,1:u,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===os.ON}}},Fo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Xt.init(s),li.init(s),QA.init(s),yA.init(s),io.init(s),Is.init(s)}};const ni=s=>!mt(s)&&!ug(s)&&!Ls(s),Fr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ni(s)||"conversationID is invalid."},isPinned:{required:!0,rules:["boolean"],allowEmpty:!1}},deleteConversation:[{key:"options",required:!0,rules:["string","object"],allowEmpty:!1,customValidator:s=>{const{core:{utils:{isArray:r,isObject:g,isString:u}}}=Bo;if(!u(s)&&!g(s))return"options is String or Object.";if(u(s)&&ni(s))return"conversationID is invalid.";if(g(s)){if(!r(s.conversationIDList))return"conversationIDList is not Array.";if(s.conversationIDList.length===0)return"conversationIDList is empty.";if(s.conversationIDList.some(E=>{if(ni(E))return!0}))return"conversationIDList includes invalid conversationID.";if(s.clearHistoryMessage&&typeof s.clearHistoryMessage!="boolean")return"clearHistoryMessage is not Boolean."}return!0}}],setConversationDraft:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!mt(s)&&!ug(s))||"conversationID is invalid."},draftText:{required:!0,rules:["string"],allowEmpty:!0}},setAllReceiveMessageOpt:{messageRemindType:{required:!1,rules:["string"],allowEmpty:!0},startHour:{required:!1,rules:["number"],allowEmpty:!0},startMinute:{required:!1,rules:["number"],allowEmpty:!0},startSecond:{required:!1,rules:["number"],allowEmpty:!0},duration:{required:!1,rules:["number"],allowEmpty:!0},isRepeated:{required:!1,rules:["boolean"],allowEmpty:!0}}},Zo={getConversationList:!0,getConversationProfile:!0,getTotalUnreadCount:!0,setMessageRead:!0,pinConversation:!0,deleteConversation:!0,setConversationDraft:!0,setMessageRemindType:!0,getAllReceiveMessageOpt:!0,setAllReceiveMessageOpt:!0};var zn=new class{constructor(){this.name="Conversation"}install(s){Bo.init(s),pi.init(s),Fo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:Zo,params:Fr})}};const Zn=new class{init(s){this.core=s}},ia="AVChatRoom",qr="AV_HISTORY_MSG",sc="GRP_COUNTER",ju="Set",Dm="Increase",_i="Decrease",ri=0,Do=1,on=2,ss=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],Eg=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Pl=["Role","JoinTime","MsgFlag","MsgSeq"],fd=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],Lc=0,Rr=1,MI="notStart",ru="resolved",Og="rejected",au=10018,vI=11e3,Uc=2,Wu=["Owner","Admin","Member"],Sm=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],Mm=0,vm=1,Rm=2,uD=4,ED=1,xv=2,dD=3,CD=4,Yv=5,DT=1,yd=0,ST=4,hD=6,MT=400,BD=300,vT={from:!0,groupID:!0,groupName:!0,to:!0},Vv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},RT=2,Jv=4,wT=5,_T=7,QD=8,pD=15,bQ=20,wm=21,_m=2600,Dd=2602,TT=2603,NT=2620,Tm=2621,mD=2623,dh=2660,GT=2661,bT=2681,Nm=2683,Hv=2684,fD=2685,Gm=2687,qv=3122,kT=10018,LT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},Kv=s=>s===Zn.core.OuterConstant.GRP_PUBLIC,Sd=s=>s===Zn.core.OuterConstant.GRP_AVCHATROOM,bm=(s,r)=>{const{isArray:g}=Zn.core.utils;if(!g(s)||!g(r))return!1;let u=!1;return r.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,u=!0):(s.push({key:E,value:m}),u=!0)}),u},Md=s=>{const r=[];if(!s)return r;for(let g=0,u=s.length;g{const r=[];for(let g=0,u=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(r){const{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=r,{common:{deepMerge:T}}=Zn.core;T(this.selfInfo,{nameCard:g,joinTime:u,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M},[],["",null,void 0,0,NaN])}setSelfNameCard(r){this.selfInfo.nameCard=r}}var Ji=new class{constructor(){this._name="GroupDataHandler"}init(s){this._core=s;const{appStore:{groupStore:r}}=s;this._groupMap=r.getGroupMap()}hasLocalGroup(s){return this._groupMap.has(s)}getLocalGroup(s){return this._groupMap.get(s)}updateLocalGroup(s){const{common:{getCurrentUserID:r}}=this._core;let g;s.forEach(E=>{var m;g=E.groupID,this.hasLocalGroup(g)?(m=this.getLocalGroup(g))===null||m===void 0||m.updateGroup(E):(this._groupMap.set(g,new zu(E)),this._clearGroupLocalMessage(g))});const u=r();for(const[,E]of this._groupMap)E.selfInfo.userID=u,E.selfInfo.role==="Owner"&&(E.ownerID=u)}deleteLocalGroup(s){this._groupMap.delete(s)}getLocalGroupList(){const{OuterConstant:{GRP_ROOM:s,GRP_LIVE:r}}=this._core;return[...this._groupMap.values()].filter(g=>{const{type:u}=g;return u!==s&&u!==r})}clearLocalGroup(){this._groupMap.clear()}emitGroupListUpdate(){const s=this.getLocalGroupList(),{OuterEvent:{GROUP_LIST_UPDATED:r},notificationCenter:g}=this._core;g.emitOuterEvent(r,{name:r,data:s})}updateConversationGroupProfile(s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core,u=`${g}${s}`,E=r.getConversation(u);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),r.updateConversation(u,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:r,messageDataHandler:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${u}${s}`;r.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function Lm(s,r){return mA(this,void 0,void 0,function*(){const{type:g,limit:u,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:u,Offset:E,Member_Account:D,ResponseFilter:M,SupportTopic:m,NeedAppDefineData:1};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_joined_group_list",data:T})})}const dn=function(s,r){return{code:0,data:s||{},successLog:r}};var jv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=MI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:r,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u}}=s;r.registerApi({apiName:"getGroupList",context:this}),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,u.GROUP_LIST_SYNC,this._syncGroupList,this)}getGroupList(){return mA(this,arguments,void 0,function*(s=!1){if(s){const g=[];return yield this._pagingGetJoinedCommunityList({limit:this.PAGING_GRP_COUNT_LIMIT,offset:0,groupList:g}),Ji.updateLocalGroup(g),Ji.getLocalGroupList()}if(this._core.ssoLog.debug("getGroupList",`${this._name}.getGroupList pagingStatus:${this._pagingStatus}`),this._pagingStatus===Og||this._pagingStatus===MI)return this._syncGroupList().then(()=>{const g=Ji.getLocalGroupList();return dn({groupList:g,isSyncCompleted:this._isSyncCompleted()})}).catch(g=>{throw g});const r=Ji.getLocalGroupList();return dn({groupList:r,isSyncCompleted:this._isSyncCompleted()},{message:`return group count:${r.length}`})})}_syncGroupList(){return mA(this,void 0,void 0,function*(){this._pagingStatus===MI&&Ji.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,r=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:r}),this._pagingStatus=ru,this._groupListTreeShaking(r),Ji.updateLocalGroup(r);const g=Ji.getLocalGroupList();return this._core.ssoLog.debug("_syncGroupList",`${this._name}._syncGroupList ok, count:${g.length}`),Ji.emitGroupListUpdate(),g}catch(g){throw this._pagingStatus=Og,g}})}_pagingGetGroupList(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{isCommunityRelay:g=!1,groupList:u}=s;let E,{limit:m,offset:D}=s;const M=[...ss];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield Lm({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Pl]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},oA=this._convertGroupKey(P);u.push(...oA);const EA=D+m,wA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${wA} current:${u.length} isCommunityRelay:${g}`;return r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?u:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):wA?(r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:u})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:u}))}catch(T){if(T.ErrorCode===au)return r.warn("_pagingGetGroupList",`${this._name}._pagingGetGroupList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetGroupList({isCommunityRelay:g,limit:m,offset:D,groupList:u});if(g)return T.code===vI&&r.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),u;throw T}})}_pagingGetJoinedCommunityList(s){return mA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:r},OuterConstant:g,ssoLog:u}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield Lm({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:r(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ss],SelfInfoFilter:[...Pl]}},this._core),{GroupIdList:T=[],TotalCount:P=0}=M||{},W=this._convertGroupKey(T);E.push(...W);const oA=D+m,EA=!(P>oA),wA=`offset:${D} limit:${m} total:${P} isCompleted:${EA} current:${E.length}`;return u.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=oA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===kT)return u.warn("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList response size exceeds the limit, request count:${m}`),m=50,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E});throw M}})}_groupListTreeShaking(s){const r=new Map([...Ji.getLocalGroupList()]);for(let u=0,E=s.length;u{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=u;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Zu=new class{constructor(){this._name="CreateGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"createGroup",context:this})}createGroup(s){return mA(this,void 0,void 0,function*(){var r;this._preCheckParams(s);const{helper:{ChatError:g}}=this._core;try{const{utils:{isEmpty:u},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:xA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:qA,joinOption:Ie,inviteOption:le,memberList:bi,groupCustomField:ki,isSupportTopic:Ot}=oA;let Li,cs;bi&&(Li=bi.map(St=>{const{userID:UA,memberCustomField:ai}=St;return{Member_Account:UA,AppMemberDefinedData:ai?YE(ai):void 0}})),ki&&(cs=YE(ki));const Re={Name:wA,Type:kA,GroupId:xA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:qA,ApplyJoinOption:Ie,InviteJoinOption:le,MemberList:Li,AppDefinedData:cs,SupportTopic:Ot,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:Re})})}(Object.assign(Object.assign({},s),{ownerID:E()}),this._core),{GroupId:M,OverJoinedGroupLimit_Account:T=[]}=D||{},P=`${this._name}.createGroup ok, type:${s.type} groupID:${M} overLimitUserIDList:${T}`;if(u(s.memberList)||u(T)||(s.memberList=(r=s.memberList)===null||r===void 0?void 0:r.filter(oA=>T.includes(oA.userID))),s.type===m)return dn({group:new zu(Object.assign(Object.assign({},s),{groupID:M}))},{message:P});Ji.updateLocalGroup([Object.assign(Object.assign({},s),{groupID:M})]);const W=Ji.getLocalGroup(M);return this._notNeedSendCustomMessage(s)||(this._sendCustomMessage(M,s.type),Ji.emitGroupListUpdate()),dn({group:W},{message:P})}catch(u){const{errorCode:E,errorInfo:m}=u;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:r,groupID:g}=s,{utils:{isEmpty:u,isUndefined:E},common:{isCommunity:m}}=this._core,D=!u(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:oA}=Zn.core.OuterConstant;return[M,T,P,W,oA]})().includes(r))throw new this._core.helper.ChatError({code:_m});if(!m({type:r})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});E(s.isSupportTopic)||(s.isSupportTopic=void 0)}if(this._canIUseMemberList(r)||E(s.memberList)||(s.memberList=void 0),this._canIUseJoinOption(r)||E(s.joinOption)||(s.joinOption=void 0),m({type:r})){if(D&&!m({groupID:g}))throw new this._core.helper.ChatError({code:Dd});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Sd(s)}_canIUseJoinOption(s){return Kv(s)||this._core.common.isCommunity({type:s})}_canIUseTopic(s){const{isSupportTopic:r}=s;return r===!0}_notNeedSendCustomMessage(s){const{type:r,isSupportTopic:g}=s,{OuterConstant:{GRP_AVCHATROOM:u,GRP_COMMUNITY:E}}=this._core;return r===u||r===E&&g===1}_sendCustomMessage(s,r){var g,u,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),oA=Lc;r===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),oA=Rr);const EA={to:s,conversationType:"GROUP",payload:{data:JSON.stringify({businessID:"group_create",content:W,cmd:oA,opUser:this._core.store.get("login").userId,version:4})}},wA=(E=(u=(g=this._core)===null||g===void 0?void 0:g.message)===null||u===void 0?void 0:u.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(EA);(M=(D=(m=this._core)===null||m===void 0?void 0:m.message)===null||D===void 0?void 0:D.messageSender)===null||M===void 0||M.sendMessage(wA,{})}},zs=new class{constructor(){this._name="AttributesDataHandler",this._groupAttributesCache=new Map,this._groupAttributesCacheValuesCopy={}}init(s){this._core=s;const{helper:r,constants:g}=s;r.registerWorkflowStep(g.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,g.WORKFLOW_STEP.GROUP_ATTRIBUTE_CACHE_CLEAR,this.clearLocalMainSequence,this)}clearLocalMainSequence(){this._groupAttributesCache.forEach(s=>{s.localMainSequence=0})}isGroupAttributesUpdated(s){const{elements:{newGroupProfile:r}}=s,{utils:{isEmpty:g,isUndefined:u}}=this._core;return!u(r)&&!g(r.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:r,groupAttributeOption:g}=s,{serverMainSequence:u,groupAttributeList:E=[],operation:m}=g;this._core.ssoLog.debug("handleGroupAttributesUpdated",`${this._name}.handleGroupAttributesUpdated groupID:${r} operation:${m}`);const{utils:{isUndefined:D}}=this._core;D(m)||(this.refreshGroupAttributesCache({groupID:r,serverMainSequence:u,groupAttributeList:E,operation:m}),this.emitGroupAttributesUpdated(r))}initGroupAttributesCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupAttributesCache.set(r,{lastUpdateTime:0,localMainSequence:0,serverMainSequence:0,avChatRoomKey:g,values:new Map}),this._core.ssoLog.debug("initGroupAttributesCache",`${this._name}.initGroupAttributesCache. groupID:${r} avChatRoomKey:${g}`)}hasGroupAttributesCache(s){return this._groupAttributesCache.has(s)}getGroupAttributesCache(s){return this.hasGroupAttributesCache(s)||this.initGroupAttributesCache({groupID:s}),this._groupAttributesCache.get(s)}deleteGroupAttributesCache(s){this.hasGroupAttributesCache(s)&&this._groupAttributesCache.delete(s)}refreshGroupAttributesCache(s){const{groupID:r,serverMainSequence:g,groupAttributeList:u,operation:E}=s;if(this.hasGroupAttributesCache(r)){const m=this.getGroupAttributesCache(r),{localMainSequence:D}=m;E!==Yv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:u,operation:E})),g-D>1&&(m.serverMainSequence=g),this._groupAttributesCache.set(r,m),this._core.ssoLog.debug("refreshGroupAttributesCache",`${this._name}.refreshGroupAttributesCache. operation:${E} localMainSequence:${D} serverMainSequence:${g}`)}}_updateGroupAttributesCacheValues(s){const{groupAttributes:r,groupAttributeList:g=[],operation:u}=s;u!==dD?u!==CD?(u===ED&&r.values.clear(),g.forEach(E=>{const{key:m,value:D,sequence:M}=E;r.values.set(m,{value:D,sequence:M})})):g.forEach(E=>{r.values.delete(E.key)}):r.values.clear()}getGroupAttributesCacheValues(s){var r;const{groupID:g,keyList:u=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(u.length===0){for(const D of m.keys())E[D]=((r=m.get(D))===null||r===void 0?void 0:r.value)||"";return E}return u.forEach(D=>{var M;m.has(D)&&(E[D]=((M=m.get(D))===null||M===void 0?void 0:M.value)||"")}),E}return E}saveGroupAttributesCacheValuesCopy(s){this._groupAttributesCacheValuesCopy=this.getGroupAttributesCacheValues({groupID:s})}emitGroupAttributesUpdated(s){var r,g;const{OuterConstant:{GRP_ROOM:u,GRP_LIVE:E}}=this._core,m=this.getGroupAttributesCacheValues({groupID:s}),D=this._core.appStore.groupStore.getGroup(s),{updatedKeyList:M,deletedKeyList:T}=this._computeValuesChangedData(m);M.length===0&&T.length===0||([u,E].includes(D.type)?(this._core.ssoLog.debug("RICH_STATUS_CHANGED",`${this._name}.emitRichStatusChanged update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(r=this._core)===null||r===void 0?void 0:r.OuterEvent.RICH_STATUS_CHANGED,data:{groupID:s,richStatus:m,updatedKeyList:M,deletedKeyList:T}})):(this._core.ssoLog.debug("emitGroupAttributesUpdated",`${this._name}.emitGroupAttributesUpdated update count:${M.length}, delete count:${T.length}`),this._emitEvent({name:(g=this._core)===null||g===void 0?void 0:g.OuterEvent.GROUP_ATTRIBUTES_UPDATED,data:{groupID:s,groupAttributes:m,updatedKeyList:M,deletedKeyList:T}})))}_computeValuesChangedData(s){const{utils:{isUndefined:r}}=this._core,g=[],u=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{r(s[E])&&u.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:u}}_emitEvent(s){var r;(r=this._core)===null||r===void 0||r.notificationCenter.emitOuterEvent(s.name,s)}convertKeyValueMapToList(s){const r=[];return Object.keys(s).forEach(g=>{r.push({key:g,value:s[g]})}),r}reset(){this._groupAttributesCache.clear(),this._groupAttributesCacheValuesCopy={}}},hh=new class{constructor(){this._name="DismissGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.destroy_group",data:m})})}(s,this._core);const{type:g}=Ji.getLocalGroup(s);return Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"dismissGroup",code:u,message:E})}})}},xl=new class{constructor(){this._name="GetGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupProfile",context:this})}getGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupCustomFieldFilter:g}=s,u={groupIDList:[r],responseFilter:{GroupBaseInfoFilter:[...ss],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...fd]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(u),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Ji.hasLocalGroup(r)&&Sd(D[0].type)?T=new zu(D[0]):(Ji.updateLocalGroup(D),T=Ji.getLocalGroup(r)),T.isSupportTopic||Ji.updateConversationGroupProfile(r),dn({group:T},{message:`groupID:${r}`})}catch(m){const{code:D,message:M}=m;throw new E({functionName:"getGroupProfile",code:D,message:M})}})}getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{groupIDList:r}=s,{common:{isCommunity:g}}=this._core,u=r.filter(T=>!g({groupID:T})),E=r.filter(T=>g({groupID:T}));u.length>50&&(u.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:u})),this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:E,isCommunityProfile:!0}))]),D=[],M=[];return m.forEach(T=>{D.push(...T.successGroupList),M.push(...T.failureGroupList)}),{successGroupList:D,failureGroupList:M}})}_getGroupProfileAdvance(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{isUndefined:g}}=this._core,{isCommunityProfile:u=!1}=s,E=So(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,oA){return mA(this,void 0,void 0,function*(){const{groupIDList:EA,responseFilter:wA}=W,kA={GroupIdList:EA,ResponseFilter:wA};return oA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_self_member_info",data:kA})})}(E,this._core),{GroupInfo:D=[]}=m||{},M=this._convertGroupProfileKey(D),T=M.filter(W=>g(W.errorCode)||W.errorCode===0),P=M.filter(W=>W.errorCode&&W.errorCode!==0).map(W=>({code:W.errorCode,message:W.errorInfo,data:{groupID:W.groupID}}));return r.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(u)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const r=[];for(let g=0,u=s.length;g0&&u{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}initGroupCountersCache(s){const{groupID:r,avChatRoomKey:g}=s;this._groupCountersMap.set(r,{lastUpdateTime:0,groupCounterSeq:0,counters:new Map,avChatRoomKey:g})}getLocalCounters(s,r){const g={};if(!this._hasLocalGroupCounters(s))return g;const{counters:u}=this.getLocalGroupCounters(s);if(r.length>0)r.forEach(E=>{u.has(E)&&(g[E]=u.get(E))});else for(const E of u.keys())g[E]=u.get(E);return g}deleteLocalGroupCounters(s){const{groupID:r,counterList:g=[],groupCounterSeq:u}=s;if(this._hasLocalGroupCounters(r)){const{counters:E,avChatRoomKey:m}=this.getLocalGroupCounters(r);g.forEach(D=>{E.delete(D.key)}),this._groupCountersMap.set(r,{lastUpdateTime:Date.now(),groupCounterSeq:u,counters:E,avChatRoomKey:m})}}setGroupCounters(s,r){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:u}=g;let E=!1;Object.entries(r).forEach(([m,D])=>{u.has(m)&&u.get(m)!==D&&(u.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:u}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},VE=new class{constructor(){this._name="JoinGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{helper:{ChatError:g},OuterConstant:u,ssoLog:E}=this._core;try{if(Ji.hasLocalGroup(r))try{return yield xl.getGroupProfile({groupID:r}),dn({status:u.JOIN_STATUS_ALREADY_IN_GROUP,group:Ji.getLocalGroup(r)},{message:`groupID:${r} joinedStatus:${u.JOIN_STATUS_ALREADY_IN_GROUP}`})}catch{return E.warn("joinGroup",`${this._name}.joinGroup ${r} was unjoined, start to join!`),Ji.deleteLocalGroup(r),yield this._applyJoinGroup(s)}return yield this._applyJoinGroup(s)}catch(m){const{errorCode:D,errorInfo:M}=m;throw new g({functionName:"joinGroup",code:D,message:M,moreMessage:`groupID:${r}`})}})}_applyJoinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r,helper:g,ssoLog:u}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(qr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return mA(this,void 0,void 0,function*(){const{groupID:qA,applyMessage:Ie,historyMessageFlag:le}=SA,bi={GroupId:qA,ApplyMsg:Ie,HugeGroupHistoryMsgFlag:le};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:bi})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:oA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=M||{},xA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${oA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;u.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${xA}`);let LA=new zu({groupID:E,type:T});if(P===r.JOIN_STATUS_WAIT_APPROVAL)return dn({status:r.JOIN_STATUS_WAIT_APPROVAL,group:LA});if(P===r.JOIN_STATUS_SUCCESS){try{LA=(yield xl.getGroupProfile({groupID:E})).data.group}catch(SA){u.warn("_applyJoinGroup",`${this._name}._applyJoinGroup getGroupProfile failed, groupID: ${E}, errorCode:${SA?.code}`)}return this._handleJoinResult({group:LA,avChatRoomFlag:EA,longPollingKey:W,startSequence:oA,avChatRoomKey:wA,historyMessageList:kA})}throw new this._core.helper.ChatError({code:dh})})}_handleJoinResult(s){const{group:r,avChatRoomFlag:g,avChatRoomKey:u}=s;return g===1?(zs.initGroupAttributesCache({groupID:r.groupID,avChatRoomKey:u}),nc.initGroupCountersCache({groupID:r.groupID,avChatRoomKey:u}),dn(s)):(Ji.updateLocalGroup([r]),Ji.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:r},{message:`groupID:${r.groupID}`}))}},kQ=new class{constructor(){this._name="QuitGroup"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}quitGroup(s){return mA(this,void 0,void 0,function*(){if(!Ji.hasLocalGroup(s))throw new this._core.helper.ChatError({code:mD});const{helper:{ChatError:r}}=this._core;try{yield function(u,E){return mA(this,void 0,void 0,function*(){const m={GroupId:u};return E.common.buildAndSendPacket({servcmd:"group_open_http_svc.quit_group",data:m})})}(s,this._core);const{type:g}=Ji.getLocalGroup(s);return Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate(),zs.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:u,errorInfo:E}=g;throw new r({functionName:"quitGroup",code:u,message:E,moreMessage:`groupID:${s}`})}})}},uB=new class{constructor(){this._name="SearchGroup"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"searchGroupByID",context:this})}searchGroupByID(s){return mA(this,void 0,void 0,function*(){try{const r=yield function(OA,qA){return mA(this,void 0,void 0,function*(){const Ie={GroupIdList:[OA],GroupBasePublicInfoFilter:[...Eg]};return qA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:Ie})})}(s,this._core),{GroupInfo:g=[]}=r||{},{AppDefinedData:u=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:oA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:xA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:xA});const LA=Md(u),SA=new zu({groupID:s,name:oA,avatar:D,introduction:M,joinOption:E,inviteOption:T,maxMemberCount:P,memberCount:W,type:wA,ownerID:EA,createTime:m,groupCustomField:LA});return dn({group:SA})}catch(r){const{errorCode:g,errorInfo:u}=r;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:u})}})}},UT=new class{constructor(){this._name="UpdateGroupProfile"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"updateGroupProfile",context:this})}updateGroupProfile(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{utils:{isUndefined:g,safeStringify:u},ssoLog:E,helper:m}=this._core;let D=Ji.getLocalGroup(r);if(D){const{type:M}=D;this._canIUseJoinOption(M)||g(s.joinOption)||(E.warn("updateGroupProfile",`${this._name}.updateGroupProfile groupID:${r} joinOption is unavailable for Work/Meeting/AVChatRoom`),s.joinOption=void 0)}g(s.muteAllMembers)||(s.muteAllMembers=s.muteAllMembers===!0?"On":"Off");try{return yield function(M,T){return mA(this,void 0,void 0,function*(){const{groupID:P,name:W,avatar:oA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:xA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:oA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:xA,InviteJoinOption:LA,AppDefinedData:SA?YE(SA):void 0};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_base_info",data:OA})})}(s,this._core),D?(D.updateGroup(s),Ji.emitGroupListUpdate()):D=new zu(s),dn({group:D},{message:`groupID:${r}`})}catch(M){const{errorCode:T,errorInfo:P}=M;throw new m.ChatError({code:T,message:P,moreMessage:`options:${u(s)}`})}})}_canIUseJoinOption(s){return Kv(s)||this._core.common.isCommunity({type:s})}},FT=new class{constructor(){this._name="ChangeGroupOwner"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"changeGroupOwner",context:this})}changeGroupOwner(s){return mA(this,void 0,void 0,function*(){const r="changeGroupOwner",{groupID:g,newOwnerID:u}=s,E=Ji.getLocalGroup(g),{helper:m,OuterConstant:D,common:{getCurrentUserID:M}}=this._core;if(E?.type===D.GRP_AVCHATROOM)throw new m.ChatError({functionName:r,code:NT});if(u===M())throw new m.ChatError({functionName:r,code:Tm});try{return yield function(T,P){return mA(this,void 0,void 0,function*(){const{groupID:W,newOwnerID:oA}=T,EA={GroupId:W,NewOwner_Account:oA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.change_group_owner",data:EA})})}(s,this._core),E.ownerID=u,Ji.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},LQ=new class{constructor(){this._name="GetGroupOnlineMemberCount",this._onlineMemberCountMap=new Map}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="getGroupOnlineMemberCount";if(!Ji.hasLocalGroup(s))return dn({memberCount:0});const g=Date.now();if(this._onlineMemberCountMap.has(s)){const u=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=u||{};if(g-E<=6e4)return dn({memberCount:m})}try{const u=yield function(D,M){return mA(this,void 0,void 0,function*(){const T={GroupId:D};return M.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:T})})}(s,this._core),{OnlineMemberNum:E=0}=u||{};this._onlineMemberCountMap.set(s,{lastReqTime:Date.now(),memberCount:E});const m=`${this._name}.${r} ok. groupID:${s} memberCount:${E}`;return dn({memberCount:E},{message:m})}catch(u){throw new this._core.helper.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo})}})}},UQ=new class{init(s,r){s.ssoLog.debug("GroupAction.init"),jv.init(s),Zu.init(s),hh.init(s,r),VE.init(s,r),kQ.init(s,r),uB.init(s),xl.init(s),UT.init(s),FT.init(s),LQ.init(s,r)}dismissGroup(s){return hh.dismissGroup(s)}joinGroup(s){return VE.joinGroup(s)}quitGroup(s){return kQ.quitGroup(s)}getGroupOnlineMemberCount(s){return LQ.getGroupOnlineMemberCount(s)}},Wv=new class{constructor(){this._name="GetGroupApplicationList"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupApplicationList",context:this})}getGroupApplicationList(){return mA(this,void 0,void 0,function*(){const s="getGroupApplicationList";try{const r=yield Promise.all([this._getGroupApplicationList(),this._getGroupApplicationList({type:this._core.OuterConstant.GRP_COMMUNITY})]);this._core.ssoLog.debug("getGroupApplicationList",`${this._name}.${s} ok.`);const g=this._handleGroupApplicationResult([...r[0],...r[1]]);return dn({applicationList:g})}catch(r){throw new this._core.helper.ChatError({functionName:s,code:r?.errorCode,message:r?.errorInfo})}})}_getGroupApplicationList(s){return mA(this,void 0,void 0,function*(){const{type:r,startTime:g=0,limit:u=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return mA(this,void 0,void 0,function*(){const{type:oA,startTime:EA,limit:wA,handleAccount:kA}=P,xA={Type:oA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:xA})})}({type:r,startTime:g,limit:u,handleAccount:E.getCurrentUserID()},this._core)}catch(P){if(P?.errorCode!==11e3)throw P;m={}}const{NextStartTime:D=0,PendencyList:M=[]}=m||{};if(D===0)return M;const T=yield this._getGroupApplicationList(Object.assign(Object.assign({},s),{startTime:D}));return[...M,...T]})}_handleGroupApplicationResult(s){const r=[];return s.forEach(g=>{const u=this._convertApplicationData(g),{handled:E}=u,m=So(u,["handled"]);E===0&&r.push(m)}),r}_convertApplicationData(s){const{Handled:r,AddTime:g,ApplyInviteMsg:u,Authentication:E,FromUserNickName:m,From_Account:D,GroupId:M,GroupName:T,PendencyType:P,To_Account:W}=s;return{handled:r,messageKey:g,applicant:D,applicantNick:m,groupID:M,groupName:T,authentication:E,applicationType:P,userID:W,note:u,addTime:g}}},zv=new class{constructor(){this._name="HandleGroupApplication"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"handleGroupApplication",context:this})}handleGroupApplication(s){return mA(this,void 0,void 0,function*(){const{application:r}=s,g=this._handleParams(s);try{r?.applicationType===Uc?yield function(E,m){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,invitee:oA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,Invited_Account:oA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_invite_join_permission_group",data:EA})})}(g,this._core):yield function(E,m){return mA(this,void 0,void 0,function*(){const{groupID:D,handleAction:M,handleMessage:T,applicant:P,authentication:W,messageKey:oA}=E,EA={GroupId:D,HandleMsg:M,ApprovalMsg:T,Applicant_Account:P,Authentication:W,MsgKey:oA};return m.common.buildAndSendPacket({servcmd:"group_open_http_svc.handle_apply_join_group",data:EA})})}(g,this._core);const u=Ji.getLocalGroup(g.groupID);return dn({group:u})}catch(u){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:u?.errorCode,message:u?.errorInfo})}})}_handleParams(s){var r;const{handleAction:g,handleMessage:u,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:oA}=E||{};D=oA.operatorID,M=(r=oA.groupProfile)===null||r===void 0?void 0:r.groupID,T=oA.authentication,P=oA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Uc&&(W=m.userID),{handleAction:g,handleMessage:u,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},yD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Wv.init(s),zv.init(s)}};let vC=class{constructor(s){this.userID="",this.avatar="",this.nick="",this.role="",this.joinTime="",this.nameCard="",this.muteUntil=0,this.memberCustomField=[],this.isOnline=!1,this.updateMember(s)}updateMember(s){const{core:{utils:{isUndefined:r},common:{deepMerge:g}}}=Zn;r(s.muteTime)||(this.muteUntil=Math.floor((Date.now()+1e3*s.muteTime)/1e3)),r(s.onlineStatus)||(this.isOnline=s.onlineStatus==="Online");const u=[null,void 0,"",0,NaN];s.memberCustomField&&bm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],u)}};function EB(s,r){return mA(this,void 0,void 0,function*(){const{groupID:g,userID:u,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=YE(M));const P={GroupId:g,Member_Account:u,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return r.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var DD=new class{constructor(){this._name="GetGroupMemberList"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="getGroupMemberList",{groupID:g,offset:u=0,count:E=100,role:m="",filter:D=""}=s,M=Ji.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:u,limit:T,memberRoleFilter:Wu.includes(m)?[m]:void 0,memberInfoFilter:Sm};try{const W=yield function(le,bi){return mA(this,void 0,void 0,function*(){const{isCommunity:ki}=bi.common,{groupID:Ot,offset:Li,limit:cs,memberRoleFilter:Re,memberInfoFilter:St}=le,UA={GroupId:Ot,Limit:cs,MemberRoleFilter:Re,MemberInfoFilter:St};return ki({groupID:Ot})?UA.Next=String(Li):UA.Offset=Li,bi.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_member_info",data:UA})})}(P,this._core),{MemberList:oA,MemberNum:EA,Next:wA}=W||{},kA=`${this._name}.${r} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:xA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!xA(oA)||oA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=u+T;SA({groupID:g})&&(OA=LA(wA)?0:wA),oA.lengthD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${r} userIDList length:${u.length} exceeds limit 50`),u.splice(50));const P=`userIDList length:${u.length} groupID:${g}`;try{const W=yield function(kA,xA){return mA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:qA}=kA,Ie={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:qA};return xA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:Ie})})}({groupID:g,userIDList:u,memberCustomFieldFilter:E,memberInfoFilter:[...Sm]},this._core),{MemberList:oA}=W||{};if(!M(oA)||oA.length===0)return dn({memberList:[]});let EA=this._convertMemberInfo(oA);EA=yield this._getMemberAvatarAndNick(EA);const wA=this._generateGroupMember(EA);return dn({memberList:wA},{message:P})}catch(W){throw new D.ChatError({functionName:r,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const r=[];for(let g=0,u=s.length;gD.userID),u=yield(r=this._core.user.userProfile)===null||r===void 0?void 0:r.getUserProfile({userIDList:g}),E=u?.data||[],m=new Map(E.map(D=>[D.userID,D]));return s.forEach(D=>{if(m.has(D.userID)){const{nick:M="",avatar:T=""}=m.get(D.userID);D.nick=M,D.avatar=T}}),s})}_generateGroupMember(s){const r=[];for(let g=0,u=s.length;g({Member_Account:M}));try{const M=yield function(wA,kA){return mA(this,void 0,void 0,function*(){const{groupID:xA,userIDList:LA}=wA,SA={GroupId:xA,MemberList:LA};return kA.common.buildAndSendPacket({servcmd:"group_open_http_svc.add_group_member",data:SA})})}({groupID:g,userIDList:D},this._core),{MemberList:T=[]}=M||{},{failureUserIDList:P,successUserIDList:W,existedUserIDList:oA,overLimitUserIDList:EA}=this._handleResult(T);return dn({failureUserIDList:P,successUserIDList:W,existedUserIDList:oA,overLimitUserIDList:EA,group:E},{message:` groupID:${g} successUserIDList:${W} failureUserIDList:${P} existedUserIDList:${oA} overLimitUserIDList:${EA}`})}catch(M){throw new m.ChatError({functionName:r,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const r=[],g=[],u=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===Mm?r.push(M):D===vm?g.push(M):D===Rm?u.push(M):D===uD&&E.push(M)}),{failureUserIDList:r,successUserIDList:g,existedUserIDList:u,overLimitUserIDList:E}}},Rd=new class{constructor(){this._name="DeleteGroupMember"}init(s,r){this._core=s;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>!r.getInstalledSubPlugins().includes(ia)})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{groupID:g,userIDList:u}=s,E=Ji.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:r,code:TT});u.length>20&&(M.warn("deleteGroupMember",`${this._name}.${r} userIDList length:${u.length} exceeds limit 20`),u.splice(20));try{return yield function(T,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:oA,reason:EA}=T,wA={GroupId:W,MemberToDel_Account:oA,Reason:EA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_member",data:wA})})}({groupID:g,userIDList:u},this._core),dn({group:E,userIDList:u},{message:`groupID:${g} userIDList length:${u.length}`})}catch(T){throw new m.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},Zv=new class{constructor(){this._name="SetGroupMemberMuteTime"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberMuteTime",context:this})}setGroupMemberMuteTime(s){return mA(this,void 0,void 0,function*(){const{helper:r}=this._core,{groupID:g,userID:u,muteTime:E}=s,m=` groupID:${g} userID:${u} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield EB(s,this._core);const D=Ji.getLocalGroup(g),M=new vC({userID:u,muteTime:E});return dn({group:D,member:M},{message:m})}catch(D){throw new r.ChatError({functionName:"setGroupMemberMuteTime",code:D?.errorCode,message:D?.errorInfo,moreMessage:m})}})}_preCheckSettingMuteParams(s){const{userID:r}=s,{store:g,helper:u}=this._core;if(r===g.get("login").userId)throw new u.ChatError({functionName:"setGroupMemberMuteTime",code:fD})}},OQ=new class{constructor(){this._name="SetGroupMemberRole"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberRole",context:this})}setGroupMemberRole(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberRole",{helper:g}=this._core,{groupID:u,userID:E,role:m}=s,D=`${this._name}.${r} ok, groupID:${u} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield EB(s,this._core);const M=Ji.getLocalGroup(u),T=new vC({userID:E,role:m});return dn({group:M,member:T},{message:D})}catch(M){throw new g.ChatError({functionName:r,code:M?.errorCode,message:M?.errorInfo,moreMessage:D})}})}_preCheckSettingRoleParams(s){var r;const{groupID:g,userID:u,role:E}=s,{store:m,helper:D,OuterConstant:M,common:{isCommunity:T}}=this._core,P=Ji.getLocalGroup(g);if(((r=P?.selfInfo)===null||r===void 0?void 0:r.role)!==M.GRP_MBR_ROLE_OWNER)throw new D.ChatError({functionName:"setGroupMemberRole",code:bT});if(u===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:Hv});const W=[...Wu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Nm})}},SD=new class{constructor(){this._name="SetGroupMemberNameCard"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberNameCard",context:this})}setGroupMemberNameCard(s){return mA(this,void 0,void 0,function*(){var r;const g="setGroupMemberNameCard",{helper:u,common:{getCurrentUserID:E}}=this._core,{groupID:m,userID:D=E(),nameCard:M}=s,T=`${this._name}.${g} ok, groupID:${m} userID:${D} nameCard:${M}`;this._preCheckSettingNameCardParams(s);try{yield EB({groupID:m,userID:D,nameCard:M},this._core);const W=Ji.getLocalGroup(m);D===((r=W?.selfInfo)===null||r===void 0?void 0:r.userID)&&(W.updateSelfInfo({nameCard:M}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m));const oA=new vC({userID:D,nameCard:M});return dn({group:W,member:oA},{message:T})}catch(P){throw new u.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Ji.getLocalGroup(r);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:Gm})}},Um=new class{constructor(){this._name="SetGroupMemberCustomField"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupMemberCustomField",context:this})}setGroupMemberCustomField(s){return mA(this,void 0,void 0,function*(){const r="setGroupMemberCustomField",{helper:g,common:{getCurrentUserID:u}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=u(),memberCustomField:D}=s,M=`${this._name}.${r} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield EB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Ji.getLocalGroup(E),W=new vC({userID:m,memberCustomField:D});return dn({group:P,member:W},{message:M})}catch(T){throw new g.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo,moreMessage:M})}})}_preCheckSettingCustomFiledParams(s){const{groupID:r}=s,{helper:g}=this._core,u=Ji.getLocalGroup(r);if(Sd(u?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:Gm})}},Xv=new class{init(s,r){s.ssoLog.debug("GroupMember.init"),DD.init(s,r),FQ.init(s),vd.init(s),Rd.init(s,r),Zv.init(s),OQ.init(s),SD.init(s),Um.init(s)}getGroupMemberList(s){return DD.getGroupMemberList(s)}deleteGroupMember(s){return Rd.deleteGroupMember(s)}},OT=new class{init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupCounters",context:this})}getGroupCounters(s){return mA(this,void 0,void 0,function*(){const r="getGroupCounters";try{km(r,sc);const{groupID:g,keyList:u=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=nc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:nc.getLocalCounters(g,u)}};const D=yield function(P){return mA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:oA,avChatRoomKey:EA}=P,{common:wA}=Zn.core,kA={GroupId:W,keyList:oA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:u,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return nc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:nc.getLocalCounters(g,u)}}}catch(g){MC(r,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:r}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:u}=g;return r(u)?3e4:Number(u)}},Fm=new class{init(s){const{helper:r}=s;r.registerApi({apiName:"setGroupCounters",context:this}),r.registerApi({apiName:"increaseGroupCounter",context:this}),r.registerApi({apiName:"decreaseGroupCounter",context:this})}setGroupCounters(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(ju,s)})}increaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(Dm,s)})}decreaseGroupCounter(s){return mA(this,void 0,void 0,function*(){return this._handleCounterOperation(_i,s)})}_handleCounterOperation(s,r){return mA(this,void 0,void 0,function*(){const g=`${s}GroupCounter`;try{km(g,sc);const{groupID:u,key:E,value:m=0}=r,{avChatRoomKey:D}=nc.getLocalGroupCounters(u),M=s===ju?this._convertObjectToList(r.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:u,counterList:M,avChatRoomKey:D,mode:s});return nc.setGroupCounters(u,T),{code:0,data:{counters:T}}}catch(u){MC(g,u)}})}_updateGroupCounters(s){return mA(this,void 0,void 0,function*(){const r=yield function(E){const{groupID:m,counterList:D,mode:M,avChatRoomKey:T}=E,{common:P}=Zn.core,W={GroupId:m,GroupCounter:D,Mode:M,BytesKey:T};return P.buildAndSendPacket({servcmd:"group_open_http_svc.update_group_counter",data:W})}(s),{GroupCounter:g=[]}=r,u={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;u[m]=D}),u})}_convertObjectToList(s){return Object.entries(s).map(([r,g])=>({Key:r,Value:g||0}))}},dB=new class{init(s){this._core=s,OT.init(s),Fm.init(s)}isGroupCounterUpdated(s){const{elements:{groupCounterInfo:r}}=s,{utils:{isEmpty:g}}=this._core;return!g(r)}handleGroupCounterUpdated(s){const{to:r,elements:{groupCounterInfo:g}}=s;g.forEach(u=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=u;E!==ri&&E!==on||this._processAndNotifyCounterUpdate(r,m,D),E===Do&&nc.deleteLocalGroupCounters({groupID:r,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,r,g){const{OuterEvent:u,notificationCenter:E}=this._core;nc.updateLocalGroupCounters({groupID:s,groupCounterSeq:r,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(u.GROUP_COUNTER_UPDATED,{name:u.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){nc.reset()}},Om=new class{constructor(){this._name="InitGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"initGroupAttributes",context:this})}initGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g}=s,{serverMainSequence:u,avChatRoomKey:E}=zs.getGroupAttributesCache(r),m=zs.convertKeyValueMapToList(g);try{const D=yield function(W,oA){return mA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:xA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:xA,AttrControl:["RaceConflict"]};return oA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:r,avChatRoomKey:E,groupAttributeList:m,mainSequence:u},this._core),{AttrMainSeq:M,GroupAttr:T}=D||{},P=T.map(W=>{const{Key:oA,seq:EA}=W;return{key:oA,value:g[oA],sequence:EA}});return zs.saveGroupAttributesCacheValuesCopy(r),zs.refreshGroupAttributesCache({groupID:r,serverMainSequence:M,groupAttributeList:P,operation:ED}),zs.emitGroupAttributesUpdated(r),dn({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${M}`})}catch(D){throw new this._core.helper.ChatError({functionName:"initGroupAttributes",code:D?.errorCode,message:D?.errorInfo})}})}},PT=new class{constructor(){this._name="SetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"setGroupAttributes",context:this}),r.registerExperimentalAPI("setRichStatus",this)}setGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r,groupAttributes:g,richStatusMode:u}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=zs.getGroupAttributesCache(r),M=zs.convertKeyValueMapToList(g).map(T=>{var P;const{key:W,value:oA}=T;return{key:W,value:oA,seq:((P=D.get(T.key))===null||P===void 0?void 0:P.sequence)||0}});try{const T=yield function(EA,wA){return mA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:xA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,qA={GroupId:kA,AttrMainSeq:xA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:qA})})}({groupID:r,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:u},this._core),{AttrMainSeq:P,GroupAttr:W}=T||{},oA=W.map(EA=>{const{Key:wA,seq:kA}=EA;return{key:wA,value:g[wA],sequence:kA}});return zs.saveGroupAttributesCacheValuesCopy(r),zs.refreshGroupAttributesCache({groupID:r,serverMainSequence:P,groupAttributeList:oA,operation:xv}),zs.emitGroupAttributesUpdated(r),dn({groupAttributes:g},{message:` groupID:${r} serverMainSequence:${P}`})}catch(T){throw new this._core.helper.ChatError({functionName:"setGroupAttributes",code:T?.errorCode,message:T?.errorInfo})}})}setRichStatus(s){return mA(this,void 0,void 0,function*(){const{groupID:r,richStatus:g}=s;return this.setGroupAttributes({groupID:r,groupAttributes:g,richStatusMode:!0})})}},MD=new class{constructor(){this._name="DeleteGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"deleteGroupAttributes",context:this}),r.registerExperimentalAPI("deleteRichStatus",this)}deleteGroupAttributes(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupAttributes",{groupID:g,keyList:u=[],richStatusMode:E}=s;try{let m;m=u.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:u,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${r} ok. groupID:${g} operation: ${T}`;return zs.saveGroupAttributesCacheValuesCopy(g),zs.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),zs.emitGroupAttributesUpdated(g),dn({keyList:D},{message:W})}catch(m){throw new this._core.helper.ChatError({functionName:r,code:m?.errorCode,message:m?.errorInfo})}})}deleteRichStatus(s){return mA(this,void 0,void 0,function*(){return this.deleteGroupAttributes(Object.assign(Object.assign({},s),{richStatusMode:!0}))})}_deleteGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=r,M=[],T=[];m.forEach(oA=>{if(E.has(oA)){const{sequence:EA=0}=E.get(oA)||{};T.push({key:oA,seq:EA}),M.push(oA)}});const P=yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:xA,avChatRoomKey:LA,richStatusMode:SA}=oA,OA={GroupId:wA,AttrMainSeq:kA,GroupAttr:xA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:u,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:CD}})}_clearGroupAttributes(s,r){return mA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:u,values:E}=zs.getGroupAttributesCache(s),{richStatusMode:m}=r||{},D=[...E.keys()],M=yield function(P,W){return mA(this,void 0,void 0,function*(){const{groupID:oA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,xA={GroupId:oA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:xA})})}({groupID:s,avChatRoomKey:u,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:dD}})}},vD=new class{constructor(){this._name="GetGroupAttributes"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"getGroupAttributes",context:this}),r.registerExperimentalAPI("getRichStatus",this,"getGroupAttributes")}getGroupAttributes(s){return mA(this,void 0,void 0,function*(){const{groupID:r}=s,{avChatRoomKey:g,lastUpdateTime:u,localMainSequence:E,serverMainSequence:m}=zs.getGroupAttributesCache(r),{helper:{ChatError:D}}=this._core,M=`groupID:${r} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-u>=3e4||E{const{key:oA,value:EA,seq:wA}=W;return{key:oA,value:EA,sequence:wA}});return zs.refreshGroupAttributesCache({groupID:u,serverMainSequence:M,groupAttributeList:P,operation:Yv}),{serverGroupAttributeList:T}})}},PQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Om.init(s),PT.init(s),MD.init(s),vD.init(s),zs.init(s)}isGroupAttributesUpdated(s){return zs.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:r,elements:{newGroupProfile:g}}=s,{groupAttributeOption:u}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=u,{localMainSequence:D}=zs.getGroupAttributesCache(r),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${r} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(zs.saveGroupAttributesCacheValuesCopy(r),m!==1||M!==1){if(zs.hasGroupAttributesCache(r)){const{avChatRoomKey:T}=zs.getGroupAttributesCache(r);vD.getGroupAttributesFromServer({groupID:r,avChatRoomKey:T}).then(()=>{zs.emitGroupAttributesUpdated(r)}).catch(()=>{})}}else zs.handleGroupAttributesUpdated({groupID:r,groupAttributeOption:u})}reset(){zs.reset()}};function JE(s,r="tips"){const{ClientSeq:g,From_Account:u,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:oA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:xA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:qA,From_Account:Ie,To_Account:le}=kA;return{groupCode:xA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:qA,from:Ie,to:le}}(oA);return{clientSequence:g,from:u,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:wA,elements:r==="tips"?Xu(EA):Bh(EA)}}function Xu(s){const r={};return Object.keys(s).forEach(g=>{var u,E;switch(g){case"MemberNum":r.memberCount=s[g];break;case"OpType":r.operationType=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"List_Account":r.userIDList=s[g];break;case"MsgMemberExtraInfo":r.memberInfoList=(u=s[g])===null||u===void 0?void 0:u.map(m=>RD(m));break;case"MsgOperatorMemberExtraInfo":r.operatorInfo=RD(s[g]);break;case"MsgGroupNewInfo":r.newGroupProfile=function(m){const D={};return Object.keys(m).forEach(M=>{switch(M){case"GroupIntroduction":D.introduction=m[M];break;case"GroupName":D.groupName=m[M];break;case"GroupFaceUrl":D.avatar=m[M];break;case"GroupNotification":D.notification=m[M];break;case"ApplyJoinOption":D.joinOption=m[M];break;case"InviteJoinOption":D.inviteOption=m[M];break;case"ShutupAll":D.muteAllMembers=m[M];break;case"Owner_Account":D.ownerID=m[M];break;case"GroupAttrOption":D.groupAttributeOption=function(P){const{BytesChangedKeys:W,GroupAttrSeq:oA,OpType:EA,PushChangedAttrValFlag:wA,GroupAttrInfo:kA}=P,xA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:qA}=LA;return{key:SA,value:OA,sequence:qA}});return{changedKeyList:W,groupAttributeList:xA,serverMainSequence:oA,operation:EA,withChangedAttributeInfo:wA}}(m[M]);break;case"MsgAppDefinedData":D.groupCustomField=(T=m[M])==null?void 0:T.map(P=>({key:P.Key,value:P.Value}));break;case"InviteOption":D.inviteOption=LT[m[M]]||m[M]}var T}),D}(s[g]);break;case"MsgMemberInfo":r.msgMemberInfo=(E=s[g])===null||E===void 0?void 0:E.map(m=>function(D){const{ShutupTime:M,User_Account:T}=D;return{muteTime:M,userID:T}}(m));break;case"OnlineMemberInfo":r.onlineMemberInfo=function(m){const{ExpireTime:D,OnlineMemberNum:M}=m;return{expireTime:D,onlineMemberNum:M}}(s[g]);break;case"GroupCounterInfo":r.groupCounterInfo=function(m){return m.map(D=>{const{GroupCounterSeq:M,GroupCounter:T,Type:P}=D;return{type:P,groupCounterSeq:M,counterList:T}})}(s[g])}}),r}function RD(s){const{ImageUrl:r,NickName:g,Role:u,UserId:E}=s;return{avatar:r,nick:g,role:u,userID:E}}function Bh(s){const r={};return Object.keys(s).forEach(g=>{switch(g){case"MsgKey":r.messageKey=s[g];break;case"Operator_Account":r.operatorID=s[g];break;case"ReportType":r.operationType=s[g];break;case"Authentication":r.authentication=s[g];break;case"MsgFlag":r.messageRemindType=s[g];break;case"UserDefinedField":r.userDefinedField=s[g];break;case"RemarkInfo":r.remarkInfo=s[g];break;case"BanDuration":r.duration=s[g];break;case"MuteTime":r.muteTime=s[g];break;case"MsgMemberExtraInfoList":r.inviteeInfoList=(u=s[g]||[])==null?void 0:u.map(E=>{const{UserId:m,ImageUrl:D,NickName:M}=E;return{userID:m,avatar:D,nick:M}});break;case"MemberList_Account":r.inviteeList=s[g]}var u}),r}class Pm{constructor(r){this.type=Zn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Xu(r);return new Pm(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"groupProfile":this._initGroupProfile(r[g]);break;case"operatorInfo":this._initOperatorInfo(r[g]);break;case"memberInfoList":case"msgMemberInfo":this._updateMemberList(r[g]);break;case"newGroupProfile":this._initNewGroupProfile(r[g]);break;case"memberExtraInfo":case"remarkInfo":case"onlineMemberInfo":break;default:this.content[g]=r[g]}}),this.content.userIDList||(this.content.userIDList=[this.content.operatorID])}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u{r.forEach(u=>{g.userID===u.userID&&Object.assign(g,u)})}):this.content.memberList=r}_initNewGroupProfile(r){this.content.newGroupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:u,messageList:g}}_emitGroupTipsEvent(s){var r;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:u=[]}=((r=s?.result)===null||r===void 0?void 0:r[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(u.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:u})}}_handleGroupTips(s,r=!0){const{Event:g,GroupTips:u}=s,E=new Map,m=[],D=[];for(let M=0,T=u.length;M{const{operationType:u}=g.payload;switch(u){case r.JOINED:this._handleNewMemberJoined(g);break;case r.QUITTED:this._handleMemberQuitted(g);break;case r.KICKED:this._handleMemberKicked(g);break;case r.GROUP_PROFILE_UPDATED:this._handleGroupProfileUpdated(g);break;case r.ADMIN_SET:this._handleMemberGrantAdmin(g);break;case r.ADMIN_CANCELED:this._handleMemberRevokeAdmin(g)}})}_handleNewMemberJoined(s){this._handleGroupMemberCountUpdated(s)}_handleMemberQuitted(s){this._handleGroupMemberCountUpdated(s)}_handleMemberKicked(s){this._handleGroupMemberCountUpdated(s)}_handleGroupProfileUpdated(s){var r;const{newGroupProfile:g,groupProfile:u,operatorInfo:E}=s.payload,{groupID:m}=u,D=Ji.getLocalGroup(m);Object.keys(g).forEach(T=>{switch(T){case"ownerID":this._handleGroupOwnerChanged(m,g);break;case"groupName":D.name=g[T];break;case"groupCustomField":Array.isArray(D[T])&&Array.isArray(g[T])?bm(D[T],g[T]):D[T]=g[T];break;default:D[T]=g[T]}});const{utils:{isUndefined:M}}=this._core;M(E)||((r=D?.selfInfo)===null||r===void 0?void 0:r.userID)!==E.userID||Object.keys(E).forEach(T=>{T==="nameCard"&&D.updateSelfInfo({nameCard:E[T]}),T==="role"&&this._updateSelfRole(D,E[T])}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m)}_handleGroupOwnerChanged(s,r){const{common:g,OuterConstant:u}=this._core,E=Ji.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=r;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:u.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,r){const{OuterConstant:g}=this._core;let u=g.GRP_MBR_ROLE_MEMBER;r===MT?u=g.GRP_MBR_ROLE_OWNER:r===BD&&(u=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:u})}_handleGroupMemberCountUpdated(s){const{memberCount:r,groupProfile:{groupID:g}}=s.payload,u=Ji.getLocalGroup(g),{utils:{isNumber:E}}=this._core;u&&E(r)&&u.memberCount!==r&&(u.memberCount=r,Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:r}}=this._core,{groupTipList:g}=s?.result||{};r(g)&&g.forEach(u=>{const{messageList:E}=this._handleGroupTips({Event:u.Event,GroupTips:[u]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Ji.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_ADMIN}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m))}_handleMemberRevokeAdmin(s){const{OuterConstant:r}=this._core,{groupProfile:g,userIDList:u}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Ji.getLocalGroup(m);D&&u.includes(E)&&(D.updateSelfInfo({role:r.GRP_MBR_ROLE_MEMBER}),Ji.emitGroupListUpdate(),Ji.updateConversationGroupProfile(m))}};class xQ{constructor(r){this.type=Zn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(r)}static parseServerPushElement(r){const g=Bh(r);return new xQ(g)}_initContent(r){Object.keys(r).forEach(g=>{switch(g){case"remarkInfo":this.content.handleMessage=r[g];break;case"groupProfile":this._initGroupProfile(r[g]);break;case"memberInfoList":break;default:this.content[g]=r[g]}})}_initGroupProfile(r){this.content.groupProfile={};const g=Object.keys(r);for(let u=0;u0&&this._handleGroupSysTemMessage(g,E),g===!0&&E.length>0&&m.emitOuterEvent(D.MESSAGE_RECEIVED,{name:D.MESSAGE_RECEIVED,data:E})}_handleGroupSystemNotification(s,r){const g=[];let u={};for(let E=0;E0?[u]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:r},OuterConstant:g,utils:{randomInt:u}}=this._core;s.flow="in",s.conversationType=g.CONV_SYSTEM,s.conversationSubType=s.groupProfile.type,s.conversationID=g.CONV_SYSTEM;const E=r.createMessage(s),m=new xQ(Object.assign(Object.assign({},s.elements),{groupProfile:Object.assign({},s.groupProfile)}));E.setElement(m),E.isSystemMessage=!0;const D=E.sequence===1&&E.random===1,M=E.sequence===2&&E.random===2;return(D||M)&&(E.sequence=u(),E.random=u(),E.generateMessageID()),E}_handleConversationOptions(s,r){const{OuterConstant:g}=this._core,u={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return r&&u.unreadCount++,u}_handleGroupSysTemMessage(s,r){s&&r.forEach(g=>{const{operationType:u}=g.payload;switch(u){case RT:this._handleGroupJoinResult(g);break;case Jv:this._handleMemberKicked(g);break;case wT:this._handleGroupDismissed(g);break;case _T:this._handleGroupInvitedResult(g);break;case QD:this._handleGroupQuitResult(g);break;case bQ:this._handleMessageRemindTypeSynced(g);break;case wm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:r}=s.payload,{groupID:g,type:u}=r,E=Ji.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${u} hasLocalGroup:${E}`),E||Sd(u)||(Ji.updateLocalGroup([Object.assign({},r)]),Ji.emitGroupListUpdate())}_handleMemberKicked(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Ji.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupDismissed(s){const{groupProfile:{groupID:r,type:g}}=s.payload;Ji.hasLocalGroup(r)&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleGroupInvitedResult(s){const{groupProfile:r}=s.payload,{groupID:g}=r,u=Ji.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${u}`),u||xl.getGroupProfile({groupID:g}).then(E=>{const{data:{group:m}}=E;Ji.updateLocalGroup([Object.assign({},m)]),Ji.emitGroupListUpdate()})}_handleGroupQuitResult(s){const{groupProfile:{groupID:r,type:g}}=s.payload,u=Ji.hasLocalGroup(r);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${r} type:${g} hasLocalGroup:${u}`),u&&this._deleteLocalGroup(r,g),this._updateConversationProfile(r,{unreadCount:0})}_handleMessageRemindTypeSynced(s){const{groupProfile:{groupID:r},messageRemindType:g}=s.payload;this._updateConversationProfile(r,{messageRemindType:g})}_handleAVChatRoomMemberBanned(s){const{groupProfile:{groupID:r,type:g}}=s.payload;this._deleteLocalGroup(r,g)}_deleteLocalGroup(s,r){if(Sd(r)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core;g.deleteConversation(`${u}${s}`)}Ji.deleteLocalGroup(s),Ji.emitGroupListUpdate()}_updateConversationProfile(s,r){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:u}}=this._core,E=`${u}${s}`;g.getConversation(E)&&g.updateConversation(E,r)}},wD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),$v.init(s),AR.init(s);const{notificationCenter:r,InnerEvent:g}=s,{InnerEventSubType:u}=r;r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),r.subscribeInnerEvent(g.MESSAGE_PUSH,u.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this),r.subscribeInnerEvent(g.DESTROY,this._dispose,this)}_onNewGroupTipsNotification(s){const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g}}=this._core;r.executeWorkflow(g.RECEIVE_GROUP_TIPS_NOTIFICATION,s)}_onNewGroupSystemNotification(s){AR.onNewGroupSystemNotification(s)}_dispose(){const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onNewGroupSystemNotification,this)}};const vn={required:!0,rules:["string"],allowEmpty:!1},YQ={required:!0,rules:["number"],allowEmpty:!1},wd={required:!0,rules:["array"],allowEmpty:!1},_D={required:!0,rules:["object"],allowEmpty:!1},xT={createGroup:{name:vn,type:vn},dismissGroup:[Object.assign({key:"groupID"},vn)],joinGroup:{groupID:vn,applyMessage:{required:!1,rules:["string"],allowEmpty:!0}},quitGroup:[Object.assign({key:"groupID"},vn)],searchGroupByID:[Object.assign({key:"groupID"},vn)],getGroupProfile:{groupID:vn,groupCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},updateGroupProfile:{groupID:vn,muteAllMembers:{required:!1,rules:["boolean"],allowEmpty:!1}},changeGroupOwner:{groupID:vn,newOwnerID:vn},getGroupOnlineMemberCount:[Object.assign({key:"groupID"},vn)],handleGroupApplication:{handleAction:vn},getGroupMemberList:{groupID:vn},getGroupMemberProfile:{groupID:vn,userIDList:wd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:wd},deleteGroupMember:{groupID:vn,userIDList:wd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},YQ),{customValidator:s=>!(s<0)||"muteTime must be a non-negative number."})},setGroupMemberRole:{groupID:vn,userID:vn,role:vn},setGroupMemberNameCard:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},nameCard:vn},setGroupMemberCustomField:{groupID:vn,userID:{required:!1,rules:["string"],allowEmpty:!1},memberCustomField:wd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},YQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:wd},initGroupAttributes:{groupID:vn,groupAttributes:_D},setGroupAttributes:{groupID:vn,groupAttributes:_D},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},wd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:_D},increaseGroupCounter:{groupID:vn,key:vn,value:YQ},decreaseGroupCounter:{groupID:vn,key:vn,value:YQ}},YT={getGroupList:!0,createGroup:!0,dismissGroup:!0,joinGroup:!0,quitGroup:!0,searchGroupByID:!0,getGroupProfile:!0,updateGroupProfile:!0,changeGroupOwner:!0,getGroupOnlineMemberCount:!0,getGroupApplicationList:!0,handleGroupApplication:!0,getGroupMemberList:!0,getGroupMemberProfile:!0,addGroupMember:!0,deleteGroupMember:!0,setGroupMemberMuteTime:!0,setGroupMemberRole:!0,setGroupMemberNameCard:!0,setGroupMemberCustomField:!0,markGroupMemberList:!0,initGroupAttributes:!0,setGroupAttributes:!0,getGroupAttributes:!0,deleteGroupAttributes:!0,getGroupCounters:!0,setGroupCounters:!0,increaseGroupCounter:!0,decreaseGroupCounter:!0};var VT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Ji,this.groupAction=UQ,this.groupAttribute=PQ,this.groupMember=Xv,this.groupCounter=dB,this.name="Group"}install(s,r=[]){this._core=s,Zn.init(s),Ji.init(s),UQ.init(s,this),Xv.init(s,this),yD.init(s),dB.init(s),PQ.init(s),wD.init(s),s.helper.registerValidateConfig({auth:YT,params:xT}),this._installSubPlugins(r);const{notificationCenter:g,InnerEvent:u}=s;g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:r}}=this._core;s&&r(s)&&s.forEach(g=>{var u;this._installedSubPlugins.includes(g.name)||((u=g.install)===null||u===void 0||u.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Ji.reset(),PQ.reset(),dB.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const CB=new class{init(s){this.core=s}},eR="AV_MBR_LIST",JT="AV_BAN_MBR",HE={NORMAL_MESSAGE:3,GROUP_TIPS_HAS_ROAMING:4,GROUP_SYSTEM_MESSAGE:5,GROUP_TIPS_HAS_NO_ROAMING:6,BROADCAST_MESSAGE:17,MESSAGE_REVOKED:20,MESSAGE_REACTION:21,LIVE_CUSTOM_DATA:100},Qh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},TD=60,ND=2603,HT=2686,qT=2688,VQ=3122;class tR{constructor(r){const{core:g,manager:u,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=r;this._name="Polling",this._core=g,this._manager=u,this._timeoutID=-1,this._isRunning=!1,this._groupID=E,this._getRequestParams=m,this._onSuccess=D,this._onFail=M}start(){this._isRunning=!0,this._request(),console.log(`${this._name}.start pollingInterval:${this._manager.getCurrentPollingInterval(this._groupID)}`)}isRunning(){return this._isRunning}_request(){return mA(this,void 0,void 0,function*(){try{const r=this._getRequestParams(this._groupID),g=yield function(E,m){return mA(this,void 0,void 0,function*(){const{longPollingKey:D,startSequence:M,startBroadcastSeq:T,simplifiedMessage:P}=E,W={Key:D,StartSeq:M,StartBroadcastSeq:T,DownsizeFlag:P,USP:1,HoldTime:90};return m.common.buildAndSendPacket({servcmd:"group_open_long_polling_http_svc.get_msg",data:W})})}(r,this._core);this._onSuccess(this._groupID,g);const u=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(u)}catch(r){this._onFail(this._groupID,r),this._runNextPolling(2e3)}})}_runNextPolling(r){this.isRunning()&&(this._timeoutID>-1&&clearTimeout(this._timeoutID),this._timeoutID=setTimeout(this._request.bind(this),r))}stop(){console.log(`${this._name}.stop timerID:${this._timeoutID}`),this._timeoutID>-1&&(clearTimeout(this._timeoutID),this._timeoutID=-1),this._isRunning=!1}}class ph{constructor(r){this._maxLength=r,this._map=new Map}set(r){var g;if(this._map.size>=this._maxLength){const u=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(u)}this._map.set(r,1)}has(r){return this._map.has(r)}delete(r){this.has(r)&&this._map.delete(r)}clear(){this._map.clear()}}const $u=s=>s===HE.GROUP_TIPS_HAS_NO_ROAMING||s===HE.GROUP_TIPS_HAS_ROAMING,JQ=s=>s===HE.GROUP_SYSTEM_MESSAGE;function xm(s){const r=function(g){const{E:u,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:oA,IsSys:EA,GInf:wA,MsgBody:kA}=g,xA=So(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:u,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:oA,IsSystemMsg:EA,GroupInfo:GD(wA),MsgBody:KT(kA)},xA)}(s);return function(g){const{Event:u}=g;($u(u)||JQ(u))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=u,(E===HE.BROADCAST_MESSAGE||(m=>m===HE.NORMAL_MESSAGE)(u))&&function(m){const{core:{OuterConstant:D}}=CB;m.CloudCustomData=m.CloudCustomData||"",m.MsgBody=m.MsgBody.map(M=>{if(M.MsgType===D.MSG_CUSTOM){const{content:T={}}=M;M.content=Object.assign({Data:"",Desc:"",Ext:""},T)}return M})}(g);var E;$u(u)&&function(m){const{GroupJoinType:D,MsgOperatorMemberExtraInfo:M={},MsgMemberExtraInfo:T,Operator_Account:P,List_Account:W,OpType:oA}=m.MsgBody||{};typeof D=="number"||oA!==1&&oA!==2||(m.MsgBody.GroupJoinType=oA===2?0:1),T||(m.MsgBody.MsgMemberExtraInfo=W?.map(EA=>({UserId:EA}))),oA!==1||T||(m.MsgBody.MsgMemberExtraInfo=[{UserId:M.UserId}]),m.MsgBody.MsgOperatorMemberExtraInfo=Object.assign({Operator_Account:P,ImageUrl:"",NickName:""},M)}(g),JQ(u)&&function(m){const{MsgOperatorMemberExtraInfo:D={},Operator_Account:M}=m.MsgBody||{};m.MsgBody.MsgMemberExtraInfo=Object.assign({UserId:M,ImageUrl:"",NickName:""},D),m.MsgBody=Object.assign({Authentication:"",RemarkInfo:"",MsgKey:1e3*m.MsgTimeStamp},m.MsgBody),m.MsgBody=Object.keys(m.MsgBody).filter(T=>T!=="MsgOperatorMemberExtraInfo").reduce((T,P)=>Object.assign(Object.assign({},T),{[P]:m.MsgBody[P]}),{})}(g)}(r),r}function GD(s){const r=s||{},{GN:g,GT:u,F_Hd:E,F_NN:m,F_Ll:D}=r,M=So(r,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:u},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function KT(s){let r=s;Array.isArray(s)||(r=[s]);const g=r.map(u=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:oA}=u,EA=So(u,["O_Account","Opt","L_Account","RT","UDF","OpInf","OnlineInf","MsgMemberExtraInfo"]),wA=Object.assign({Operator_Account:E,OpType:m,List_Account:D,ReportType:M,UserDefinedField:T},EA);return P&&(wA.MsgOperatorMemberExtraInfo=function(kA){const{Img:xA,NN:LA}=kA,SA=So(kA,["Img","NN"]);return Object.assign({ImageUrl:xA,NickName:LA},SA)}(P)),oA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(xA=>{const{Img:LA,NN:SA}=xA,OA=So(xA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(oA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:xA,Num:LA}=kA;return{ExpireTime:xA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var mh=new class{constructor(){this._name="MessageParser",this._sequenceList=new ph(200),this._messageIDList=new ph(100),this._broadcastMessageIDMap=new Map,this._reportMessageStackedCount=0}init(s,r){this._core=s,this._avChatRoomHandler=r}onMessageReceived(s,r,g=!1){this._sortServerMessageList({groupID:s,serverMessageList:r,isHistoryMessage:g});const u=this._handleMessageList(s,r);if(u.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,oA=W(u[u.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:oA})}this._checkMessageStacked(u);const E=u.filter(T=>T.isModified===!0),m=u.filter(T=>T.isModified===!1),{OuterEvent:{MESSAGE_RECEIVED:D,MESSAGE_MODIFIED:M}}=this._core;E.length>0&&this._emitEvent({name:M,data:E}),m.length>0&&this._emitEvent({name:D,data:m})}_sortServerMessageList(s){const{groupID:r,serverMessageList:g,isHistoryMessage:u}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!u?(g.sort((m,D)=>m.MS-D.MS),E=g.map(m=>m.MS)):(g.sort((m,D)=>m.MsgSeq-D.MsgSeq),E=g.map(m=>m.MsgSeq)),console.log(`${this._name}._sortServerMessageList groupID:${r} count:${E.length} sequenceList:${E}`),E.length=0}_handleMessageList(s,r){var g;const{message:{messageDataHandler:u,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=r.length;for(let T=0;Tg===HE.MESSAGE_REVOKED)(r)?(this._handleMessageRevoked(s),null):(g=>g===HE.LIVE_CUSTOM_DATA)(r)?(this._onLiveCustomData(s),null):(g=>g===HE.MESSAGE_REACTION)(r)?null:s:(console.warn(`${this._name}.onMessageReceived unknown event:${r}`),null)}_createMessage(s){const{message:{messageFactory:r},OuterConstant:g}=this._core;let u=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(u=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=r.createMessage(Object.assign(Object.assign({},s),{conversationType:u,isSystemMessage:E,flow:"in"}));return m.setElement(s.elements),m}_filterDuplicateMessage(s){const{common:r}=this._core;if(!r.isUnlimitedAVChatRoom()){if(this._sequenceList.has(s.sequence))return null;this._sequenceList.set(s.sequence)}const g=this._messageIDList.has(s.ID);return g?(console.warn(`${this._name}_filterDuplicateMessageItem ID:${s.ID} has:${g}`),null):(this._messageIDList.set(s.ID),s)}_handleMessageRevoked(s){const{OuterConstant:r,OuterEvent:{MESSAGE_REVOKED:g}}=this._core,{ToGroupId:u,MsgBody:{RevokeMsgList:E},RevokerInfo:{Revoker_Account:m,Reason:D=""}}=s,M=[];E.forEach(T=>{const{TinyId:P,MsgClientTime:W,Random:oA,MsgSeq:EA}=T,wA={conversationID:`${r.CONV_GROUP}${u}`,ID:`${P}-${W}-${oA}`,revoker:m,revokeReason:D,revokerInfo:{userID:m,nick:"",avatar:""},sequence:EA};M.push(wA)}),M.length!==0&&this._emitEvent({name:g,data:M})}_onLiveCustomData(s){const{OuterEvent:{ROOM_CUSTOM_DATA_RECEIVED:r}}=this._core,{ToGroupId:g,MsgSeq:u,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:r,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${u} time:${E} data:${D}`)}_onGroupDismissed(s){this._avChatRoomHandler.reset(s)}_checkMessageStacked(s){const{length:r}=s;if(r>=100&&this._reportMessageStackedCount<5){const g=this._avChatRoomHandler.getJoinedGroups();this._core.ssoLog.info("MessageStacked",`count:${r} groupID:${g.join(",")}`),this._reportMessageStackedCount+=1}}_emitEvent(s){this._core.notificationCenter.emitOuterEvent(s.name,s)}onBroadcastMessageReceived(s){const{message:{messageHelper:r},OuterEvent:{MESSAGE_RECEIVED:g}}=this._core,u=this._avChatRoomHandler.isPollingSimplifiedMessage(),E=[],m=s.length;for(let D=0;D0&&this._emitEvent({name:g,data:E})}_updateLocalOnlineMemberCountFromTips(s){const{utils:{isEmpty:r}}=this._core,{ToGroupId:g,MsgBody:{OnlineMemberInfo:u}}=s;if(r(u))return;const{OnlineMemberNum:E=0,ExpireTime:m=TD}=u,D=Date.now();let M=this._avChatRoomHandler.getLocalOnlineMemberCount(g);r(M)?M={lastReqTime:0,lastSyncTime:0,latestUpdateTime:D,memberCount:E,expireTime:m}:(M.latestUpdateTime=D,M.memberCount=E),this._avChatRoomHandler.updateLocalOnlineMemberCount(g,M)}reset(){this._reportMessageStackedCount=0,this._sequenceList.clear(),this._messageIDList.clear(),this._broadcastMessageIDMap.clear()}};const hB=s=>{const{core:{store:r}}=CB;return(r.get("cloudConfig")||{})[s]},fh=s=>{const{core:{utils:{isUndefined:r}}}=CB;return!r(s)},HQ=()=>{const s=hB("polling_interval");return fh(s)?parseInt(s,10):300},BB=()=>{const s=hB("polling_simplified_msg");return fh(s)?parseInt(s,10):0};var iR=new class{constructor(){this._name="GetAVChatRoomOnlineMemberCount"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupOnlineMemberCount",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},OuterConstant:g}=this._core,u=r.getGroup(s);return u?u.type===g.GRP_AVCHATROOM?this._getOnlineMemberCount(s):this._parentPlugin.groupAction.getGroupOnlineMemberCount(s):{code:0,data:{memberCount:0}}})}_getOnlineMemberCount(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCount",{utils:{isEmpty:g}}=this._core,u=Pg.getLocalOnlineMemberCount(s);if(g(u)||this._isExpired(s)){const{memberCount:E=0}=yield this._getOnlineMemberCountFromServer(s);return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${E} from server.`),{code:0,data:{memberCount:E}}}return console.log(`${this._name}.${r} ok, groupID:${s} memberCount:${u.memberCount} from local.`),{code:0,data:{memberCount:u.memberCount}}})}_isExpired(s){const r=Pg.getLocalOnlineMemberCount(s),g=Date.now(),u=g-r.lastSyncTime>1e3*r.expireTime,E=g-r.latestUpdateTime>1e4,m=g-r.lastReqTime>3e3;return u&&E&&m}_getOnlineMemberCountFromServer(s){return mA(this,void 0,void 0,function*(){const r="_getOnlineMemberCountFromServer";try{const g=yield function(M,T){return mA(this,void 0,void 0,function*(){const P={GroupId:M};return T.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_online_member_num",data:P})})}(s,this._core),{OnlineMemberNum:u=0,ExpireTime:E=TD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:u,expireTime:E};return Pg.updateLocalOnlineMemberCount(s,D),{memberCount:u}}catch(g){const u=new this._core.helper.ChatError({functionName:r,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${r} fail:`,u),u}})}},Pg=new class{constructor(){this._name="AVChatRoomHandler",this._joinedGroupMap=new Map,this._pollingRequestInfoMap=new Map,this._pollingInstanceMap=new Map,this._onlineMemberCountMap=new Map,this._pollingIntervalMap=new Map,this._pollingNoMessageCountMap=new Map,this._membersReqInfoMap=new Map,this._startBroadcastSequence=1}init(s,r){this._core=s,this._parentPlugin=r,mh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:r}}=this._core,{GroupTips:g=[]}=s;for(let u=0;u0&&(r=[...this._joinedGroupMap.values()].filter(g=>g.type===s)),r}handleJoinGroupResult(s){return mA(this,void 0,void 0,function*(){const{utils:{isUndefined:r},OuterConstant:{CONV_GROUP:g},apiMap:{getConversationProfile:u},OuterConstant:E}=this._core,{longPollingKey:m,group:D,historyMessageList:M=[]}=s,{groupID:T}=D;return yield this._preCheck(D),this._joinedGroupMap.set(T,D),this._parentPlugin.groupDataHandler.updateLocalGroup([D]),this._parentPlugin.groupDataHandler.emitGroupListUpdate(),u(`${g}${T}`),iR.getGroupOnlineMemberCount(T),M.length>0&&mh.onMessageReceived(T,M,!0),r(m)?{code:0,data:{status:E.JOIN_STATUS_SUCCESS,group:D}}:{code:0,data:this.startMessageLongPolling(s)}})}isGroupCounterUpdated(s){return this._parentPlugin.groupCounter.isGroupCounterUpdated(s)}handleGroupCounterUpdated(s){this._parentPlugin.groupCounter.handleGroupCounterUpdated(s)}_preCheck(s){return mA(this,void 0,void 0,function*(){const{common:r,OuterConstant:g,helper:u,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(r.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=hB("polling_count_limit");return fh(T)&&T>0?parseInt(T,10):20})())throw new u.ChatError({code:qT,message:"the count of longPolling exceeds the max limit"});return}if(this._joinedAVChatRoomCount()===0||s.type===g.GRP_LIVE)return;const[D,M]=this._joinedGroupMap.entries().next().value;if(M.selfInfo.role===g.GRP_MBR_ROLE_OWNER)this._parentPlugin.groupDataHandler.deleteLocalGroup(D);else try{yield E(D)}catch(T){m.debug("quitGroup",`${this._name}._preCheck quitGroup failed, groupID:${D} info:`,T)}this.reset(D)})}startMessageLongPolling(s){const{OuterConstant:r}=this._core,{longPollingKey:g,startSequence:u=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:u}),this._pollingIntervalMap.set(m,HQ()),this._startPolling(m),this._reportLongPollingCount(),{status:r.JOIN_STATUS_SUCCESS,group:E}}_startPolling(s){if(this._core.ssoLog.debug("_startPolling",`${this._name}._startPolling groupID:${s}`),this._pollingInstanceMap.has(s)){const g=this._pollingInstanceMap.get(s);return void(g?.isRunning()||g==null||g.start())}const r=new tR({core:this._core,manager:this,groupID:s,getRequestParams:this._handleRequestParams.bind(this),onSuccess:this._handleSuccess.bind(this),onFail:this._handleFailure.bind(this)});r.start(),this._pollingInstanceMap.set(s,r)}_handleRequestParams(s){const{longPollingKey:r,startSequence:g}=this._pollingRequestInfoMap.get(s)||{};return s===[...this._pollingInstanceMap.keys()][0]?{longPollingKey:r,startSequence:g,startBroadcastSeq:this._startBroadcastSequence,simplifiedMessage:BB()}:{longPollingKey:r,startSequence:g,simplifiedMessage:BB()}}_handleSuccess(s,r){const{ErrorCode:g}=r;if(g!==0){const{longPollingKey:u,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${u} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,r)}_handleResponseData(s,r){const{Key:g,NextSeq:u,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=r;if(g&&u&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:u}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,HQ())),mh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=hB("polling_no_msg_count");return fh(T)?parseInt(T,10):20})()){const T=HQ()+(()=>{const P=hB("polling_interval_plus");return fh(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&mh.onBroadcastMessageReceived(D)}_handleFailure(s,r){const{ssoLog:g,utils:{safeStringify:u}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${u(r)}`)}_joinedAVChatRoomCount(){const{OuterConstant:s}=this._core;let r=[];return this._joinedGroupMap.size>0&&(r=this.getJoinedGroups().filter(g=>g.type===s.GRP_AVCHATROOM)),r.length}_hasJoinedAVChatRoom(s){return this._joinedGroupMap.has(s)}getJoinedGroups(){return[...this._joinedGroupMap.values()]}updateLocalLiveGroup(s,r){this._joinedGroupMap.set(s,r),this._parentPlugin.groupDataHandler.updateLocalGroup([r])}handleLiveHistoryMessages(s,r){mh.onMessageReceived(s,r,!0)}isOverFrequencyLimit(s){if(!this._membersReqInfoMap.has(s))return this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1;let{startTime:r,requestCount:g}=this._membersReqInfoMap.get(s);const{interval:u,count:E}=(()=>{const m=hB("av_members_freq_limit");if(fh(m)){const{interval:D,count:M}=JSON.parse(m);if(M>0&&D>0)return{interval:D,count:M}}return{interval:30,count:4}})();return Date.now()-r>1e3*u?(this._membersReqInfoMap.set(s,{startTime:Date.now(),requestCount:1}),!1):(g+=1,this._membersReqInfoMap.set(s,{startTime:r,requestCount:g}),g>E)}_stopPolling(s){if(this._core.ssoLog.debug("_stopPolling",`${this._name}._stopPolling groupID:${s}`),s){const{appStore:{conversationStore:r},OuterConstant:{CONV_GROUP:g}}=this._core;r.deleteConversation(`${g}${s}`);const u=this._pollingInstanceMap.get(s);return u?.stop(),this._parentPlugin.groupDataHandler.deleteLocalGroup(s),this._pollingInstanceMap.delete(s),this._pollingRequestInfoMap.delete(s),this._joinedGroupMap.delete(s),this._onlineMemberCountMap.delete(s),this._pollingIntervalMap.delete(s),this._pollingNoMessageCountMap.delete(s),void this._membersReqInfoMap.delete(s)}for(const r of this._pollingInstanceMap.values())r?.stop();this._pollingInstanceMap.clear(),this._pollingRequestInfoMap.clear(),this._joinedGroupMap.clear(),this._onlineMemberCountMap.clear(),this._pollingIntervalMap.clear(),this._pollingNoMessageCountMap.clear(),this._membersReqInfoMap.clear()}_updatePollingNoMessageCount(s,r){this._pollingNoMessageCountMap.set(s,r)}_getPollingNoMessageCount(s){return this._pollingNoMessageCountMap.get(s)||0}_reportLongPollingCount(){const s=this._joinedGroupMap.size;if(s>1){const{common:r,OuterConstant:g,ssoLog:u}=this._core,E=r.isUnlimitedAVChatRoom()?1:0,m=[],D=[];Array.from(this._joinedGroupMap.values()).forEach(({groupID:M,type:T})=>{T===g.GRP_LIVE?D.push(M):m.push(M)}),u.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,mh.reset()}},oR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"joinGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}joinGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.joinGroup(s),{data:{status:u,group:{type:E}}}=g;return E===r.GRP_AVCHATROOM?u===r.JOIN_STATUS_ALREADY_IN_GROUP?g:Pg.handleJoinGroupResult(g.data):g})}},jT=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"quitGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}quitGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.quitGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Pg.reset(s),g})}},sR=new class{init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"dismissGroup",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}dismissGroup(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=yield this._parentPlugin.groupAction.dismissGroup(s),{data:{type:u}}=g;return u===r.GRP_AVCHATROOM&&Pg.reset(s),g})}},Ym=new class{constructor(){this._name="GetAVChatRoomMemberList"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"getGroupMemberList",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const{appStore:{groupStore:r},helper:g,OuterConstant:u}=this._core,{groupID:E}=s,m=r.getGroup(E);if(m?.type===u.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(eR)){if(Pg.isOverFrequencyLimit(E))throw{code:2996,message:`Over frequency limit: get_members-${E}`};return this._getGroupMemberList(s)}return this._parentPlugin.groupMember.getGroupMemberList(s)})}_getGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="_getGroupMemberList",{helper:g}=this._core;try{const u=yield function(M,T){return mA(this,void 0,void 0,function*(){const{groupID:P,offset:W=0}=M,oA={GroupId:P,Timestamp:W};return T.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.get_members",data:oA})})}(s,this._core),{MemberList:E=[],NextTimestamp:m=0}=u||{},D=this._handleMemberList(E);return console.log(`${this._name}.${r} ok, groupID:${s.groupID} count:${D.length} nextOffset:${m}`),{code:0,data:{memberList:D,offset:m}}}catch(u){const E=new g.ChatError({functionName:r,code:u?.errorCode,message:u?.errorInfo});throw console.error(`${this._name}.${r} fail:`,E),E}})}_handleMemberList(s){return s.map(r=>{const{Member_Account:g,NickName:u="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=r;return{userID:g,nick:u,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},Vm=new class{constructor(){this._name="DeleteAVChatRoomMember"}init(s,r){this._core=s,this._parentPlugin=r;const{helper:g}=s;g.registerApi({apiName:"deleteGroupMember",context:this,matcher:()=>r.getInstalledSubPlugins().length>0})}deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="deleteGroupMember",{appStore:{groupStore:g},utils:{isUndefined:u},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(u(M))throw new E.ChatError({functionName:r,code:ND});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(JT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:r,code:VQ})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return mA(this,void 0,void 0,function*(){const r="_deleteGroupMember",{appStore:{groupStore:g},helper:u,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new u.ChatError({functionName:r,code:HT});try{return yield function(T,P){return mA(this,void 0,void 0,function*(){const{groupID:W,userIDList:oA,duration:EA,reason:wA}=T,kA={GroupId:W,Members_Account:oA,Duration:EA,Description:wA};return P.common.buildAndSendPacket({servcmd:"group_open_http_svc.ban_group_member",data:kA})})}(s,this._core),E.debug(r,`${this._name}.${r} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new u.ChatError({functionName:r,code:T?.errorCode,message:T?.errorInfo})}})}},_d=new class{constructor(){this._name="MarkAVChatRoomMember"}init(s){this._core=s;const{helper:r}=s;r.registerApi({apiName:"markGroupMemberList",context:this})}markGroupMemberList(s){return mA(this,void 0,void 0,function*(){const r="markGroupMemberList",{groupID:g,markType:u,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(oA,EA){return mA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:xA}=oA,LA={GroupId:wA,CommandType:kA,MemberList:xA};return EA.common.buildAndSendPacket({servcmd:"group_open_avchatroom_http_svc.modify_user_info",data:LA})})}(D,this._core),{MemberList:T=[]}=M||{},{successUserIDList:P,failureUserIDList:W}=this._handleResult(T,m);return{code:0,data:{successUserIDList:P,failureUserIDList:W},successLog:{message:`${this._name}.${r} ok, groupID:${g} markType:${u} enableMark:${E} success:${P.length} fail:${W.length}`}}}catch(M){throw new this._core.helper.ChatError({functionName:r,code:M?.errorCode,message:M?.errorInfo})}})}_generateRequestData(s){const{groupID:r,markType:g,enableMark:u,userIDList:E=[]}=s,m=u===!0?1:2,D=[...E];return D.length>500&&console.warn(`${this._name}._generateRequestData, the length of userIDList cannot exceed 500`),{groupID:r,operationType:m,memberList:D.map(M=>({Member_Account:M,Marks:[g]}))}}_handleResult(s,r){const g=[],u=[];return s.length===r.length?(g.push(...r),{successUserIDList:g,failureUserIDList:u}):(r.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):u.push(E)}),{successUserIDList:g,failureUserIDList:u})}},nR=new class{init(s,r){s.ssoLog.debug("AVChatRoomAction.init"),oR.init(s,r),jT.init(s,r),sR.init(s,r),Ym.init(s,r),iR.init(s,r),Vm.init(s,r),_d.init(s)}},rR=new class{constructor(){this._name="LiveHandler"}init(s){this._core=s;const{helper:r,ssoLog:g}=s;r.registerExperimentalAPI("startMessageLongPolling",this),r.registerExperimentalAPI("stopMessageLongPolling",this),g.debug("LiveHandler.init")}startMessageLongPolling(s){const{common:r,utils:{isEmpty:g},OuterConstant:u,ssoLog:E}=this._core,{groupID:m,longPollingKey:D,longPollingSequence:M=1}=s;if(g(D))return E.warn("startMessageLongPolling",`${this._name}.startMessageLongPolling longPollingKey is empty.`),Promise.resolve({});Pg.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Pg.getJoinedLiveList(),P=r.isUnlimitedAVChatRoom();!P&&T.length>0&&this.stopMessageLongPolling({groupID:T[0].groupID}),E.debug("startMessageLongPolling",`${this._name}.startMessageLongPolling isUnlimited:${P} groupID:${m} longPollingKey:${D} longPollingSequence:${M}`);const W={groupID:m,type:u.GRP_LIVE};return Pg.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Pg.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:r}=s;return Pg.reset(r),this._core.ssoLog.debug("stopMessageLongPolling",`${this._name}.stopMessageLongPolling ok, groupID:${r}`),Promise.resolve({groupID:r})}_getLiveHistoryMessages(s){return mA(this,void 0,void 0,function*(){const{ssoLog:r}=this._core,{groupID:g}=s;try{const u=yield function(m,D){return mA(this,void 0,void 0,function*(){const{groupID:M,longPollingKey:T,startSequence:P}=m,W={GroupId:M,LongPollingKey:T,PullPreSeq:P};return D.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_huge_group_msg",data:W})})}(s,this._core),{RspMsgList:E=[]}=u||{};r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Pg.handleLiveHistoryMessages(g,E)}catch(u){r.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${u.message}`)}})}},Jm=new class{constructor(){this.name="AVChatRoom"}install(s,r){this._core=s,CB.init(s),Pg.init(s,r),nR.init(s,r),rR.init(s);const{notificationCenter:g,InnerEvent:u}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(u.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(u.LOGOUT,this._reset,this),g.subscribeInnerEvent(u.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Pg.onAVChatRoomSystemNotification(s)}_reset(){Pg.reset()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:r}=this._core,{InnerEventSubType:g}=s;s.unSubscribeInnerEvent(r.MESSAGE_PUSH,g.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this._dispose,this)}};const Ag=new class{init(s){this.core=s}},Hm="message",QB="user",pB={OR:"or",AND:"and"},RI=20,WT=20,aR=20,yh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},qm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![pB.OR,pB.AND].includes(s)||"keywordListMatchType should be OR or AND"},RC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},qQ={required:!1,rules:["string"],allowEmpty:!0},gR={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=Ag.core;if(!Array.isArray(s))return"groupTypeList should be an array";const g=[r.GRP_PUBLIC,r.GRP_COMMUNITY,r.GRP_WORK,r.GRP_MEETING];let u=!1;for(let E=0;E{const{OuterConstant:r}=Ag.core,g=[r.MSG_TEXT,r.MSG_IMAGE,r.MSG_AUDIO,r.MSG_FILE,r.MSG_VIDEO,r.MSG_LOCATION,r.MSG_CUSTOM,r.MSG_MERGER];let u=!1;for(let E=0;E{const{OuterConstant:r}=Ag.core;return!(!s?.startsWith(r.CONV_C2C)&&!s?.startsWith(r.CONV_GROUP)&&s!==r.CONV_SYSTEM)||"conversationID is invalid"}},Km=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:r=>typeof r=="number"&&r>=0||`${s} should be a number >= 0';`}),bD={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:r}=Ag.core;return!![r.GENDER_FEMALE,r.GENDER_MALE].includes(s)||"gender is invalid"}},jm={searchCloudMessages:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:cR,conversationID:lR,timePosition:Km("timePosition"),timePeriod:Km("timePeriod")},searchCloudUsers:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,miniBirthday:Km("miniBirthday"),maxBirthday:Km("maxBirthday"),gender:bD},searchCloudGroupMembers:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,groupTypeList:gR,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:yh,keywordListMatchType:qm,cursor:qQ,count:RC,groupTypeList:gR}},kD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var LD=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,Ag.init(s),s.helper.registerApi({apiName:"searchCloudMessages",context:this}),s.helper.registerApi({apiName:"searchCloudUsers",context:this}),s.helper.registerApi({apiName:"searchCloudGroupMembers",context:this}),s.helper.registerApi({apiName:"searchCloudGroups",context:this}),s.helper.registerValidateConfig({auth:kD,params:jm})}searchCloudMessages(s){return mA(this,void 0,void 0,function*(){try{const{OuterConstant:r,helper:g}=this._core,{conversationID:u,timePeriod:E,timePosition:m}=s,D=So(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);u&&(u.startsWith(r.CONV_C2C)?M.account=u.replace(r.CONV_C2C,""):u.startsWith(r.CONV_GROUP)&&(M.groupID=u.replace(r.CONV_GROUP,""))),this._setTimeRangeParams(M,{timePeriod:E,timePosition:m});const T=yield function(LA){return mA(this,void 0,void 0,function*(){const{count:SA,keywordList:OA,keywordListMatchType:qA,senderUserIDList:Ie,messageTypeList:le,endTime:bi,startTime:ki,cursor:Ot,account:Li,groupID:cs}=LA,Re={Count:SA,KeywordList:OA,MatchType:qA,SendUserIDList:Ie,MsgTypeList:le,EndTime:bi,StartTime:ki,Cursor:Ot,PeerAccount:Li,GroupID:cs};return Ag.core.common.buildAndSendPacket({servcmd:"message_search.query",data:Re})})}(M);if(!T)return{code:0,data:{}};const{ErrorCode:P,ErrorInfo:W,TotalCount:oA,Cursor:EA="",ConversationMsgs:wA=[]}=T;if(P!==0)throw{errorCode:P,errorInfo:W};const kA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} res: totalCount:${oA}`;return{code:0,data:{searchResultList:wA.map(LA=>{const{MsgList:SA,Count:OA,GroupID:qA,UserID:Ie}=LA,le=qA?`${r.CONV_GROUP}${qA}`:`${r.CONV_C2C}${Ie}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:le,messageCount:OA,messageList:[]};const bi=SA.map(ki=>g.isEmpty(qA)?function(Ot,Li){const cs=Li.OuterConstant.CONV_C2C,Re=Li.message.messageHelper.parseServerPushMessage(Ot),St=Li.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:cs,flow:"in"}));return St.setElement(Re.elements),St}(ki,this._core):function(Ot,Li){const cs=Li.OuterConstant.CONV_GROUP,Re=Li.message.messageHelper.parseServerGroupMessage(Ot),St=Li.message.messageFactory.createMessage(Object.assign(Object.assign({},Re),{conversationType:cs,flow:"in"}));return St.setElement(Re.elements),St}(ki,this._core));return{conversationID:le,messageCount:OA,messageList:bi}}),cursor:EA,totalCount:oA},successLog:{message:kA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:Hm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return mA(this,void 0,void 0,function*(){var r;try{const{keywordListMatchType:g,count:u=WT}=s,E=So(s,["keywordListMatchType","count"]),m=Object.assign({count:u,keywordListMatchType:g===pB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return mA(this,void 0,void 0,function*(){const{count:xA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:qA,cursor:Ie,gender:le}=kA,bi={Count:xA,Keywords:LA,KeywordMatchType:SA,Cursor:Ie,UserBirthStart:OA,UserBirthEnd:qA,Gender:le};return Ag.core.common.buildAndSendPacket({servcmd:"user_search.query",data:bi})})}(m);if(!D)return{error:0,data:{}};const{ErrorCode:M,ErrorInfo:T,TotalCount:P,Cursor:W="",Users:oA=[]}=D;if(M!==0)throw{errorCode:M,errorInfo:T};const EA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${P}`,wA=[];for(let kA=0,xA=oA.length;kA({tag:Ie.Tag,value:Ie.StrValue})),qA=(r=this._core.user.userProfile)===null||r===void 0?void 0:r.createProfile(LA,OA);wA.push(qA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:u,errorInfo:E}=g||{};this._handleError({errorCode:u,errorInfo:E,searchType:QB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return mA(this,void 0,void 0,function*(){try{const{count:r=aR,keywordListMatchType:g}=s,u=So(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===pB.AND?1:0},u),m=yield function(wA){return mA(this,void 0,void 0,function*(){const{count:kA,keywordList:xA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:qA}=wA,Ie={Count:kA,Keywords:xA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:qA};return Ag.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:Ie})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,GroupMembers:T=[],Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const oA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`,EA=new Map;return T.forEach(wA=>{const{GroupID:kA,GroupName:xA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:qA,GroupMemberNameCard:Ie,GroupMemberAvatar:le=""}=wA,bi={groupID:kA,name:xA,type:LA,avatar:SA},ki={userID:qA,nick:OA,nameCard:Ie,avatar:le};if(EA.has(kA)){const Ot=EA.get(kA);Ot.memberList.push(ki),EA.set(kA,Ot)}else EA.set(kA,{groupInfo:bi,memberList:[ki]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:oA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:QB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return mA(this,void 0,void 0,function*(){try{const{count:r=RI,keywordListMatchType:g}=s,u=So(s,["count","keywordListMatchType"]),E=Object.assign({count:r,keywordListMatchType:g===pB.AND?1:0},u),m=yield function(EA){return mA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:xA,groupTypeList:LA,cursor:SA}=EA,OA={Count:wA,Keywords:kA,KeywordMatchType:xA,Cursor:SA,GroupType:LA};return Ag.core.common.buildAndSendPacket({servcmd:"group_search.query",data:OA})})}(E);if(!m)return{code:0,data:{}};const{ErrorCode:D,ErrorInfo:M,Groups:T,Cursor:P,TotalCount:W}=m;if(D!==0)throw{errorCode:D,errorInfo:M};const oA=`keywordList:${s.keywordList} keywordListMatchType:${s.keywordListMatchType} cursor:${s.cursor} count:${s.count} res: totalCount:${W}`;return{code:0,data:{searchResultList:T?.map(EA=>function(wA){const{GroupFaceUrl:kA,GroupID:xA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:qA,GroupOwnerUserID:Ie,GroupOwnerUserName:le,GroupType:bi,GroupAddOption:ki,GroupInviteOption:Ot}=wA;return{avatar:kA,groupID:xA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:qA,ownerID:Ie,ownerNick:le,type:bi,joinOption:ki,inviteOption:Ot}}(EA))||[],cursor:P,totalCount:W},successLog:{message:oA}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};this._handleError({errorCode:g,errorInfo:u,searchType:QB,functionName:"searchCloudGroups"})}})}_setTimeRangeParams(s,{timePeriod:r,timePosition:g}){r&&r>0&&(s.startTime=g&&g>0?g-r:this._core.helper.timeManager.getServerTimeSeconds()-r),s.startTime&&s.startTime<0&&(s.startTime=void 0),g&&g>0&&(s.endTime=g)}_handleError({errorCode:s,errorMessage:r,searchType:g}){const{helper:u}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Hm&&s===27003?E="SearchParamsError":g!==Hm&&s===60018&&(E="SearchOverLimit"),new u.ChatError({code:E,message:r})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,r){const{miniBirthday:g,maxBirthday:u}=r;g!==void 0&&(s.miniBirthday=g,u===void 0&&(s.maxBirthday=4294967295)),u!==void 0&&(s.maxBirthday=u)}};function Dh(s,r){return Math.round(Number(s)*Math.pow(10,r))/Math.pow(10,r)}const IR="qualityStat",UD="im-ssolog-quality-stat";var FD;(function(s){s[s.ONLINE=8]="ONLINE"})(FD||(FD={}));const Wm="networkRTT",Sh="messageE2EDelay",mB="sendMessageC2C",Mh="sendMessageGroup",vh="sendMessageGroupAV",fB="sendMessageRichMedia",yB="cosUpload",wC="messageReceivedGroup",KQ="messageReceivedGroupAVPush",jQ="messageReceivedGroupAVPull",zT={[Wm]:2,[Sh]:3,[mB]:4,[Mh]:5,[vh]:6,[fB]:7,[wC]:8,[KQ]:9,[jQ]:10,[yB]:11},uR=[mB,Mh,vh,fB,yB],Rh=[wC,KQ,jQ],DB=[Wm,Sh,mB,Mh,vh,fB,yB,wC,KQ,jQ],OD={ERR_SVR_COMM_SENSITIVE_TEXT:80001,ERR_SVR_COMM_BODY_SIZE_LIMIT:80002,OPEN_SERVICE_OVERLOAD_ERROR:60022,ERR_SVR_MSG_PKG_PARSE_FAILED:20001,ERR_SVR_MSG_INTERNAL_AUTH_FAILED:20002,ERR_SVR_MSG_INVALID_ID:20003,ERR_SVR_MSG_PUSH_DENY:20006,ERR_SVR_MSG_IN_PEER_BLACKLIST:20007,ERR_SVR_MSG_BOTH_NOT_FRIEND:20009,ERR_SVR_MSG_NOT_PEER_FRIEND:20010,ERR_SVR_MSG_NOT_SELF_FRIEND:20011,ERR_SVR_MSG_SHUTUP_DENY:20012,ERR_SVR_GROUP_INVALID_PARAMETERS:10004,ERR_SVR_GROUP_PERMISSION_DENY:10007,ERR_SVR_GROUP_NOT_FOUND:10010,ERR_SVR_GROUP_INVALID_GROUPID:10015,ERR_SVR_GROUP_REJECT_FROM_THIRDPARTY:10016,ERR_SVR_GROUP_SHUTUP_DENY:10017,MSG_SEND_FAIL:2100,OVER_FREQUENCY_LIMIT:2996},zm="quality_stat";var WQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(OD))}init(s){this._core=s,Object.values(uR).forEach(r=>{this._messageStatsMap.set(r,{totalCount:0,successCount:0,failedCountOfUserSide:0,costSum:0,costCount:0,fileSizeSum:0})})}dispatchSendStats(s){const{name:r,message:g,error:u,startTs:E}=s,{SEND_MESSAGE_STAT:m}=this._core.constants;switch(r){case m.TOTAL_COUNT:this._handleTotalCount(g);break;case m.SUCCESS_COUNT:this._handleSuccessCount(g);break;case m.FAILED_COUNT:this._handleFailedCount(g,u);break;case m.SEND_COST:this._handleSendCost(g,E)}}getStatResult(s){const r=this._messageStatsMap.get(s);if(!r||r.totalCount===0)return null;const{totalCount:g,successCount:u,failedCountOfUserSide:E}=r,m=Dh(u/g*100,2),D=u+E,M=Dh(D/g*100,2),T=this._calcAverageValue(r,s);return this._resetStat(s),{total_count:g,success_count_business:u,percent_business:m,success_count_platform:D,percent_platform:M,average_value:T}}_handleTotalCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.totalCount++}_handleSuccessCount(s){const r=this._getSendMessageSpecifiedKey(s),g=r&&this._messageStatsMap.get(r);g&&g.successCount++}_handleFailedCount(s,r){var g;const u=(g=r?.code)!==null&&g!==void 0?g:r?.errorCode;if(this._isUserSideError(u)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,r){const g=this._getSendMessageSpecifiedKey(s),u=g&&this._messageStatsMap.get(g);u&&(u.costSum+=Date.now()-r,u.costCount++)}_isUserSideError(s){return this._userSideErrorCodes.has(s)||s>=120001&&s<=13e4||s>=10100&&s<=10200}_getSendMessageSpecifiedKey(s){const{MSG_IMAGE:r,MSG_AUDIO:g,MSG_VIDEO:u,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([r,g,u,E].includes(s.type))return fB;if(s.conversationType===m)return mB;if(s.conversationType===D){const{groupStore:T}=this._core.appStore,P=T.getGroup(s.to);if(!P)return;const{type:W}=P;return W===M?vh:Mh}}_calcAverageValue(s,r){return s.costCount===0?0:Math.round(r===yB?1e3*s.fileSizeSum/s.costSum:s.costSum/s.costCount)}_resetStat(s){const r=this._messageStatsMap.get(s);r&&(r.totalCount=0,r.successCount=0,r.failedCountOfUserSide=0,r.costSum=0,r.costCount=0,r.fileSizeSum=0)}},zQ=new class{constructor(){this._lastCycleStats=new Map,this._currentCycleStats=new Map}init(s){this._core=s;const{OuterEvent:r,notificationCenter:g}=s;this._initStatsMap(),g.subscribeOuterEvent(r.MESSAGE_RECEIVED,this._onMessageReceived,this)}addMessageSequence(s){const r=this._getReceivedMessageSpecifiedKey(s),{utils:{isUndefined:g},OuterConstant:{CONV_GROUP:u},ssoLog:E}=this._core;if(g(r)||!this._currentCycleStats.has(r))return void E.debug("addMessageSequence",`${IR}.addMessageSequence invalid key:${r}`);const{conversationID:m,sequence:D}=s,M=m.replace(u,""),T=this._lastCycleStats.get(r);if(T.size===0||!T.has(M))return void this._addToCurrentCycle(r,M,D);const P=T.get(M);D>P.minSeq&&D{const{sortedSequences:m,minSeq:D,maxSeq:M}=E;m.length>0&&(u+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:u,percent_business:Dh(u/g*100,2)})}reset(){this._lastCycleStats.clear(),this._currentCycleStats.clear()}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_initStatsMap(){Object.values(Rh).forEach(s=>{this._lastCycleStats.set(s,new Map),this._currentCycleStats.set(s,new Map)})}_onMessageReceived(s){const{data:r=[]}=s;r.forEach(g=>{this.addMessageSequence(g)})}_transferCycleDataOptimized(s){const r=this._currentCycleStats.get(s);if(!r)return;const g=new Map;r.forEach((u,E)=>{const m=u.dirty?[...u.sortedSequences].sort((D,M)=>D-M):u.sortedSequences;g.set(E,{sortedSequences:m,minSeq:u.minSeq,maxSeq:u.maxSeq,dirty:!1})}),this._lastCycleStats.set(s,g),this._currentCycleStats.set(s,new Map)}_getReceivedMessageSpecifiedKey(s){const{OuterConstant:{CONV_GROUP:r,GRP_AVCHATROOM:g}}=this._core;if(s.conversationType===r&&s?._onlineOnlyFlag!==!0){const{groupStore:u}=this._core.appStore,E=u.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?jQ:wC}}_insertToLastCycle(s,r){r.dirty&&(r.sortedSequences.sort((u,E)=>u-E),r.dirty=!1);const g=this._findInsertPos(r.sortedSequences,s);r.sortedSequences.splice(g,0,s),r.minSeq=Math.min(r.minSeq,s),r.maxSeq=Math.max(r.maxSeq,s)}_findInsertPos(s,r){let g=0,u=s.length-1;for(;g<=u;){const E=Math.floor((g+u)/2);if(s[E]===r)return E;s[E]0&&(this._totalDelay+=g,this._totalCount++,g<=1?this._countLessThan1s++:g<=3&&this._countLessThan3s++)}getStatResult(){if(this._totalCount===0)return null;const s={total_count:this._totalCount,success_count_business:this._countLessThan1s,success_count_platform:this._countLessThan3s,percent_business:this._calculatePercentage(this._countLessThan1s,this._totalCount),percent_platform:this._calculatePercentage(this._countLessThan3s,this._totalCount),average_value:this._calculateAverageDelay(this._totalCount)};return this.reset(),s}reset(){this._totalDelay=0,this._totalCount=0,this._countLessThan1s=0,this._countLessThan3s=0}dispose(){const{notificationCenter:s,OuterEvent:{MESSAGE_RECEIVED:r}}=this._core;s.unSubscribeOuterEvent(r,this._onMessageReceived,this),this.reset()}_onMessageReceived(s){const{data:r=[]}=s,{OuterConstant:{MSG_GRP_TIP:g,MSG_GRP_SYS_NOTICE:u}}=this._core,E=[g,u];r.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:Dh(this._totalDelay/s,1)}_calculatePercentage(s,r){return Dh(s/r*100,2)}},ER=new class{init(s){this.core=s}},ZT=new class{constructor(){this.name="MessageQualityStat",this._reportIndex=0,this._wholePeriod=!1,this._pendingReports=[],this._failedLogsCache=new Map}install(s){this._core=s;const{helper:r,notificationCenter:g,InnerEvent:{QUALITY_STAT:u,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;ER.init(s),WQ.init(s),zQ.init(s),ZQ.init(s),r.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(u,this._handleQualityStat,this),g.subscribeInnerEvent(E,this._reset,this),g.subscribeInnerEvent(m,this._dispose,this)}handleLoginSuccess(){const{store:s,helper:r,utils:{isUndefined:g}}=this._core,u=s.get("cloudConfig")||{},{q_rpt_interval:E}=u,m=g(E)?12e4:Number(E);r.taskScheduler.addTask({id:zm,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...DB.map(r=>{const g=this._buildQualityReportItem(r);return g?Object.assign(Object.assign({},g),{report_index:this._reportIndex,whole_period:this._wholePeriod}):null}).filter(Boolean),...this._pendingReports];this._pendingReports=[],this._needSkipReport()||this._uploadQualityReports(s)}_handleQualityStat(s){const{constants:{QUALITY_METRICS:r}}=this._core,{label:g,data:u}=s;g===r.MESSAGE_SEND_SUCCESS_RATE&&WQ.dispatchSendStats(u)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("instance")||{},{sdkAppId:E}=u,{q_rpt_sdkappid_bl:m=[]}=g;if(!r.isEmpty(m))return m.split(",").map(D=>Number(D)).includes(E)}_isTinyIDInWhitelist(){const{store:s,utils:r}=this._core,g=s.get("cloudConfig")||{},u=s.get("login")||{},E=Number(u.tinyID),{q_rpt_tinyid_wl:m=[]}=g;if(!r.isEmpty(m))return m.split(",").includes(E)}_buildQualityReportItem(s){const r=this._getStatResultByKey(s);if(r===null)return null;const g={quality_type:zT[s],timestamp:Date.now(),network_type:FD.ONLINE,extension:""};return Object.assign(Object.assign({},g),r)}_getStatResultByKey(s){switch(s){case Sh:return ZQ.getStatResult();case mB:case Mh:case vh:case fB:case yB:return WQ.getStatResult(s);case wC:case KQ:case jQ:return zQ.getStatResult(s);default:return null}}_uploadQualityReports(s){return mA(this,void 0,void 0,function*(){try{const r={header:this._core.common.getCommonHead(),quality:s};yield function(g){const{common:u,channel:E}=ER.core,m="imopenstat.tim_web_report_v2",D=u.generateSSOLogProtocolData({servcmd:m,data:g}),M=`${D.head.seq}${m}`;return E.sendPacket(D,{requestId:M})}(r),this._reportIndex++,this._wholePeriod=!1}catch(r){console.warn("doReport failed. error:",r),this._pendingReports=this._pendingReports.concat(s),this._cacheFailedLogs()}})}_cacheFailedLogs(){const s=this._pendingReports,r=`${IR}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(UD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${r} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(UD,g),console.log(`${r} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(zm)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:r,LOGOUT:g,DESTROY:u}}=this._core;s.unSubscribeInnerEvent(r,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(u,this._dispose,this),this._reset(),ZQ.dispose(),zQ.dispose()}};const ll=new class{init(s){this.core=s}};function dR(s){return mA(this,void 0,void 0,function*(){var r;const{message:g,user:u,appStore:E,constants:{OuterConstant:m}}=ll.core,D=E.conversationStore.getConversationMap();if(D.has(s)){const T=(r=D.get(s))===null||r===void 0?void 0:r.userProfile;if(T&&s.startsWith(m.CONV_C2C)){const{avatar:P,nick:W}=T;ll.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield u.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function CR(s){return mA(this,void 0,void 0,function*(){const r=s.map(g=>g.revoker);try{const g=yield function(u){return mA(this,void 0,void 0,function*(){var E,m;const D=yield(E=ll.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:u});return D?.data?(m=D.data)===null||m===void 0?void 0:m.reduce((M,{userID:T,nick:P,avatar:W})=>(M[T]={nick:P||"",avatar:W||""},M),{}):null})}(r);g&&s.forEach(u=>{const{revoker:E}=u;g[E]&&(u.revokerInfo.nick=g[E].nick||"",u.revokerInfo.avatar=g[E].avatar||"",u.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const PD=1,hR=2,wh=20,XQ=2500,BR=1,_h=300;function $Q(s){return mA(this,void 0,void 0,function*(){var r,g;const{appStore:u,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=ll.core,{messageList:P,conversationID:W}=s,oA=u.conversationStore.getConversationMap();let EA=(r=oA.get(W))===null||r===void 0?void 0:r.peerReadTime;if(!EA){const kA=W.replace(T,""),xA=yield function(LA){return mA(this,void 0,void 0,function*(){const SA={To_Account:LA};return ll.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(xA){const{ReadTime:LA}=xA;EA=LA?.[0],oA.has(W)&&(oA.get(W).peerReadTime=EA)}}if(oA.has(W)){const kA=(g=oA.get(W))===null||g===void 0?void 0:g.lastMessage;E(kA)||kA.fromAccount===m()&&kA.lastTime<=EA&&!kA.isPeerRead&&(kA.isPeerRead=!0,u.conversationStore.updateConversation(W,{lastMessage:kA}))}const wA=[];P.forEach(kA=>{kA.time<=EA&&!kA.isPeerRead&&kA.flow==="out"&&(kA.isPeerRead=!0,wA.push(kA))}),wA.length>0&&D.emitOuterEvent(M.MESSAGE_READ_BY_PEER,{name:M.MESSAGE_READ_BY_PEER,data:wA})})}var QR=new class{init(s){this._core=s,s.helper.registerApi({apiName:"getMessageList",context:this}),s.helper.registerApi({apiName:"getMessageListHopping",context:this}),s.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(s){return mA(this,void 0,void 0,function*(){try{const{message:r,OuterConstant:{Direction:g,CONV_C2C:u,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=wh;if(M==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const W=this._getAvailableLocalMessagesCount({conversationID:M,nextReqMessageID:T});if(this._needFetchHistoryMessageList({conversationID:M,availableLocalMessagesCount:W,targetCount:P})){let oA=null;if(M.startsWith(E)?oA=yield r.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(u)&&(oA=yield r.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),oA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=oA,xA=r.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(Ie){const{appStore:le,message:bi,OuterConstant:ki}=ll.core,Ot=le.conversationStore.getConversation(Ie),Li=bi.messageDataHandler.getLocalMessageList(Ie);if(!Ot||Li.length===0||Ie===ki.CONV_SYSTEM)return;const cs=[];for(let St=0;StUA.isRevoked).length;Re=cs.length-Ot.unreadCount-St}else Re=cs.length-Ot.unreadCount;for(let St=0;StIe.isRevoked);yield CR(SA),D.emitInnerEvent(m,xA);const OA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},qA=LA.map(Ie=>Ie.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(qA)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:M,nextReqMessageID:T,count:P}),successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W}}`}}}catch(r){const{code:g,message:u}=r||{};throw new this._core.helper.ChatError({code:g,message:u,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return mA(this,void 0,void 0,function*(){var r,g;const{OuterConstant:{Direction:u,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=u.FORWARD}=s,{utils:{isEmpty:oA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![u.BACKWARD,u.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:xA=wh}=s;xA=xA>wh?wh:xA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:xA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:qA,invisibleSequenceList:Ie}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(qA),wA.emitInnerEvent(kA,qA),W===u.FORWARD){const le=OA&&SA<1;return{code:0,data:{messageList:qA,isCompleted:le,nextMessageSeq:le?"":SA}}}if(W===u.BACKWARD){if(oA(qA)&&oA(Ie))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const le=((r=qA?.[qA.length-1])===null||r===void 0?void 0:r.sequence)||0,bi=((g=Ie?.[Ie.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:qA.filter(ki=>ki.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(le,bi)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:xA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:qA}=LA;return wA.emitInnerEvent(kA,SA),qA||(W===u.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield $Q({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:qA,nextMessageTime:qA?"":OA}}}})}clearHistoryMessage(s){return mA(this,void 0,void 0,function*(){var r;const{appStore:g,common:{ChatError:u,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new u({code:XQ});const W={fromAccount:E()},{type:oA}=P;oA===m?(W.type=PD,W.toAccount=s.replace(m,"")):oA===D&&(W.type=hR,W.toGroupID=s.replace(D,""));try{return yield(r=M?.setMessageRead)===null||r===void 0?void 0:r.call(M,{conversationID:s}),(yield function(wA){return mA(this,void 0,void 0,function*(){const{fromAccount:kA,type:xA,toAccount:LA,toGroupID:SA}=wA,OA={From_Account:kA,Type:xA,To_Account:LA,ToGroupid:SA};return ll.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:OA})})}(W))&&(T.messageDataHandler.deleteConversationMessageList(s),T.messageHistory.completedHistoryConversations.delete(s),T.messageHistory.clearHistoryMessageListFetchAnchors(s),this._updateConversationLastMessage(s)),{code:0,data:{conversationID:s},successLog:{message:`convID:${s}`}}}catch(EA){const{errorCode:wA}=EA;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:wA,moreMessage:`convID:${s}`})}})}_updateConversationLastMessage(s){const{appStore:r}=this._core;r.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:r}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:u}}=this._core,E=this._core.message.messageDataHandler.getLocalMessageList(s),{length:m}=E;if(!r)return m;let D=-1;return s?.startsWith(g)?D=E.findIndex(M=>M.ID===r):s?.startsWith(u)&&(D=E.findIndex(M=>r.includes("-")?M.ID===r:String(M.sequence)===r)),D===-1?0:D}_needFetchHistoryMessageList({conversationID:s,availableLocalMessagesCount:r,targetCount:g}){const{message:u}=this._core;return rr.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=oA>u?oA-u:0,T=oA):W=M>u?M-u:0,P.messageList=D.slice(W,oA),P.isCompleted=T<=u&&m.messageHistory.completedHistoryConversations.has(r),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:r,targetIndex:W}),r.startsWith(E)&&(yield dR(r),yield $Q({messageList:P.messageList,conversationID:r})),P})}_generateNextReqMessageID({conversationID:s,targetIndex:r}){const g=this._core.message.messageDataHandler.getLocalMessageList(s);return s.startsWith("C2C")?g[r].ID:String(g[r].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},SB=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(s){this._core=s;const{common:{workflowManager:r},constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:u,InnerEvent:E}}=s;r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),r.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,u.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),s.notificationCenter.subscribeInnerEvent(E.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=r.filter(m=>m.type===g.CONV_GROUP&&m.groupProfile.type!==g.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(E)}}_recoverGroupHistoryMessage(s){return mA(this,void 0,void 0,function*(){const{OuterConstant:r}=this._core,g=[],u=[];return yield Promise.all(s?.map(E=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:m}={},lastMessage:{lastSequence:D}={}}=E,M=`${r.CONV_GROUP}${m}`;let T=this._getLocalLastMessageSequence(M);this._shouldRecoverHistory({localLastMessageSequence:T,serverLastMessageSequence:D})&&(yield this._recoverGroupHistoryForConversation({conversationID:M,localLastMessageSequence:T,serverLastMessageSequence:D,groupTipList:u})),g.push(M.replace(r.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:u}})}_recoverGroupHistoryForConversation(s){return mA(this,arguments,void 0,function*({conversationID:r,localLastMessageSequence:g,serverLastMessageSequence:u,groupTipList:E}){try{const{utils:{isArray:m,isObject:D,isEmpty:M},OuterEvent:T,OuterConstant:P,notificationCenter:W,message:oA,appStore:EA,common:{getMessagePreviewText:wA,buildLastMessage:kA}}=this._core,xA=u-g,LA=Math.min(20,xA),SA={},OA=yield oA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:r,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:qA,hasNoMoreHistoryMessage:Ie,messageList:le,serverGroupTipList:bi}=OA;m(bi)&&E.push(...bi);const ki=Ie&&qA<0,Ot=[];if(m(le)&&(le.forEach(Li=>{oA.messageReceiver.groupMessageReceiver.updateMessageProfile(Li),Li.from===P.CONV_SYSTEM&&(Li.isSystemMessage=!1),oA.messageDataHandler.storeConversationMessage(Li)&&!M(Li.payload)&&(Ot.push(Li),Li._isExcludedFromLastMessage||(SA.lastMessage=kA(Li)))}),Ot.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:Ot})),!ki&&le.length>0){const Li=le[le.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:r,localLastMessageSequence:Li,serverLastMessageSequence:u,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(SA.lastMessage.type,SA.lastMessage.payload),EA.conversationStore.updateConversation(r,SA))}catch(m){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${r}`,{error:m})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:s}=this._core,r=s.messageDataHandler.getContinuousMessagesByConversation();for(const[g,u]of r){const E=Array.from(u.values());if(E?.length>0){const m=E[E.length-1];g.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(g,m.time):g.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(g,m.sequence)}}}_getLocalLastMessageSequence(s){const{message:r}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(s))return this._lastMessageSequenceMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:r,serverLastMessageSequence:g}=s;if(typeof r!="number"||typeof g!="number")return!1;const u=g-r;return g!==0&&r>0&&u>=BR&&u<_h}_syncC2COfflineMessage(s){const{conversationList:r}=s?.result||{},{OuterConstant:g,utils:{isArray:u}}=this._core;if(u(r)){const E=[];return r.forEach(m=>{m.type===g.CONV_C2C&&E.push(m)}),this._recoverC2CHistoryMessage(E)}}_recoverC2CHistoryMessage(s){return mA(this,void 0,void 0,function*(){yield Promise.all(s?.map(r=>mA(this,void 0,void 0,function*(){const{conversationID:g,lastMessage:{lastTime:u}={}}=r,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:u})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:u}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:r,serverLastMessageTime:g}=s,u=g-r;return r>0&&u>=1&&u<=600}_recoverHistoryForC2CConversation(s){return mA(this,void 0,void 0,function*(){var r;const{conversationID:g,localLastMessageTime:u,serverLastMessageTime:E}=s,{utils:{isArray:m,isObject:D,isEmpty:M,safeStringify:T},OuterEvent:P,OuterConstant:W,notificationCenter:oA,message:EA,appStore:wA,common:{getMessagePreviewText:kA,buildLastMessage:xA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:u,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:qA}=SA,Ie=[];m(qA)&&(qA.forEach(bi=>{EA.messageDataHandler.storeConversationMessage(bi)&&!M(bi.payload)&&(Ie.push(bi),bi._isExcludedFromLastMessage||(LA.lastMessage=xA(bi)))}),Ie.length>0&&oA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:Ie}));const le=(r=qA[qA.length-1])===null||r===void 0?void 0:r.time;!OA&&le>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:le,serverLastMessageTime:E})),D(LA.lastMessage)&&(LA.lastMessage.messageForShow=kA(LA.lastMessage.type,LA.lastMessage.payload),wA.conversationStore.updateConversation(g,LA))}catch(LA){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${g} error: ${T(LA)}`)}})}_getLocalLastMessageTime(s){const{message:r}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=r.messageDataHandler.getLocalMessageList(s),u=g[g.length-1];return u?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},MB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,ll.init(s),QR.init(s),SB.init(s),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.LOGOUT,this._reset,this),s.notificationCenter.subscribeInnerEvent(s.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:s,InnerEvent:r}=this._core;s.unSubscribeInnerEvent(r.LOGOUT,this._reset,this),s.unSubscribeInnerEvent(r.DESTROY,this.dispose,this),SB.dispose()}_reset(){SB.reset()}},xD=new class{init(s){this.core=s}},_C=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(s){const{helper:{registerExperimentalAPI:r}}=s;this._core=s,r("reportModalView",this),r("reportTUIFeatureUsage",this),r("reportRoomEngineEvent",this)}reportModalView(s){const{ssoLog:r,utils:{safeStringify:g,isString:u}}=this._core;try{if(!u(s))throw new Error("reportModalView data is not a string");r.createSSOLogData({method:"reportModalView",message:s,eventType:30}).end(!0)}catch(E){r.debug(`reportModalView Report failed: ${g(E)}`)}}reportTUIFeatureUsage(s){const{ssoLog:r,utils:{safeStringify:g,isEmpty:u}}=this._core,{atomicStoreID:E}=s;try{u(E)||this._reportedAtomicStoreIDs.has(E)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${s.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:E}),this._reportedAtomicStoreIDs.add(E))}catch(m){r.debug(`reportTUIFeatureUsage Report failed: ${g(m)}`)}}reportRoomEngineEvent(s){const{utils:{safeStringify:r},ssoLog:g}=this._core;try{g.debug(`reportRoomEngineEvent Report: ${r(s)}`);const{eventId:u,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:u,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(u){g.debug(`reportRoomEngineEvent Report failed: ${r(u)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},Ap=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:r,InnerEvent:{LOGOUT:g,DESTROY:u}}=s;xD.init(s),_C.init(s),r.subscribeInnerEvent(g,this._reset,this),r.subscribeInnerEvent(u,this._dispose,this)}_reset(){_C.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:r,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(r,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),_C.dispose()}};let Zm=gr.STANDARD,vB=[];Zm=gr.STANDARD,vB=[lh,dC,CC,hC,Rc,ZT,MB,Ap,OE,wi,zn,VT,Jm,LD,$I];function RB(s,r){const{operationType:g,memberInfoList:u,operatorInfo:E}=s||{};let m={};if(Rs(u)?Rs(E)||(m=E):g!==Tg.JOINED&&g!==Tg.KICKED&&g!==Tg.ADMIN_SET&&g!==Tg.ADMIN_CANCELED||(m=Object.assign({},u[0])),!Rs(m)){const{nick:D="",avatar:M=""}=m;r.nick=D,r.avatar=M}}const ep=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Zc(s?.type,s?.payload),payload:s?.payload||null,type:s?.type||"",isRevoked:s?.isRevoked||!1,cloudCustomData:s?.cloudCustomData||"",onlineOnlyFlag:s?._onlineOnlyFlag||!1,nick:s?.nick||"",nameCard:s?.nameCard||"",version:s?.version||0,isPeerRead:s?.isPeerRead||!1,revoker:s?.revoker||null});var tp=Object.freeze({__proto__:null,ChatError:gs,WorkflowManager:ws,buildAndSendPacket:gg,buildLastMessage:ep,get builtInPlugins(){return vB},checkBusinessCapabilityBits:tn,deepMerge:Cd,getCurrentUserID:ir,getErrorMessage:rs,getMessagePreviewText:Zc,isC2CConv:s=>c(s)&&s.slice(0,3)===ka.CONV_C2C,isCommunity:$r,isGroupConv:s=>c(s)&&s.slice(0,5)===ka.CONV_GROUP,isInternational:_l,isTopic:zc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=De.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ca,registerInterceptor:Mc,registerValidateConfig:Wc,requireAuth:ud,get sdkEdition(){return Zm},setGroupTipsUserInfo:RB,t:Lu,updateGroupAtInfo:(s,r)=>{const{CONV_AT_ME:g,CONV_AT_ALL:u,CONV_AT_ALL_AT_ME:E}=Uo;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:oA}=Uo,{groupID:EA,sequence:wA}=M;let kA=!1;return $r({groupID:EA})&&T.forEach(xA=>{xA.messageSequence===wA&&(xA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(xA.atTypeArray=[oA]),xA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(xA.atTypeArray=[oA],xA.__random=M.__random,xA.__sequence=M.__sequence),kA=!0)}),kA}(s,r))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(u)&&(m=[E]);const D={from:s.from,groupID:s.groupID,topicID:s.topicID,messageSequence:s.sequence,atTypeArray:m,__random:s.__random,__sequence:s.__sequence};r.push(D)},validateAndExecute:vr,validateParameters:uI});class gu{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return gu._instance||(gu._instance=new gu),gu._instance}static setInstance(r){gu._instance=r}installBuiltInPlugin(r){r&&this._installPlugin(r,this._builtInPlugins)}installExternalPlugin(r){r&&this._installPlugin(r,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(r,g){let u=[];u=C(r)?r:[r];const E=u.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?u.splice(E,1):[];u.forEach(D=>{this._isPluginInstalled(D.name)||(D&&vg(D.install)?(g.add(D.name),vg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(pr.getInstance().exposeApiForPlugin(),m)):D.install(pr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):vg(D)?(g.add(D.name),D(pr.getInstance().exposeApiForPlugin()),vg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(r){return this._builtInPlugins.has(r)||this._externalPlugins.has(r)}_isLoggedIn(){var r;return((r=De.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}}var wB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,r,g){const{emit:u=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!Rs(r)&&(Object.keys(r).forEach(D=>{m[D]=r[D]}),u&&De.notificationCenter.emitInnerEvent(ro.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),De.notificationCenter.emitInnerEvent(ro.CONVERSATION_UPDATED))}},ip=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(s){return this._groupMap.get(s)}updateGroup(s,r){const g=this._groupMap.get(s);g&&!Rs(r)&&Object.keys(r).forEach(u=>{g[u]=r[u]})}},op=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,r,g){var u;const{operation:E,updateUnreadCount:m=!0}=g,D=So(g,["operation","updateUnreadCount"]),M=[];for(const T of r){const P=(u=this._messagesByConversation.get(s))===null||u===void 0?void 0:u.get(T);if(!P)return!1;Object.keys(D).forEach(W=>{P[W]=D[W]}),M.push(P)}return this._emitMessageStoreOperationEvent(E,{conversationID:s,messageList:M,updateUnreadCount:m}),M}getMessagesByConversation(s){var r;return[...((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(s,r){const{conversationID:g}=r;zc(g)?De.notificationCenter.emitInnerEvent(Tu[s],r):De.notificationCenter.emitInnerEvent(s,r)}},rc=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(s){return this.userProfileMap.get(s)}getFriend(s){return this.friendMap.get(s)}},YD=Object.freeze({__proto__:null,conversationStore:wB,groupStore:ip,messageStore:op,userStore:rc});class pr{static getInstance(){return pr._instance||(pr._instance=new pr),pr._instance}static setInstance(r){pr._instance=r}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:De.notificationCenter.subscribeOuterEvent.bind(De.notificationCenter),off:De.notificationCenter.unSubscribeOuterEvent.bind(De.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:gu.getInstance().installExternalPlugin.bind(gu.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(r){De.ssoLog.debug("registerPlugin",r)}statKeyFeatureUsage(r){De.ssoLog.debug("statTUIKeyFeatures",r)}setLogLevel(r){De.ssoLog.debug("setLogLevel",r),De.ssoLog.setLogLevel(r)}setApplicationID(r){De.store.set("instance",{applicationID:r})}getApiMap(){return this._apiMap}setApiMap(r){this._apiMap=r}registerApi(r){const{common:{timeManager:g},utils:{safeStringify:u}}=De,{apiName:E,context:m,methodName:D=E,matcher:M}=r;this._apiHandlersMap[E]||(this._apiHandlersMap[E]=[]),this._apiHandlersMap[E].push({context:m,methodName:D,matcher:M}),this._apiMap[E]&&this._apiHandlersMap[E].length!==1||(this._apiMap[E]=(...T)=>{const P=g.getServerTimeMs();let W=0;E==="login"&&(W=4),KI.includes(E)&&De.ssoLog.debug(E,`${E} start params: ${u(T)}`),vr(D,T);const oA=this._apiHandlersMap[E];for(const EA of oA)if(!EA.matcher||EA.matcher(T))try{const wA=EA.context[EA.methodName].bind(EA.context)(...T);return this._isPromiseLike(wA)?this._handleAsyncResult(wA,E,W,P):(this._reportApiSuccessLog({result:wA,apiName:E,eventType:W,startTime:P}),wA)}catch(wA){throw De.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(r,g,u){const E=u||r;this._experimentalApiMap[r]=g[E].bind(g)}destroy(){return mA(this,void 0,void 0,function*(){var r,g;try{!((r=De.store.get("login"))===null||r===void 0)&&r.isLogin&&(yield this._apiMap.logout()),De.notificationCenter.emitInnerEvent(ro.DESTROY)}catch(u){console.debug("destroy error: ",u)}finally{De.notificationCenter.emitOuterEvent(Mr.SDK_DESTROY,{SDKAppID:(g=De.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ca.clear(),gu.getInstance().clear(),ws.getInstance().destroy(),De.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:ro,InnerEventSubType:De.notificationCenter.InnerEventSubType,OuterEvent:Mr,OuterConstant:Uo,SignalingEvent:qc,helper:Object.assign(Object.assign(Object.assign({},De.utils),De.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Mc,registerValidateConfig:Wc,checkBusinessCapabilityBits:tn,registerWorkflowStep:ws.getInstance().registerWorkflowStep.bind(ws.getInstance()),ChatError:gs}),apiMap:this._apiMap},De),{constants:Object.assign(Object.assign({},za),De.constants),common:Object.assign(Object.assign(Object.assign({},tp),De.common),{workflowManager:ws.getInstance()}),utils:De.utils,appStore:YD})}callExperimentalAPI(r,g){return De.ssoLog.debug(`callExperimentalAPI.${r} start params: ${De.utils.safeStringify(g)}`),this._experimentalApiMap[r]?this._experimentalApiMap[r](g):(De.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${r} not found, params: ${De.utils.safeStringify(g)}`),Promise.reject(new gs({code:da.INVALID_OPERATION})))}_isPromiseLike(r){return r!==null&&typeof r=="object"&&typeof r.then=="function"}_handleAsyncResult(r,g,u,E){return r.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:u,startTime:E}),m)).catch(m=>{throw De.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:De.common.timeManager.getServerTimeMs()-E,eventType:u,method:g,startTime:E}),m})}_reportApiSuccessLog(r){let{result:g,apiName:u,startTime:E,eventType:m}=r;const{timeManager:D}=De.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();u==="login"&&(E+=D.getTimeOffsetWithServer()),KI.includes(u)&&De.ssoLog.info(u,`${u} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class pR{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:r,store:g}=De;g.set("login",{isReady:!1}),pr.getInstance().registerApi({apiName:"login",context:this}),pr.getInstance().registerApi({apiName:"logout",context:this}),pr.getInstance().registerApi({apiName:"getLoginUser",context:this}),pr.getInstance().registerApi({apiName:"isReady",context:this}),pr.getInstance().registerApi({apiName:"getServerTime",context:this}),pr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),r.subscribeInnerEvent(ro.RECONNECTED,this._reLogin,this),De.notificationCenter.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}login(r){return mA(this,void 0,void 0,function*(){var g;const{sdkEdition:u}=De.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new gs({functionName:"login",code:da.REPEAT_LOGIN});const E=yield this._performLogin(r);this._validateAfterLogin(E),this._handleLoginSuccess(E),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const m=(g=De.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=De.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:u,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==da.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new gs({functionName:"login",code:m});throw console.error(D),D}})}_reLogin(){return mA(this,void 0,void 0,function*(){var r;try{if(!this._isLoginIn())return;const g=yield ku(this._customLoginInfo);if(g){const{instanceID:u,customStatus:E}=g;De.store.set("login",{statusInstanceId:u}),ws.getInstance().executeWorkflow(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:DE.USER_STATUS_ONLINE});const m=(r=De.channel.getSocketAdapter())===null||r===void 0?void 0:r.getId();De.ssoLog.info("reLogin",`socketId:${m} instanceId:${u}`)}}catch(g){console.warn(g)}})}logout(){return mA(this,arguments,void 0,function*(r=ra.USER_INITIATED){const{ssoLog:g}=De;g.debug("logout",`logout start logoutReason: ${r}`);try{yield this._performLogout(r),g.info("logout","logout success"),De.ssoLog.uploadSSOLogData()}catch(u){const{errorCode:E}=u;throw new gs({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?ir():""}isReady(){var r;return(r=De.store.get("login"))===null||r===void 0?void 0:r.isReady}setCustomLoginInfo(r=""){this._customLoginInfo=r}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),ws.getInstance().reset(),De.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:r}=De.common;return r.getServerTimeMs()}_updateAndEmitSDKReady(){De.store.set("login",{isReady:!0}),setTimeout(()=>{De.notificationCenter.emitOuterEvent(Mr.SDK_READY,{name:Mr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){De.store.set("login",{isReady:!1}),De.notificationCenter.emitOuterEvent(Mr.SDK_NOT_READY,{name:Mr.SDK_NOT_READY})}_validateAfterLogin(r){const g="login";if(!r)throw new gs({functionName:g,message:"login response is empty"});const{tinyID:u,a2Key:E}=r||{};if(!u)throw new gs({functionName:g,code:da.NO_TINYID});if(!E)throw new gs({functionName:g,code:da.NO_A2KEY})}_createRepeatLoginResponse(){var r;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:rs({code:"RepeatLogin",replacement1:(r=De.store.get("login"))===null||r===void 0?void 0:r.userId}),repeatLogin:!0}}}_performLogin(r){return mA(this,void 0,void 0,function*(){const{userID:g,userSig:u}=r;return De.store.set("login",{userId:g,userSig:u}),this._latestLoginAt=Date.now(),ku(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(r=>{setTimeout(()=>r(null),1)})})}_handleLoginSuccess(r){const{timeManager:g}=De.common,{helloInterval:u,timeStamp:E,customStatus:m,purchaseBits:D}=r,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=u||120,this._updateLoginStore(r),De.user.userStatus.setCustomStatus(m),ws.getInstance().executeWorkflow(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),De.common.taskScheduler.addTask({id:Gg,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(r){return function(g){return mA(this,void 0,void 0,function*(){const{logoutReason:u}=g,E="im_open_status.wslogout",m=De.common.generateProtocolData({servcmd:E,data:{wslogout_type:u,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield De.channel.sendPacket(m,{requestId:D})})}({logoutReason:r})}_updateLoginStore(r){const{a2Key:g,tinyID:u,instanceID:E,authKey:m}=r;De.store.set("login",{a2Key:g,tinyID:u,statusInstanceId:E,authKey:m,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const r="im_open_status.wshello",g=De.common.generateProtocolData({servcmd:r,data:{isWebUniapp:0}}),u=`${g.head.seq}${r}`;return De.channel.sendPacket(g,{requestId:u})}()}catch(r){De.ssoLog.warn("_sendOnlinePresenceRequest",` error:${r.message}`)}})}_isLoginIn(){var r;return((r=De.store.get("login"))===null||r===void 0?void 0:r.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){De.common.taskScheduler.removeTask(Gg),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",De.store.clear("login"),De.store.set("login",{isReady:!1}),De.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.RECONNECTED,this._reLogin,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}const mR={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},XT={logout:!0};class Th{constructor(){this.loginAction=new pR,this.kickedOutHandler=new bu,this.loginAction.init(),this.kickedOutHandler.init(),Wc({auth:XT,params:mR})}}var Kr,AE,qE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Kr||(Kr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(AE||(AE={})),function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_IMAGE="TIMImageElem",s.MSG_AUDIO="TIMSoundElem",s.MSG_FILE="TIMFileElem",s.MSG_VIDEO="TIMVideoFileElem",s.MSG_GRP_TIP="TIMGroupTipElem",s.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",s.MSG_MERGER="TIMRelayElem"}(qE||(qE={}));const VD={1:AE.MSG_PRIORITY_HIGH,2:AE.MSG_PRIORITY_NORMAL,3:AE.MSG_PRIORITY_LOW,4:AE.MSG_PRIORITY_LOWEST},JD=0,fR=1;var eE;(function(s){s.IN="in",s.OUT="out"})(eE||(eE={}));const yR=2,sp={};function cu(s){if(!s)return 0;if(sp[s]===void 0){const r=new Date,g=`3${r.getHours()}`.slice(-2),u=`0${r.getMinutes()}`.slice(-2),E=`0${r.getSeconds()}`.slice(-2);sp[s]=parseInt([g,u,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${sp[s]}`)}else sp[s]+=1;return sp[s]}class KE{constructor(r){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=AE.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=De.common.timeManager.getServerTimeSeconds()||0,senderTinyID:u,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:oA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:xA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:qA,checkResult:Ie=0,isPlaceMessage:le=0,messageFlagBits:bi,receiverList:ki,isSystemMessage:Ot=!1,status:Li=Yr.SUCCESS,revokeReason:cs="",conversationSubType:Re,clientSequence:St,protocol:UA="JSON",revokerInfo:ai={userID:"",nick:"",avatar:""},readReceiptInfo:_s={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Ui,groupProfile:Or,atUserList:Vi,flow:Ir,isRead:Nt=!1,priority:Gt=AE.MSG_PRIORITY_NORMAL,onlineOnlyFlag:iE=!1,nameCard:ln="",quoteInfo:Qo}=r;var Il;this.clientTime=g,this.senderTinyID=u||kA,this.needReadReceipt=m===!0||m===1,this.isSupportExtension=D===!0||D===1,this._cmConfigID=M,this.to=T,this.nick=W,this.avatar=oA,this.protocol=UA,this.random=Ui===void 0?(Il=Il||99999999,Math.round(Math.random()*Il)):Ui,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=xA,this.messageLifeTime=LA,this.from=P||null,this.sequence=qA||0,this.conversationType=OA||Kr.CONV_C2C,this.hasRiskContent=Ie>1,this.version=SA,this.isPlaceMessage=le,this.isRevoked=le===2||bi===8,this.isSystemMessage=Ot,this.readReceiptInfo=_s,this.revokeReason=cs,this.revokerInfo=ai,this._receiverList=ki,this.conversationSubType=Re,this.revoker=ai?.revoker||"",this.clientSequence=St||qA||0,this.status=Li,this.atUserList=Vi||[],this.flow=Ir,this.isRead=Nt,this.priority=Gt,this._onlineOnlyFlag=iE,this.nameCard=ln,this.quoteInfo=Qo,this.reInitialize(E),this._initC2CReadReceiptInfo(r),this._extractGroupInfo(Or)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(r){Array.isArray(r)?this._elements=r:this._elements=[r],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(r=>r.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(r){this._relayFlag=r}validateBeforeSend(){var r,g,u;return this._relayFlag?{isValid:!0}:((r=this._elements)===null||r===void 0?void 0:r.length)>0?(u=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||u===void 0?void 0:u.call(g):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(r){const{readReceiptSentByPeer:g,timestamp:u=0}=r;this.conversationType===Kr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=u)}_extractGroupInfo(r){if(!r)return;const{From_AccountNick:g,From_AccountHeadurl:u,MsgFrom_AccountExtraInfo:E,GroupType:m}=r,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof u=="string"&&(this.avatar=u),typeof D=="string"&&(this.nameCard=D),this.conversationSubType=m}reInitialize(r){r===this.from&&(this.isRead=!0),this._initSequence(r),this._concatConversationID(r),this.generateMessageID()}_concatConversationID(r){let g="";const u=this.conversationType;u!==Kr.CONV_SYSTEM?(g=u===Kr.CONV_C2C?r===this.from?this.to:this.from:this.to,this.conversationID=g?`${u}${g}`:null):this.conversationID=Kr.CONV_SYSTEM}_initSequence(r){this.clientSequence===0&&r&&(this.clientSequence=cu(r)),this.sequence===0&&this.conversationType===Kr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Kr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(r){this.isRead=r}}class Td{static parseServerPushElement(r){const{MsgContent:g={}}=r,{Data:u,Ext:E,Desc:m}=g;return new Td({data:u,description:m,extension:E})}constructor(r){this.type=qE.MSG_CUSTOM;const{data:g="",description:u="",extension:E=""}=r;this.content={data:g,description:u,extension:E}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{data:E,description:m,extension:D}=u;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:r}=De.utils,g=[this.content.data,this.content.description,this.content.extension].some(u=>!r(u));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class Nd{static parseServerPushElement(r){const{MsgContent:g={Text:""}}=r,{Text:u}=g;return new Nd({text:u})}constructor(r){this.type=wg.MSG_TEXT,this.content={text:r.text||""}}validateBeforeSend(){var r,g;return((g=(r=this.content)===null||r===void 0?void 0:r.text)===null||g===void 0?void 0:g.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(r){const{isMergerMessage:g=!1}=r||{},u=g?this.payload:this.content,{text:E}=u;return{MsgType:this.type,MsgContent:{Text:E}}}}var Xm=new class{constructor(){this._elementClassMap={[qE.MSG_CUSTOM]:Td,[qE.MSG_TEXT]:Nd}}init(){pr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),pr.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(s,r){var g;(g=r).prototype!==void 0&&"constructor"in g.prototype&&(this._elementClassMap[s]=r)}getElementClass(s){return this._elementClassMap[s]}createMessage(s){const{from:r,flow:g=eE.OUT}=s,{userId:u}=De.store.get("login")||{};this._isSendByCurrentInstance({from:r,flow:g,currentUser:u})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:r,flow:g,currentUser:u})&&(s.flow=eE.OUT);const E=Object.assign(Object.assign({},s),{currentUser:u});return new KE(E)}createCustomMessage(s){const r=ir(),g=this.createMessage(Object.assign(Object.assign({},s),{from:r})),u=this._elementClassMap[qE.MSG_CUSTOM];if(!g)return null;if(u){const E=new u(s.payload);g.setElement(E)}return g}createTextMessage(s){var r;if(!s)return null;const g=typeof s.payload=="string"?s.payload:((r=s?.payload)===null||r===void 0?void 0:r.text)||"",u=new Nd({text:g}),E=ir(),m=De.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(u),m}_updateWithSenderInfo(s){var r,g;const{nick:u,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=De.store.get("login")||{},P=rc.getUserProfile(M);return s.nick=u||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Yr.UNSENT,s.flow=eE.OUT,m===ka.CONV_GROUP&&(s.nameCard=(g=(r=ip.getGroup(D))===null||r===void 0?void 0:r.selfInfo)===null||g===void 0?void 0:g.nameCard),s}_isMultiEndpointSyncMessage(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===eE.IN}_isSendByCurrentInstance(s){const{from:r,flow:g,currentUser:u}=s;return r===u&&g===eE.OUT}};const DR={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},Gd={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},HD={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function SR(s,r){return Object.keys(r).forEach(g=>{const{range:u,defaultValue:E}=r[g];s[g]=u.includes(s[g])?s[g]:E}),s}function np(s){const r=s.lastIndexOf(".");return r===-1?s:s.slice(0,r)}function MR(s){const{androidInfo:r={},androidOPPOChannelID:g=""}=s,u=r.OPPOChannelID||g,E=SR(r,Gd),{sound:m="",FCMChannelID:D=""}=E,M=So(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:np(m),OPPOChannelID:u,GoogleChannelID:D})}function vR(s){const{apnsInfo:r={},ignoreIOSBadge:g=!1,disableVoipPush:u}=s,E=SR(r,HD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=So(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return n(u)||(W=u===!1?1:0),n(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function qD(s){return De.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:vR(s),AndroidInfo:MR(s)}:DR}function $m(s){const{From_AccountHeadurl:r,From_AccountNick:g,IsNeedReadReceipt:u,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:oA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:xA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:qA,InnerSdkCustomData:Ie}=s;let le,{From_Account:bi,To_Account:ki}=s;if(m===1){const Ot=ki;ki=bi,bi=Ot}if(qA){const{Reason:Ot,Revoker_Account:Li,Revoker_FromUin:cs}=qA;le={reason:Ot,revoker:Li,revokerFromUin:cs,userID:Li}}return{from:bi,avatar:r,nick:g,needReadReceipt:u===1,isSyncMessage:m,clientTime:M,messageLifeTime:T,random:P,sequence:W,time:oA,messageControlInfo:{excludedFromLastMessage:EA?.NoLastMsg===1,excludedFromUnreadCount:EA?.NoUnread===1},isSupportExtension:wA,to:ki,tinyID:kA,checkResult:xA,cloudCustomData:LA,revokerInfo:le,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:TC(D),onlineOnlyFlag:T===0,quoteInfo:rp(Ie)}}function Af(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:r,clientTime:u,random:E,sequence:m,time:D,to:M,elements:TC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function KD(s){const{ClientSeq:r,From_Account:g,GroupInfo:u,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:oA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:xA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:qA,InnerSdkCustomData:Ie}=s;let le,bi=AE.MSG_PRIORITY_NORMAL;if(Object.keys(VD).includes(String(s.MsgPriority))&&(bi=VD[s.MsgPriority]),SA){const{Reason:Ot,Revoker_Account:Li,Revoker_FromUin:cs}=SA;le={reason:Ot,revoker:Li,revokerFromUin:cs,userID:Li}}const ki=function(Ot){const Li=[];return Array.isArray(Ot)&&Ot.forEach(cs=>{cs.GroupAtAllFlag===JD?Li.push(cs.GroupAt_Account):cs.GroupAtAllFlag===fR&&Li.push(Uo.MSG_AT_ALL)}),Li}(OA);return{clientSequence:r,from:g,groupProfile:u,clientTime:m,priority:bi,random:D,sequence:M,time:T,messageControlInfo:{excludedFromLastMessage:P?.NoLastMsg===1,excludedFromUnreadCount:P?.NoUnread===1},isSupportExtension:W,tinyID:oA,cloudCustomData:EA,messageVersion:wA,checkResult:kA,needReadReceipt:xA,isPlaceMessage:LA,revokerInfo:le,atUserList:ki,elements:TC(E),to:$T(s),onlineOnlyFlag:qA===1,quoteInfo:rp(Ie)}}function $T(s){const{utils:{isEmpty:r},constants:{IS_TOPIC_MESSAGE:g}}=De,{ToGroupId:u,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||r(m)?u:m}function TC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const u=De.message.messageFactory.getElementClass(g.MsgType);return u?.parseServerPushElement(g)});const r=De.message.messageFactory.getElementClass(s.MsgType);return r?.parseServerPushElement(s)}function jD(s){const{From_Account:r,MsgBody:g,MsgClientTime:u,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:oA}=s;return{from:r,clientTime:u,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:TC(g),messageVersion:P,cloudCustomData:W,checkResult:oA}}function rp(s){const{utils:{isString:r,safeStringify:g},ssoLog:u}=De;if(!r(s))return null;try{const{messageID:E,messageTime:m,messageSequence:D}=JSON.parse(s).businessQuote;return{msgID:E,messageTime:m,messageSequence:D}}catch(E){return u.debug("_parseServerQuoteInfo",g(E)),null}}function ap({conversationUpdateFields:s,message:r}){const{conversationID:g,conversationType:u,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=r,T=M?"":ep(r),P=!D&&m===eE.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:u,subType:E,unreadCount:P?1:0,lastMessage:T})}function _B(s){return s.filter(r=>{const g=!Rs(r?._elements),u=r?.isPlaceMessage===1;return g||De.ssoLog.error("emptyMessageBody",`from:${r.from} to:${r.to} sequence:${r.sequence}`),g&&!u})}function TB(s){const{messageDataHandler:r}=De.message;return!r.isInMessageList(s)&&!r.isMessageSentByCurrentInstance(s)}var RR=Object.freeze({__proto__:null,autoIncrementIndex:cu,createAndroidPushInfo:MR,createApnsPushInfo:vR,createOfflinePushInfo:qD,filterValidMessages:_B,getAndroidSoundName:np,parseServerGroupMessage:KD,parseServerPushC2CModifyMessage:Af,parseServerPushGroupModifyMessage:jD,parseServerPushMessage:$m,parseServerPushMessageElement:TC,shouldStoreMessage:TB,updateConversationFields:ap});const{isPlainObject:wR}=De.utils;function gp(s,r={}){const{onlineUserOnly:g,messageControlInfo:u}=r;let{offlinePushInfo:E}=r;s.conversationType===Kr.CONV_C2C&&g===!0&&(E?E.disablePush=!0:E={disablePush:!0});let m="";typeof s.cloudCustomData=="string"&&s.cloudCustomData.length>0&&(m=s.cloudCustomData);const D=[];if(u&&wR(u)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=u;M===!0&&D.push("NoUnread"),T===!0&&D.push("NoLastMsg"),P===!0&&D.push("NoMsgCheck")}return{onlineUserOnly:g,cloudCustomData:m,messageControlInfo:D,offlinePushInfo:E}}function WD(s){const{webhookInfo:{disableCloudMessagePreHook:r=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!r&&!g)return;const u=[];return r&&u.push("ForbidBeforeSendMsgCallback"),g&&u.push("ForbidAfterSendMsgCallback"),u}function Nh(s,r){return mA(this,void 0,void 0,function*(){const g=s.conversationType===Kr.CONV_GROUP?function(E,m){var D;const M=gp(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return C(E._receiverList)&&E._receiverList.length>0&&(wA=E._receiverList,E._receiverList.length>50&&(wA=E._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(D=De.store.get("login"))===null||D===void 0?void 0:D.userId,GroupId:E.to,MsgBody:EA,CloudCustomData:P,Random:E.random,MsgPriority:E.priority,ClientSeq:E.clientSequence,GroupAtInfo:E._groupAtInfoList,OnlineOnlyFlag:T?1:0,MsgClientTime:E.clientTime,OfflinePushInfo:qD(oA),SendMsgControl:T?void 0:W,NeedReadReceipt:E.needReadReceipt===!0?1:0,To_Account:wA,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,ForbidCallbackControl:WD(m),InnerSdkCustomData:GB(E)}}}(s,r):function(E,m){var D;const M=gp(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=T===!0?0:void 0,wA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(D=De.store.get("login"))===null||D===void 0?void 0:D.userId,To_Account:E.to,MsgBody:wA,CloudCustomData:P,MsgSeq:E.sequence,MsgRandom:E.random,MsgLifeTime:EA,From_AccountNick:E.nick,From_AccountHeadurl:E.avatar,SendMsgControl:EA!==0?W:void 0,MsgClientTime:E.clientTime,IsNeedReadReceipt:E.needReadReceipt===!0?1:0,SupportMessageExtension:E.isSupportExtension===!0?1:0,IsRelayMsg:E._relayFlag===!0?1:0,CustomModerationConfigID:E._cmConfigID,OfflinePushInfo:qD(oA),ForbidCallbackControl:WD(m),InnerSdkCustomData:GB(E)}}}(s,r),u=yield gg(g);return u?{time:u.MsgTime,messageDropReason:u.MsgDropReason,sequence:u.MsgSeq}:null})}function Gh(s){return mA(this,void 0,void 0,function*(){const{from:r,to:g,version:u=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:r,To_Account:g,MsgVersion:u,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield gg({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:oA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:TC(oA),messageVersion:EA,cloudCustomData:wA}}})}function NB(s){return mA(this,void 0,void 0,function*(){const{to:r,version:g=0,sequence:u,cloudCustomData:E}=s,m={GroupId:r,MsgVersion:g,MsgSeq:u,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield gg({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:TC(M),messageVersion:T,cloudCustomData:P}}})}function bh(s){return mA(this,void 0,void 0,function*(){const{groupID:r,count:g,messageSequence:u,messageSequenceList:E,getType:m}=s,D={GroupId:r,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return u&&(D.ReqMsgSeq=u),C(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield gg({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function ef(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E,direction:m}=s;return gg({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:u,MsgKey:E,GetDirection:m}})})}function GB(s){if(De.utils.isObject(s.quoteInfo)){const{msgID:r,messageSequence:g,messageTime:u}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:r,messageSequence:g,messageTime:u}})}}var zD=Object.freeze({__proto__:null,createMessagePackOptions:gp,generateForbidCallbackControl:WD,getC2CRoamingMessagesByAnchor:ef,getGroupRoamingMessagesByAnchor:bh,getRoamingMessages:function(s){return mA(this,void 0,void 0,function*(){const{peerAccount:r,count:g,lastMessageTime:u,messageKey:E}=s;return(yield gg({servcmd:"openim.getroammsg",data:{Peer_Account:r,MaxCnt:g||15,LastMsgTime:u||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Gh,modifyGroupMessage:NB,sendMessage:Nh});const{isPlainObject:AN}=De.utils,{MSG_AUDIO:ZD,MSG_FILE:XD,MSG_IMAGE:_R,MSG_VIDEO:TR,MSG_MERGER:NR}=Uo;class tf{constructor(){this._sendProtocolMap=new Map}init(){pr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:r=>![ZD,XD,_R,TR,NR].includes(r[0].type)})}registerSendProtocol(r,g,u){this._sendProtocolMap.set(r,g.bind(u))}sendMessage(r,g){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:u,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=cr;if(!(r instanceof KE))throw new gs({code:da.MSG_INSTANCE_REQUIRED});const M=r.validateBeforeSend();if(!M.isValid){const{code:W,message:oA=""}=M.error||{};throw new gs({code:W,message:oA})}this._reportMessageSendQuality({name:u,message:r});let T=!1;const{messageDataHandler:P}=De.message||{};try{const{messageControlInfo:W}=g||{};let oA=null;P.addRandomOfSentMessage(r.random);const EA=Date.now(),wA=this._getSendProtocol(r);if(r.conversationType===Kr.CONV_C2C?(T=g?.onlineUserOnly===!0,oA=yield wA(r,g)):r.conversationType===Kr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(r),oA=yield wA(r,g)),oA){const{messageDropReason:kA,sequence:xA,time:LA}=oA;if(this._updateNickAndAvatarOfSentMessageByMe(r),kA&&this._logRateLimitInfo(r,xA,kA),this._reportMessageSendQuality({name:m,message:r}),this._reportMessageSendQuality({name:E,message:r,startTs:EA}),r.isResend===!0){const SA=P.findMessage(r.ID);SA&&(De.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return r.status=Yr.SUCCESS,r.time=LA,r.conversationType===Kr.CONV_GROUP&&(r.sequence=xA),T?r._onlineOnlyFlag=!0:(P.storeConversationMessage(r),this._applySentMessageControlInfo(r,W),this._emitOnlineMessageSent(r)),r.type===wg.MSG_STREAM?{code:0,data:{message:r,streamMessageID:oA.streamMessageID}}:{code:0,data:{message:r}}}}catch(W){r.status=Yr.FAIL,P.removeRandomOfSentMessage(r.random);let{errorCode:oA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(oA)&&(r.hasRiskContent=!0),T||this._isRejectedByRestApi(oA)||P.storeConversationMessage(r),this._reportMessageSendQuality({name:D,message:r,error:W}),new gs({code:oA,message:EA,data:{message:r},moreMessage:`type:${r.type} from:${r.from} to:${r.to}`})}})}_hasRiskContent(r){return r===80001||r===80004}_isRejectedByRestApi(r){return r>=10100&&r<=10200||r>=120001&&r<=13e4}_emitOnlineMessageSent(r){const g=r._isExcludedFromLastMessage?"":r,{conversationID:u,conversationType:E}=r,m=zc(u)?ro.TOPIC_NEW_MESSAGE:ro.NEW_MESSAGE;De.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:u,type:E,message:r,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(r,g){g&&AN(g)&&(g.excludedFromLastMessage===!0&&(r._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(r._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(r,g,u){const E=`from:${r.from} to:${r.to} sequence:${g} messageDropReason:${u}`;De.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(r){const{messageDataHandler:g}=De.message||{};let u=!1;const{conversationID:E}=r,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===r.nick&&M===r.avatar||(u=!0),u&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:r.nick,latestAvatar:r.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(r){return mA(this,void 0,void 0,function*(){var g,u,E;const{to:m,from:D}=r;let M=m,T=ip.getGroup(M);if($r({groupID:M})&&T?.isSupportTopic)throw new gs({code:da.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zc(m)&&([M]=m.split(na.TOPIC),T=ip.getGroup(M)),!T&&typeof((g=pr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield pr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(u=P?.data)===null||u===void 0?void 0:u.group)===null||E===void 0?void 0:E.type)===Uo.GRP_AVCHATROOM){const W=rs({code:da.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new gs({code:da.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(r){De.notificationCenter.emitInnerEvent(ro.QUALITY_STAT,{label:lI.MESSAGE_SEND_SUCCESS_RATE,data:r})}_getSendProtocol(r){return this._sendProtocolMap.get(r.type)||Nh}}var eN=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){De.notificationCenter.subscribeInnerEvent(ro.LOGOUT,this._reset,this),De.notificationCenter.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}get _messagesByConversation(){return op.getMessages()}storeConversationMessage(s,r=!1){if(an)return!0;const{conversationID:g}=s;if(!g||(this._messagesByConversation.has(g)||this._messagesByConversation.set(g,new Map),this._shouldSkipStoreMessage(s,r)))return!1;const u=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(u,s),this._updateLatestMessageMap(s),!0}_updateLatestMessageMap(s){const{conversationID:r}=s;s.flow==="out"?this._setLatestMsgSentByMe(r,s):r.startsWith("C2C")&&this._setLatestMsgSentByPeer(r,s)}_shouldSkipStoreMessage(s,r){const g=this._getUniqueIdOfMessage(s),u=this._messagesByConversation.get(s.conversationID);if(u?.has(g)){const E=u?.get(g);if(!r||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var r;const{conversationID:g=""}=s,u=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((r=this._messagesByConversation.get(g))===null||r===void 0||r.delete(u))}modifyConversationMessage(s,r){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const u=this._getUniqueIdOfMessage(r),E=this._getMessageFromLocalMessage(s,u);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=r,P=T>1;if(De.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,r)break;if(!r){const u=Array.from(this._sparseMessagesByConversation.values());for(const E of u)if(r=E.get(s)||null,r)break}return r}deleteConversationMessageList(s){this._messagesByConversation.has(s)&&(this._messagesByConversation.delete(s),this._latestMessageSentByMeMap.delete(s),this._latestMessageSentByPeerMap.delete(s)),this._sparseMessagesByConversation.has(s)&&this._sparseMessagesByConversation.delete(s)}revokeMessage({conversationID:s,sequence:r,random:g,revoker:u}){const E=this._messagesByConversation.get(s);let m=null;if(E){const D=Array.from(E.values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),m){const M=this._getUniqueIdOfMessage(m);return op.updateMessage(s,[M],{isRevoked:!0,revoker:u,operation:yc.revoke}),m}}if(this._sparseMessagesByConversation.has(s)){const D=Array.from(this._sparseMessagesByConversation.get(s).values());if(m=this._findMessageBySequenceAndRandom({messageList:D,random:g,sequence:r}),m)return m.isRevoked=!0,m.revoker=u,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:r,random:g}){for(let u=0;u0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return u}storeSparseMessageList(s){if(s.length===0)return;const{conversationID:r}=s[0],g=s.length;this._sparseMessagesByConversation.has(r)||this._sparseMessagesByConversation.set(r,new Map);const u=this._sparseMessagesByConversation.get(r);for(let E=0;E=0;u--)if(g[u].flow==="out"){this._setLatestMsgSentByMe(s,g[u]);break}}}_updateLatestMessageSentByPeer(s){var r;const g=Array.from(((r=this._messagesByConversation.get(s))===null||r===void 0?void 0:r.values())||[]);if(g.length!==0&&s.startsWith("C2C")){for(let u=g.length-1;u>=0;u--)if(g[u].flow==="in"){this._setLatestMsgSentByPeer(s,g[u]);break}}}_getUniqueIdOfMessage(s){const{from:r,to:g,random:u,sequence:E,time:m}=s;return`${r}-${g}-${u}-${E}-${m}`}_setLatestMsgSentByPeer(s,r){this._latestMessageSentByPeerMap.set(s,r)}_setLatestMsgSentByMe(s,r){this._latestMessageSentByMeMap.set(s,r)}getLatestMsgSentByPeer(s){return this._latestMessageSentByPeerMap.get(s)}getLatestMsgSentByMe(s){return this._latestMessageSentByMeMap.get(s)}addRandomOfSentMessage(s){this._randomOfSentMessageList.add(s)}removeRandomOfSentMessage(s){this._randomOfSentMessageList.delete(s)}updateNickAndAvatarOfSentMessage(s){const{conversationID:r="",latestAvatar:g,latestNick:u,isSentByMe:E=!0}=s,m=this._messagesByConversation.get(r);if(!m)return;const D=Array.from(m.values()),M=E?"out":"in";D.forEach(T=>{const{nick:P,avatar:W,flow:oA}=T;oA===M&&(P!==u&&(T.nick=u),W!==g&&(T.avatar=g))})}isInMessageList(s){var r;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const u=this._getUniqueIdOfMessage(s);return(r=this._messagesByConversation.get(g))===null||r===void 0?void 0:r.has(u)}isMessageSentByCurrentInstance(s){const{random:r}=s;return this._randomOfSentMessageList.has(r)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(s){const r=this._messagesByConversation.get(s);return r?[...r.values()]:[]}getSparseMessageList(s){const r=this._sparseMessagesByConversation.get(s);return r?[...r.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),De.notificationCenter.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),De.notificationCenter.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}};function of(s,r){const g=wB.getConversation(s);if(g?.lastMessage){const{lastMessage:u}=g,{lastTime:E,lastSequence:m,version:D}=u,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:oA}=r;E===M&&m===T&&D!==P&&(u.type=W[0].type,u.payload=W[0].content,u.messageForShow=Zc(u.type,u.payload),u.cloudCustomData=oA,u.version=P,wB.updateConversation(s,{lastMessage:u}))}}class GR{init(){pr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(r){return mA(this,void 0,void 0,function*(){const{to:g,payload:u,sequence:E,conversationType:m,random:D,time:M,from:T,type:P}=r;if(this._canModifyMessageElement(P)){const W=r?._elements||[];W.length>=1&&(W[0].type=P,W[0].content=u)}try{let W=null,oA=null;if(m===Kr.CONV_C2C?W=yield Gh(r):m===Kr.CONV_GROUP&&(W=yield NB(r)),W){let EA=`${m}${g}`;return g===ir()&&m===Kr.CONV_C2C&&(EA=`${m}${T}`),oA={conversationType:m,from:T,to:g,time:M,random:D,sequence:E,elements:W?.elements,cloudCustomData:W?.cloudCustomData,messageVersion:W?.messageVersion,conversationID:EA},this._handleModifyMessageSuccess(oA),{code:0,data:{message:r},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:oA}=W||{};throw new gs({functionName:"modifyMessage",code:oA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent(Mr.MESSAGE_MODIFIED,{name:Mr.MESSAGE_MODIFIED,data:[E]}),De.notificationCenter.emitInnerEvent(ro.MESSAGE_MODIFIED,{conversationID:g,message:E}),of(g,r)}_canModifyMessageElement(r){return[qE.MSG_TEXT,qE.MSG_CUSTOM,qE.MSG_LOCATION,qE.MSG_FACE].includes(r)}}class kh{init(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;ws.getInstance().registerWorkflowStep(Jt.RECEIVE_C2C_NEW_MESSAGE,Wt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),ws.getInstance().registerWorkflowStep(Jt.RECEIVE_C2C_NEW_MESSAGE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){ws.getInstance().executeWorkflow(Jt.RECEIVE_C2C_NEW_MESSAGE,r)}_handleC2CMessagePush(r){const g=r.data||{},{messageDataHandler:u}=De.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;u.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?u.isMessageSentByCurrentInstance(M)||E.push(M):TB(M)&&(u.storeConversationMessage(M)&&ap({conversationUpdateFields:m,message:M}),u.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Wt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(u)}_emitMessageEventsAfterSyncUnreadMessage(r){var g;const{messages:u=[]}=((g=r.result)===null||g===void 0?void 0:g[Wt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(u)}_emitMessageEvents(r){const g=r?.filter(E=>E?.isModified===!0)||[];g.length>0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const u=r?.filter(E=>!E?.isModified);u.length>0&&De.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:u})}_generateC2CMessage(r){const g=Kr.CONV_C2C,u=$m(r),E=De.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:eE.IN})),{elements:m}=u;return E.setElement(m),E}_updateMessageProfile(r){var g;const{messageDataHandler:u}=De.message||{},E=(g=De.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T=""}=r;if(m!==E){const P=u.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:oA}=P;n(D)||n(M)?(r.nick=c(W)?W:r.nick,r.avatar=c(oA)?oA:r.avatar):D===W&&M===oA||(u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=u.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(r){const{conversationID:g,nick:u,avatar:E}=r,m=wB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===u||wB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:u,avatar:E})})}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),De.notificationCenter.emitInnerEvent("ModifyMessageSuccess",r),of(g,r)}_handleC2CMessageModify(r){r.C2cMsgModNotifys.forEach(g=>{var u;const E=Kr.CONV_C2C;let m=Af(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((u=De.store.get("login"))===null||u===void 0?void 0:u.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;De.notificationCenter.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),De.notificationCenter.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),De.notificationCenter.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}class Lh{init(){const{notificationCenter:r}=De,{InnerEventSubType:g}=r;ws.getInstance().registerWorkflowStep(Jt.RECEIVE_GROUP_NEW_MESSAGE,Wt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),ws.getInstance().registerWorkflowStep(Jt.RECEIVE_GROUP_NEW_MESSAGE,Wt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(r){this._canExecuteReceiverNewMessageWorkFlow(r)&&ws.getInstance().executeWorkflow(Jt.RECEIVE_GROUP_NEW_MESSAGE,r)}_handleGroupMessagePush(r){const g=r.data||{},{messageDataHandler:u}=De.message,E=[],m=new Map,D=g?.GroupMsgArray;return D?.forEach(M=>{if(M.GroupInfo.NotVisible===1)return;const T=this._generateGroupMessage(M);this.updateMessageProfile(T);let P=T.isModified===1;u.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?u.isMessageSentByCurrentInstance(T)||E.push(T):TB(T)&&u.storeConversationMessage(T)&&(E.push(T),ap({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(r){var g;const{messages:u}=((g=r.result)===null||g===void 0?void 0:g[Wt.HANDLE_GROUP_NEW_MESSAGE])||{},E=u?.filter(D=>D?.isModified===!0)||[];E.length>0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=u?.filter(D=>!D?.isModified)||[];m.length>0&&De.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(r){const g=Kr.CONV_GROUP,u=KD(r),E=De.message.messageFactory.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:eE.IN})),{elements:m}=u;return E.setElement(m),E}updateMessageProfile(r){var g;const{messageDataHandler:u}=De.message||{},E=(g=De.store.get("login"))===null||g===void 0?void 0:g.userId,{from:m,nick:D,avatar:M,conversationID:T="",_elements:P}=r;if(m===E){const W=u.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||u.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===Uo.CONV_SYSTEM){const{operationType:W,memberInfoList:oA,operatorInfo:EA}=P;let wA={};if(Rs(oA)?Rs(EA)||(wA=EA):[Tg.JOINED,Tg.KICKED,Tg.ADMIN_SET,Tg.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},oA[0])),!Rs(wA)){const{nick:kA="",avatar:xA=""}=wA;r.nick=kA,r.avatar=xA}}}_updateMessageListDueToModify(r){const{conversationID:g}=r,{isUpdated:u,message:E}=De.message.messageDataHandler.modifyConversationMessage(g,r);u===!0&&De.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),of(g,r)}_handleGroupMessageModify(r){r.GroupMsgModNotifys.forEach(g=>{const u=Kr.CONV_GROUP;let E=jD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${u}${M}`;E=Object.assign({conversationType:u,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:r}=De,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:u}}=r;r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,u,this._handleGroupMessageModify,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(r){var g,u;const{GroupId:E,GroupType:m}=((u=(g=r?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||u===void 0?void 0:u.GroupInfo)||{},D=m===La.GRP_AVCHATROOM;return!(!ip.getGroup(E)&&D)}}var $D=new class{constructor(){this.c2cMessageReceiver=new kh,this.groupMessageReceiver=new Lh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const bR={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!(!s.startsWith("C2C")&&!s.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>function(r){var g;return typeof r?.text!="string"||typeof r.text=="string"&&((g=r?.text)===null||g===void 0?void 0:g.length)===0?"payload.text must be a string":!0}(s)}}},tN={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var iN=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){try{const{conversationID:r,count:g,direction:u,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=r.replace(ka.CONV_GROUP,""),P=[];let W=E;if(u===Kc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const oA=yield bh({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(oA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:xA}=oA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${u} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${xA}`,SA=[];for(let Ie=0;Ie=E),OA&&D&&this.completedHistoryConversations.add(r);const qA=_B(SA);return De.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:qA,invisibleSequenceList:xA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(r){const{errorCode:g,errorInfo:u}=r||{};throw new gs({code:g,message:u})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var r;const g=ka.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=Uo.MSG_GRP_TIP);const u=KD(s),E=Xm.createMessage(Object.assign(Object.assign({},u),{conversationType:g,flow:"in"}));return RB(((r=u.elements)===null||r===void 0?void 0:r.content)||{},E),E.setElement(u.elements),E}getC2CRoamingMessagesByAnchor(s){return mA(this,void 0,void 0,function*(){var r;try{const{conversationID:g,count:u,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?De.message.messageDataHandler.findMessage(E):null;if(T=EA?.time||0,E&&this._historyMessageListFetchAnchors.has(g)){const wA=this._historyMessageListFetchAnchors.get(g);T=wA.lastMessageTime,P=wA.messageKey}}const W=g.replace(ka.CONV_C2C,""),oA=yield ef({count:u,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(oA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:xA}=oA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:xA});const LA=[];for(let Ie=0;Ie{const{tag:E,value:m}=u;E&&E.indexOf(eS)>-1?g.profileCustomField.push({key:E,value:m}):bd.has(E)&&(g[bd.get(E)]=m)}),Object.assign(Object.assign({},sf),g)}parseProfileItem(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.Value})}),r}parseProfileList(s=[]){const r=[];return s.forEach(g=>{r.push({tag:g.Tag,value:g.ValueBytes})}),r}convertParamsToProfile(s){const r=[];return Object.keys(s).forEach(g=>{g!==tS&&r.push({tag:Yl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&C(s.profileCustomField)&&s.profileCustomField.forEach(g=>{r.push({tag:g.key,value:g.value})}),r}normalizeProfileFields(s){const r={},g=[];return s.forEach(u=>{const{tag:E,value:m}=u;if(E&&E.indexOf(eS)>-1&&g.push({key:E,value:m}),bd.has(E)&&m!==void 0){const D=bd.get(E);r[D]=m}}),g.length>0&&(r.profileCustomField=g),r}};const{generateProtocolData:LR}=De.common;function UR(s){return mA(this,void 0,void 0,function*(){const r="profile.portrait_get_all",g={From_Account:ir(),UserItem:[]};s.forEach(D=>{g.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:D})});const u=LR({servcmd:r,data:g}),E=`${u.head.seq}${r}`,m=yield De.channel.sendPacket(u,{requestId:E});if(m)return function(D){const{ActionStatus:M,ErrorCode:T,ErrorDisplay:P,ErrorInfo:W,UserProfileItem:oA}=D,EA=[];return oA.map(wA=>{const{To_Account:kA,CustomSequence:xA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:qA}=wA,Ie=tE.parseProfileItem(qA);EA.push({userId:kA,customSequence:xA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:Ie})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function jE(s){return rc.getFriendMap().has(s)}const{isEmpty:iS}=De.utils;class nf{constructor(){this._strangerProfileMap=new Map}init(){pr.getInstance().registerApi({apiName:"getMyProfile",context:this}),pr.getInstance().registerApi({apiName:"getUserProfile",context:this}),pr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=tE.createProfile.bind(tE);const{notificationCenter:r}=De;ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,Wt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const r=ir(),g=yield UR([r]);if(g){const u=this._handleProfileFormResponse(g)[0];return rc.getUserProfileMap().set(r,u),{code:0,data:u}}}catch(r){const{errorCode:g,errorInfo:u}=r;throw new gs({functionName:"getMyProfile",code:g,message:u})}})}getUserProfile(r){return mA(this,void 0,void 0,function*(){try{let{userIDList:g}=r;const{userIdListToRequest:u,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(u.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};u.length>kR&&(De.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),u.length=kR);const{data:m,error:D}=yield this._batchFetchUserProfiles(u),M=u.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!iS(D))throw D;if(C(m))return m.forEach(oA=>{jE(oA.userID)?rc.getUserProfileMap().set(oA.userID,oA):this._strangerProfileMap.set(oA.userID,oA)}),{code:0,data:m.concat(E),successLog:{message:`getUserProfile query:${M} success:${T} fail:${P} from cache:${E.length}`}}}catch(g){throw new gs(g)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const r=ir(),g=rc.getUserProfileMap().has(r);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(r){return mA(this,void 0,void 0,function*(){const g=ir(),u={};for(const m in r)r[m]!==void 0&&(u[m]=r[m]);const E=tE.convertParamsToProfile(u);try{yield function(P){return mA(this,void 0,void 0,function*(){const W="profile.portrait_set",oA=LR({servcmd:W,data:P}),EA=`${oA.head.seq}${W}`,wA=yield De.channel.sendPacket(oA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:xA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:xA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=rc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),u):tE.createProfile(g,E);const T=!rg(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),rc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${De.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new gs({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${De.utils.safeStringify(r)}`})}})}updateMyNickAndAvatar(r){return mA(this,void 0,void 0,function*(){const g=ir(),u=Date.now(),E=rc.getUserProfile(g);let m={};m=E?Object.assign(E,r):tE.createProfile(g,r),m.lastUpdatedTime=u,rc.getUserProfileMap().set(g,m)})}_onProfileDataModify(r){const g=function(m){const{Profile_Account:D,PushType:M,ProfileList:T}=m;return{userId:D,pushType:M,profileList:tE.parseProfileList(T)}}(r.ProfileDataMod[0]);if(iS(g))return;const{isProfileUpdated:u,profile:E}=this._handleProfileModified(g);u&&this._emitProfileUpdated(E)}_emitProfileUpdated(r){De.notificationCenter.emitInnerEvent(ro.PROFILE_UPDATE,{name:ro.PROFILE_UPDATE,data:[r]}),De.notificationCenter.emitOuterEvent(Mr.PROFILE_UPDATED,{name:Mr.PROFILE_UPDATED,data:[r]}),wB.updateConversation(`C2C${r?.userID}`,{userProfile:r})}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(r){const{userId:g,profileList:u}=r,E=rc.getUserProfile(g);if(!(ir()===g||jE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=tE.normalizeProfileFields(u),D=Object.keys(m).some(W=>W===tS?this._isCustomFieldChanged(E.profileCustomField,m.profileCustomField):E[W]!==m[W]);if(!D)return{isProfileUpdated:!1,profile:E};const M=Date.now(),T=Object.prototype.hasOwnProperty.call(m,tS)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return rc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(r){const g=[],u=[];return r.forEach(E=>{const m=rc.getUserProfileMap().has(E);jE(E)&&m?u.push(rc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?u.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:u}}_handleProfileFormResponse(r){const{userProfile:g}=r;if(!Array.isArray(g))return[];const u=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!iS(m.profileItem)),E=Date.now();return u.map(m=>{const D=tE.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(r){var g;if(!jE(r)){const{lastUpdatedTime:u=0}=this._strangerProfileMap.get(r)||{},E=((g=De.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-u<=E}return!1}_chunkUserIDList(r,g){return Array.from({length:Math.ceil(r.length/g)},(u,E)=>r.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(r){return mA(this,void 0,void 0,function*(){const g=[],u=[];let E={};return this._chunkUserIDList(r,100).forEach(m=>{g.push(UR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);C(M)&&u.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:u,error:E}})}_isCustomFieldChanged(r=[],g=[]){if(!C(g)||g.length===0)return!1;if(!C(r)||r.length===0)return!0;const u=new Map(r.map(E=>[E.key,E.value]));return g.some(E=>u.get(E.key)!==E.value)}_mergeProfileCustomField(r=[],g=[]){const u=C(r)?r.map(E=>Object.assign({},E)):[];return C(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=u.find(M=>M.key===E);D?D.value=m:u.push({key:E,value:m})}),u}_reset(){rc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const rf=new Map,oS=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,r=oS.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(u){return console.warn(u),""}}const{isEmpty:sN}=De.utils,{generateProtocolData:af}=De.common;function FR(s){return mA(this,void 0,void 0,function*(){const r="im_open_status.ws_get_user_status",g=af({servcmd:r,data:{To_Account:s}}),u=`${g.head.seq}${r}`,E=yield De.channel.sendPacket(g,{requestId:u});if(E)return function(m){const{ErrorCode:D,ErrorInfo:M,ErrorList:T=[],UserStatusList:P=[]}=m,W=P.map(EA=>{const{To_Account:wA,Status:kA,CustomStatus:xA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:cp(xA),onlineDevices:nN(LA)}}),oA=T.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:xA,ErrorInfo:LA}=EA;return{userID:sN(kA)?wA:kA,code:xA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:oA}}(E)})}function nN(s){const r=[];return s?.forEach(g=>{const{Platform:u,Status:E}=g;E==="Online"&&r.push(u)}),r}class rN{constructor(){this._customStatus=""}init(){const{notificationCenter:r}=De;pr.getInstance().registerApi({apiName:"getUserStatus",context:this}),pr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),pr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),pr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.USER_STATUS_UPDATE,this._onReOnline,this),r.subscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this)}setSelfStatus(r){return mA(this,void 0,void 0,function*(){const g=ir(),{customStatus:u}=r;try{return yield function(E){return mA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=af({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield De.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(u),this._customStatus=u,{code:0,data:{userID:g,statusType:Uh,customStatus:u},successLog:{message:`customStatus: ${u}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new gs({functionName:"setSelfStatus",code:m,message:D})}})}getUserStatus(r){return mA(this,void 0,void 0,function*(){const{userIDList:g=[]}=r;if(this._isOnlyMeInArray(g))return this._getMyStatus();const u=yield this._getUserStatus(g);return Object.assign(Object.assign({},u),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(r){const g=cp(r);this._customStatus=g}subscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=r;this._checkBusinessCapabilityBits("subscribeUserStatus");const u=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=De,P="im_open_status.ws_status_subscribe",W=af({servcmd:P,data:{To_Account:M}}),oA=`${W.head.seq}${P}`;return yield T.sendPacket(W,{requestId:oA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"subscribeUserStatus",code:u})}})}unsubscribeUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=r,u=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,u),m=yield function(M){return mA(this,void 0,void 0,function*(){const{channel:T}=De,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const oA=af({servcmd:P,data:W}),EA=`${oA.head.seq}${P}`;return yield T.sendPacket(oA,{requestId:EA})})}(E),D=this._parseResponse(m);return{code:0,data:{failureUserList:D},successLog:{message:`userID length:${g.length} failCount: ${D.length}`}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"unsubscribeUserStatus",code:u})}})}_onUserStatusUpdate(r){const{UserStatusList:g=[]}=r||{},u=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:cp(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(u)}_onReOnline(r){const g=cp(r.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const u={userID:ir(),statusType:Uh,customStatus:g};this._emitUserStatusUpdatedEvent(u)}_emitUserStatusUpdatedEvent(r){De.notificationCenter.emitOuterEvent(Mr.USER_STATUS_UPDATED,{name:Mr.USER_STATUS_UPDATED,data:r})}_sliceUserIDList(r,g){return r.slice(0,g)}_parseResponse(r){const{ErrorList:g=[]}=r;return g.map(u=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=u;return{userID:De.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(r){if(!De.store.get("commercialConfig").get(oN))throw new gs({functionName:r,code:da.NO_USE,replacement1:r})}_getMaxUserCount(r){const g=De.store.get("cloudConfig")||{},u={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:E,default:m}=u[r],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:ir(),statusType:Uh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(r){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),u=this._sliceUserIDList(r,g),E=yield FR(u),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:u}=g;throw new gs({functionName:"getUserStatus",code:u})}})}_isOnlyMeInArray(r){const g=ir();return r.length===1&&r.indexOf(g)>-1}_dispose(){const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.MESSAGE_PUSH,r.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this),r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const sS={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(s){for(const r of s){if(typeof r!="object")return"Each item in profileCustomField must be an object";if(typeof r?.key!="string")return"Each item.key in profileCustomField must be a string";if(!r?.key.startsWith(eS))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},aN={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class gN{constructor(){this.userProfile=new nf,this.userStatus=new rN,this.userProfile.init(),this.userStatus.init(),Wc({auth:aN,params:sS})}}function nS(s){const r=[];if(!c(s))return r;const g=s.length;if(g===0)return r;for(let u=g-1;u>=0;u--)s[u]==="1"&&r.push(2**(g-u-1));return r}var kd,NC,Ld;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(kd||(kd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(NC||(NC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Ld||(Ld={}));class rS{constructor(){this._name="SyncConversationHandler",this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:r}=De;ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Wt.CONVERSATION_RECOVER,this._syncConversationList,this),ws.getInstance().registerWorkflowStep(Jt.SYNC_SERVER_INFO_AFTER_LOGIN,Wt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),r.subscribeInnerEvent(ro.LOGOUT,this._reset,this),r.subscribeInnerEvent(ro.DESTROY,this._dispose,this),De.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===kd.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:r,utils:{safeStringify:g}}=De;r.debug("_syncConversationList","start");try{const u=yield this._pagingGetConversationList(!0);this._pagingStatus=kd.RESOLVED;const{conversationList:E=[]}=u||{};return r.info("_syncConversationList",`success count:${E.length}`),u}catch(u){const E=new gs(u);r.error("_syncConversationList",`fail ${g(u)}`,{error:E})}})}_pagingGetConversationList(r){return mA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=kd.PENDING;const u=yield function(oA){return mA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:xA,pagingPinnedStartIndex:LA}=oA;return gg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:xA}})})}({fromAccount:ir(),pagingTimeStamp:r?this._pagingTimeStamp:0,pagingStartIndex:r?this._pagingStartIndex:0,pagingPinnedTimeStamp:r?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:r?this._pagingPinnedStartIndex:0}),{CompleteFlag:E,SessionItem:m=[],TimeStamp:D,StartIndex:M,TopTimeStamp:T,TopStartIndex:P}=u||{};let W=[];if(E===1&&(this._pagingStatus=kd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),De.notificationCenter.emitInnerEvent(ro.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:W}),this._pagingTimeStamp=D,this._pagingStartIndex=M,this._pagingPinnedTimeStamp=T,this._pagingPinnedStartIndex=P,E!==1){const{conversationList:oA}=yield this._pagingGetConversationList(r);g.push(...oA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(r){const{utils:{isUndefined:g}}=De,u=this._convertConversationKey(r);return this._filterValidConversations(u).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===NC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(r){return r.filter(({type:g,userID:u})=>g===NC.C2C&&!function(E){let m;return E.startsWith(Uo.CONV_C2C)&&(m=E.replace(Uo.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(u)||g===2)}_assembleC2COption(r){var g,u,E,m,D,M,T,P;const W=this._createUserprofile(r);return{conversationID:`${Uo.CONV_C2C}${r.userID}`,type:Uo.CONV_C2C,lastMessage:{lastTime:r.time,lastSequence:r.sequence,fromAccount:r.lastC2CMsgFromAccount,type:!((g=r.lastMsg)===null||g===void 0)&&g.elements[0]?(u=r.lastMsg)===null||u===void 0?void 0:u.elements[0].type:null,payload:!((E=r.lastMsg)===null||E===void 0)&&E.elements[0]?this._amendLayersOverLimitProp(r.lastMsg.elements[0].content):null,cloudCustomData:((M=(D=(m=r.lastMsg)===null||m===void 0?void 0:m.elements)===null||D===void 0?void 0:D[0])===null||M===void 0?void 0:M.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Ld.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(r),revoker:((P=(T=r.lastMsg)===null||T===void 0?void 0:T.revokerInfo)===null||P===void 0?void 0:P.revoker)||null},unreadCount:0,userProfile:W,peerReadTime:r.peerReadTime,isPinned:r.isPinned===1,customData:r.customMark||"",markList:nS(r.standardMark),conversationGroupList:[],remark:r.friendRemark||"",messageRemindType:this._transMsgRemindType(r.messageRemindType)}}_createUserprofile(r){var g;const{userID:u,nick:E,peerAvatar:m}=r,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=De.user.userProfile)===null||g===void 0?void 0:g.createProfile(u,D)}_computeIsPeerRead(r){const g=ir(),{lastC2CMsgFromAccount:u,time:E,c2cPeerReadTime:m}=r;return u===g&&E<=m}_assembleGroupOption(r){var g,u,E,m,D;return{conversationID:`${Uo.CONV_GROUP}${r.groupID}`,type:Uo.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:r.time,lastSequence:r.sequence,fromAccount:r.msgGroupFromAccount},this._patchTypeAndPayload(r)),{cloudCustomData:((E=(u=(g=r.lastMsg)===null||g===void 0?void 0:g.elements)===null||u===void 0?void 0:u[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:r.lastMessageFlag===Ld.GROUP,onlineOnlyFlag:!1,nick:r.msgGroupFromNickName||"",nameCard:r.msgGroupFromCardName||"",revoker:((D=(m=r.lastMsg)===null||m===void 0?void 0:m.revokerInfo)===null||D===void 0?void 0:D.revoker)||null}),groupProfile:{groupID:r.groupID,name:r.groupNick,avatar:r.groupImage,type:r.groupType,nextMessageSeq:r.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(r),peerReadTime:0,isPinned:r.isPinned===1,version:0,customData:r.customMark||"",markList:nS(r.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(r.messageRemindType),subType:r.groupType}}_convertConversationKey(r){return r.map(g=>({type:g.Type,userID:g.To_Account,nick:g.C2cNick,peerAvatar:g.C2cImage,time:g.MsgTimeStamp,sequence:g.MsgSeq,lastC2CMsgFromAccount:g.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(g.LastMsg),lastMessageFlag:g.LastMsgFlags,c2cPeerReadTime:g.C2cPeerReadTime,peerReadTime:g.C2cPeerReadTime,friendRemark:g.C2cRemark,isPinned:g.TopFlags,standardMark:g.StandardMark,customMark:g.CustomMark,messageRemindType:g.MsgRecvOption,groupID:g.ToAccount,groupNick:g.GroupNick,groupImage:g.GroupImage,groupType:g.GroupType,nextMessageSeq:g.GroupNextMsgSeq,msgGroupFromAccount:g.MsgGroupFrom_Account,msgGroupFromNickName:g.MsgGroupFromNickName,msgGroupFromCardName:g.MsgGroupFromCardName,unreadCount:g.UnreadMsgCount,noUnreadCount:g.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(r){var g,u,E;const{utils:{isEmpty:m}}=De;if(m(r))return null;let D="",M=null;if(!m(r.GroupTips)){const{From_Account:T,GroupName:P}=((g=r.GroupTips)===null||g===void 0?void 0:g.GroupInfo)||{};D=Uo.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,r.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return r.MsgBody&&(D=(u=r.MsgBody[0])===null||u===void 0?void 0:u.MsgType,M=this._parseContent(D,r.MsgBody[0])),{event:r.Event,elements:[{type:D,content:M,cloudCustomData:r.CloudCustomData}],revokerInfo:{revoker:(E=r.RevokerInfo)===null||E===void 0?void 0:E.Revoker_Account}}}_parseContent(r,g){var u;if(!g)return g;const E=De.message.messageFactory.getElementClass(r);return E?(u=E.parseServerPushElement(g))===null||u===void 0?void 0:u.content:g}_amendLayersOverLimitProp(r){const{LayersOverLimit:g}=r;return So(r,["LayersOverLimit"]).layersOverLimit=g===1,r}_transMsgRemindType(r){let g="";return r===0?g=Uo.MSG_REMIND_ACPT_AND_NOTE:r===1?g=Uo.MSG_REMIND_DISCARD:r===2?g=Uo.MSG_REMIND_ACPT_NOT_NOTE:r===3&&(g=Uo.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(r){var g;const{utils:{isUndefined:u}}=De,{event:E,elements:m=[]}=r.lastMsg||{};return u(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:Uo.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(r){const{unreadCount:g=0,noUnreadCount:u=0}=r,E=g-u;return E>0?E:0}_reset(){this._pagingStatus=kd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:r}=De;r.unSubscribeInnerEvent(ro.LOGOUT,this._reset,this),r.unSubscribeInnerEvent(ro.DESTROY,this._dispose,this)}}class aS{constructor(){this.syncConversationHandler=new rS,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Xr}`);var gS={create:function(s){var r,g;const{SDKAppID:u,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:oA=""}=s;let EA=u;if(!function(kA){if(typeof kA=="number")return!0;const xA=Number(kA);return!Number.isNaN(xA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ca.has(EA))return Ca.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&ws.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(vB),P.isReady()&&((g=(r=ws.getInstance()).executeWorkflow)===null||g===void 0||g.call(r,Jt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function Ie(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Ie()+Ie()}${Ie()}${Ie()}${Ie()}${Ie()}${Ie()}${Ie()}`}();De.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Zm,version:Xr,proxyServer:oA}),ws.getInstance().init(),De.message=new AS,De.user=new gN,De.login=new Th,De.conversation=new aS,gu.getInstance().installBuiltInPlugin(vB),wA=pr.getInstance().exposeApiForClient(),wA._workflowManager=ws.getInstance(),wA._pluginManager=gu.getInstance();const{utils:{IS_WORKER_AVAILABLE:xA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=De,qA=`instanceID:${kA} SDKAppID:${u} platform:${VA} host:${SA()} isIOSWebView:${OA} workerAvailable:${xA} UserAgent:${LA}`;De.ssoLog.info("sdkConstruct",qA)}return Ca.set(EA,wA),wA},TSignaling:qc,EVENT:Mr,VERSION:Xr,TYPES:Uo};return gS})}(aY)),aY.exports}var fsA=msA();const ig=HW(fsA);var gY={exports:{}},ysA=gY.exports,T8;function DsA(){return T8||(T8=1,function(t,i){(function(n,c){t.exports=c()})(ysA,function(){function n(ce,Ve){if(!(ce instanceof Ve))throw new TypeError("Cannot call a class as a function")}function c(ce,Ve){for(var Dt=0;Dt"u"&&typeof uni.requireNativePlugin=="function",HA=RA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ZA=(RA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||tA||BA||IA||gA||RA),KA=L!==void 0&&(L.nativeModuleProxy!==void 0||L.ReactNative!==void 0),me=tA?qq:BA?tt:IA?swan:gA?my:lA?wx:RA?uni:{},ae=function(ce){if(N(ce)!=="object"||ce===null)return!1;var Ve=Object.getPrototypeOf(ce);if(Ve===null)return!0;for(var Dt=Ve;Object.getPrototypeOf(Dt)!==null;)Dt=Object.getPrototypeOf(Dt);return Ve===Dt};function gt(ce){if(ce==null)return!0;if(typeof ce=="boolean")return!1;if(typeof ce=="number")return ce===0;if(typeof ce=="string"||typeof ce=="function"||Array.isArray(ce))return ce.length===0;if(ce instanceof Error)return ce.message==="";if(ae(ce)){for(var Ve in ce)if(Object.prototype.hasOwnProperty.call(ce,Ve))return!1;return!0}return!1}var dt=function(){return I(function ce(){n(this,ce),this._n="WebRequest"},[{key:"request",value:function(ce,Ve){var Dt=this,ti="".concat(this._n,".request"),Pt=ce.downloadUrl||"",oi=(ce.method||"PUT").toUpperCase(),Ni=ce.url;if(console.log("%c tim-upload-plugin %c","background:#0abf5b; padding:1px; border-radius:3px; color: #fff","background:transparent","".concat(ti," URL:").concat(Ni)),ce.qs){var Co=function(Gi){var As=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Lo=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return gt(Gi)?"":ae(Gi)?Object.keys(Gi).map(function($i){var zt=encodeURIComponent($i)+Lo;return Array.isArray(Gi[$i])?Gi[$i].map(function(Ao){return zt+encodeURIComponent(Ao)}).join(As):zt+encodeURIComponent(Gi[$i])}).filter(Boolean).join(As):void 0}(ce.qs);Co&&(Ni+="".concat(Ni.indexOf("?")===-1?"?":"&").concat(Co))}var to=new XMLHttpRequest;to.open(oi,Ni,!0),to.responseType=ce.dataType||"text";var so=ce.headers||{};if(ce.uploadByIP&&(so=w(w({},so),{},{host:ce.uploadIP})),!gt(so))for(var ks in so)so.hasOwnProperty(ks)&&ks.toLowerCase()!=="content-length"&&ks.toLowerCase()!=="user-agent"&&ks.toLowerCase()!=="origin"&&ks.toLowerCase()!=="host"&&to.setRequestHeader(ks,so[ks]);return to.onload=function(){if(to.status===200)Ve(null,Dt._xhrRes(to,Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),so));else{if(ce.uploadIP&&ce.url.indexOf(ce.uploadIP)===-1)return ce.url=function(As,Lo){return As.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Lo,"/"))}(ce.url,ce.uploadIP),ce.uploadByIP=!0,Dt.request(ce,Ve);var Gi={code:to.status,message:JSON.stringify(to.responseText)};Ve(Gi,Dt._xhrRes(to,Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),so))}},to.onerror=function(Gi){var As=Dt._xhrBody(to,Pt,ce.uploadByIP&&ce.uploadIP),Lo={code:to.status,message:JSON.stringify(to.responseText)};As||to.statusText||to.status!==0||(Gi.message="CORS blocked or network error"),Ve(Lo,Dt._xhrRes(to,As)),Lo=null},ce.onProgress&&to.upload&&(to.upload.onprogress=function(Gi){var As=Gi.total,Lo=Gi.loaded,$i=Math.floor(100*Lo/As);ce.onProgress({total:As,loaded:Lo,percent:($i>=100?100:$i)/100})}),to.send(ce.resources),to}},{key:"_xhrRes",value:function(ce,Ve){var Dt={};return ce.getAllResponseHeaders().trim().split(` +`).forEach(function(ti){if(ti){var Pt=ti.indexOf(":"),oi=ti.substr(0,Pt).trim().toLowerCase(),Ni=ti.substr(Pt+1).trim();Dt[oi]=Ni}}),{statusCode:ce.status,statusMessage:ce.statusText,headers:Dt,data:Ve}}},{key:"_xhrBody",value:function(ce,Ve,Dt){return ce.status===200&&Ve?{location:Ve,uploadIP:Dt}:{response:ce.responseText,uploadIP:Dt}}}])}(),We=["unknown","image","video","audio","log"],lt=["name"],wt=function(){return I(function ce(){n(this,ce)},[{key:"request",value:function(ce,Ve){var Dt=this,ti=ce.resources,Pt=ti===void 0?"":ti,oi=ce.headers,Ni=oi===void 0?{}:oi,Co=ce.url,to=ce.downloadUrl,so=to===void 0?"":to,ks=Co,Gi=null,As=so.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Lo=decodeURIComponent(As[3]),$i=Lo.indexOf("?")>-1?Lo.split("?")[0]:Lo,zt={key:ce.fileKey?ce.fileKey:$i,success_action_status:200,"Content-Type":""},Ao={};if(HA){var Ri=Co.split("?sign=");if(Ri.length>1){var Es=Ri[1];ks="".concat(Ri[0],"?sign=").concat(encodeURIComponent("".concat(Es))),Ao.sign=decodeURIComponent(Es),Ao.signature=decodeURIComponent(Es)}}var VA={url:ks,header:Ni,name:"file",filePath:Pt,formData:w(w({},zt),Ao),timeout:ce.timeout||3e5};if(gA){var Ee=VA;Ee.name,VA=w(w({},function(Je,Ut){if(Je==null)return{};var ot,ut,$t=function(Ge,Xe){if(Ge==null)return{};var se={};for(var ve in Ge)if({}.hasOwnProperty.call(Ge,ve)){if(Xe.includes(ve))continue;se[ve]=Ge[ve]}return se}(Je,Ut);if(Object.getOwnPropertySymbols){var Zt=Object.getOwnPropertySymbols(Je);for(ut=0;ut=3e4&&(this.systemClockOffset=Co-Ni,Ve=!0)}else Math.floor(ce.statusCode/100)===5&&(Ve=!0)}return Ve}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(gY)),gY.exports}var SsA=DsA();const MsA=HW(SsA);/** * @vue/shared v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**//*! #__NO_SIDE_EFFECTS__ */function DW(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const Da={},H_=[],RQ=()=>{},XoA=()=>!1,$Y=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),SW=t=>t.startsWith("onUpdate:"),sI=Object.assign,MW=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},$oA=Object.prototype.hasOwnProperty,Wr=(t,i)=>$oA.call(t,i),Ms=Array.isArray,q_=t=>AV(t)==="[object Map]",Q6=t=>AV(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",Cm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",p6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),m6=Object.prototype.toString,AV=t=>m6.call(t),AsA=t=>AV(t).slice(8,-1),f6=t=>AV(t)==="[object Object]",vW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,jL=DW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),eV=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},esA=/-(\w)/g,sh=eV(t=>t.replace(esA,(i,r)=>r?r.toUpperCase():"")),tsA=/\B([A-Z])/g,rD=eV(t=>t.replace(tsA,"-$1").toLowerCase()),tV=eV(t=>t.charAt(0).toUpperCase()+t.slice(1)),Dj=eV(t=>t?`on${tV(t)}`:""),Wy=(t,i)=>!Object.is(t,i),X1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},p3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},isA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let g8;const iV=()=>g8||(g8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Br(t){if(Ms(t)){const i={};for(let r=0;r{if(r){const l=r.split(ssA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function qi(t){let i="";if(fg(t))i=t;else if(Ms(t))for(let r=0;r!!(t&&t.__v_isRef===!0),oi=t=>fg(t)?t:t==null?"":Ms(t)||Na(t)&&(t.toString===m6||!$s(t.toString))?S6(t)?oi(t.value):JSON.stringify(t,M6,2):String(t),M6=(t,i)=>S6(i)?M6(t,i.value):q_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,I],h)=>(r[Sj(l,h)+" =>"]=I,r),{})}:Q6(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>Sj(r))}:Cm(i)?Sj(i):Na(i)&&!Ms(i)&&!f6(i)?String(i):i,Sj=(t,i="")=>{var r;return Cm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/** +**//*! #__NO_SIDE_EFFECTS__ */function qW(t){const i=Object.create(null);for(const n of t.split(","))i[n]=1;return n=>n in i}const Da={},j_=[],TQ=()=>{},vsA=()=>!1,uV=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),KW=t=>t.startsWith("onUpdate:"),nI=Object.assign,jW=(t,i)=>{const n=t.indexOf(i);n>-1&&t.splice(n,1)},RsA=Object.prototype.hasOwnProperty,Wr=(t,i)=>RsA.call(t,i),vs=Array.isArray,W_=t=>EV(t)==="[object Map]",V6=t=>EV(t)==="[object Set]",$s=t=>typeof t=="function",fg=t=>typeof t=="string",Qm=t=>typeof t=="symbol",Na=t=>t!==null&&typeof t=="object",J6=t=>(Na(t)||$s(t))&&$s(t.then)&&$s(t.catch),H6=Object.prototype.toString,EV=t=>H6.call(t),wsA=t=>EV(t).slice(8,-1),q6=t=>EV(t)==="[object Object]",WW=t=>fg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,tU=qW(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),dV=t=>{const i=Object.create(null);return n=>i[n]||(i[n]=t(n))},_sA=/-(\w)/g,gh=dV(t=>t.replace(_sA,(i,n)=>n?n.toUpperCase():"")),TsA=/\B([A-Z])/g,cD=dV(t=>t.replace(TsA,"-$1").toLowerCase()),CV=dV(t=>t.charAt(0).toUpperCase()+t.slice(1)),Oj=dV(t=>t?`on${CV(t)}`:""),zy=(t,i)=>!Object.is(t,i),cY=(t,...i)=>{for(let n=0;n{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:c,value:n})},L3=t=>{const i=parseFloat(t);return isNaN(i)?t:i},NsA=t=>{const i=fg(t)?Number(t):NaN;return isNaN(i)?t:i};let N8;const hV=()=>N8||(N8=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function Cr(t){if(vs(t)){const i={};for(let n=0;n{if(n){const c=n.split(bsA);c.length>1&&(i[c[0].trim()]=c[1].trim())}}),i}function xi(t){let i="";if(fg(t))i=t;else if(vs(t))for(let n=0;n!!(t&&t.__v_isRef===!0),Kt=t=>fg(t)?t:t==null?"":vs(t)||Na(t)&&(t.toString===H6||!$s(t.toString))?W6(t)?Kt(t.value):JSON.stringify(t,z6,2):String(t),z6=(t,i)=>W6(i)?z6(t,i.value):W_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((n,[c,I],C)=>(n[Pj(c,C)+" =>"]=I,n),{})}:V6(i)?{[`Set(${i.size})`]:[...i.values()].map(n=>Pj(n))}:Qm(i)?Pj(i):Na(i)&&!vs(i)&&!q6(i)?String(i):i,Pj=(t,i="")=>{var n;return Qm(t)?`Symbol(${(n=t.description)!=null?n:i})`:t};/** * @vue/reactivity v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let iC;class lsA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=iC,!i&&iC&&(this.index=(iC.scopes||(iC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,r;if(this.scopes)for(i=0,r=this.scopes.length;i0)return;if(zL){let i=zL;for(zL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;WL;){let i=WL;for(WL=void 0;i;){const r=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(l){t||(t=l)}i=r}}if(t)throw t}function _6(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function T6(t){let i,r=t.depsTail,l=r;for(;l;){const I=l.prevDep;l.version===-1?(l===r&&(r=I),_W(l),usA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=I}t.deps=i,t.depsTail=r}function m3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(N6(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function N6(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===dU))return;t.globalVersion=dU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!m3(t)){t.flags&=-3;return}const r=_a,l=sB;_a=t,sB=!0;try{_6(t);const I=t.fn(t._value);(i.version===0||Wy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=r,sB=l,T6(t),t.flags&=-3}}function _W(t,i=!1){const{dep:r,prevSub:l,nextSub:I}=t;if(l&&(l.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let h=r.computed.deps;h;h=h.nextDep)_W(h,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function usA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let sB=!0;const G6=[];function aD(){G6.push(sB),sB=!1}function gD(){const t=G6.pop();sB=t===void 0?!0:t}function c8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=_a;_a=void 0;try{i()}finally{_a=r}}}let dU=0;class EsA{constructor(i,r){this.sub=i,this.dep=r,this.version=r.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class TW{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!sB||_a===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==_a)r=this.activeLink=new EsA(_a,this),_a.deps?(r.prevDep=_a.depsTail,_a.depsTail.nextDep=r,_a.depsTail=r):_a.deps=_a.depsTail=r,b6(r);else if(r.version===-1&&(r.version=this.version,r.nextDep)){const l=r.nextDep;l.prevDep=r.prevDep,r.prevDep&&(r.prevDep.nextDep=l),r.prevDep=_a.depsTail,r.nextDep=void 0,_a.depsTail.nextDep=r,_a.depsTail=r,_a.deps===r&&(_a.deps=l)}return r}trigger(i){this.version++,dU++,this.notify(i)}notify(i){RW();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{wW()}}}function b6(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let l=i.deps;l;l=l.nextDep)b6(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const CY=new WeakMap,Qv=Symbol(""),f3=Symbol(""),CU=Symbol("");function pu(t,i,r){if(sB&&_a){let l=CY.get(t);l||CY.set(t,l=new Map);let I=l.get(r);I||(l.set(r,I=new TW),I.map=l,I.key=r),I.track()}}function lm(t,i,r,l,I,h){const f=CY.get(t);if(!f){dU++;return}const w=_=>{_&&_.trigger()};if(RW(),i==="clear")f.forEach(w);else{const _=Ms(t),G=_&&vW(r);if(_&&r==="length"){const U=Number(l);f.forEach((j,lA)=>{(lA==="length"||lA===CU||!Cm(lA)&&lA>=U)&&w(j)})}else switch((r!==void 0||f.has(void 0))&&w(f.get(r)),G&&w(f.get(CU)),i){case"add":_?G&&w(f.get("length")):(w(f.get(Qv)),q_(t)&&w(f.get(f3)));break;case"delete":_||(w(f.get(Qv)),q_(t)&&w(f.get(f3)));break;case"set":q_(t)&&w(f.get(Qv));break}}wW()}function dsA(t,i){const r=CY.get(t);return r&&r.get(i)}function f_(t){const i=br(t);return i===t?i:(pu(i,"iterate",CU),th(t)?i:i.map(mu))}function oV(t){return pu(t=br(t),"iterate",CU),t}const CsA={__proto__:null,[Symbol.iterator](){return vj(this,Symbol.iterator,mu)},concat(...t){return f_(this).concat(...t.map(i=>Ms(i)?f_(i):i))},entries(){return vj(this,"entries",t=>(t[1]=mu(t[1]),t))},every(t,i){return im(this,"every",t,i,void 0,arguments)},filter(t,i){return im(this,"filter",t,i,r=>r.map(mu),arguments)},find(t,i){return im(this,"find",t,i,mu,arguments)},findIndex(t,i){return im(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return im(this,"findLast",t,i,mu,arguments)},findLastIndex(t,i){return im(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return im(this,"forEach",t,i,void 0,arguments)},includes(...t){return Rj(this,"includes",t)},indexOf(...t){return Rj(this,"indexOf",t)},join(t){return f_(this).join(t)},lastIndexOf(...t){return Rj(this,"lastIndexOf",t)},map(t,i){return im(this,"map",t,i,void 0,arguments)},pop(){return QL(this,"pop")},push(...t){return QL(this,"push",t)},reduce(t,...i){return l8(this,"reduce",t,i)},reduceRight(t,...i){return l8(this,"reduceRight",t,i)},shift(){return QL(this,"shift")},some(t,i){return im(this,"some",t,i,void 0,arguments)},splice(...t){return QL(this,"splice",t)},toReversed(){return f_(this).toReversed()},toSorted(t){return f_(this).toSorted(t)},toSpliced(...t){return f_(this).toSpliced(...t)},unshift(...t){return QL(this,"unshift",t)},values(){return vj(this,"values",mu)}};function vj(t,i,r){const l=oV(t),I=l[i]();return l!==t&&!th(t)&&(I._next=I.next,I.next=()=>{const h=I._next();return h.value&&(h.value=r(h.value)),h}),I}const hsA=Array.prototype;function im(t,i,r,l,I,h){const f=oV(t),w=f!==t&&!th(t),_=f[i];if(_!==hsA[i]){const j=_.apply(t,h);return w?mu(j):j}let G=r;f!==t&&(w?G=function(j,lA){return r.call(this,mu(j),lA,t)}:r.length>2&&(G=function(j,lA){return r.call(this,j,lA,t)}));const U=_.call(f,G,l);return w&&I?I(U):U}function l8(t,i,r,l){const I=oV(t);let h=r;return I!==t&&(th(t)?r.length>3&&(h=function(f,w,_){return r.call(this,f,w,_,t)}):h=function(f,w,_){return r.call(this,f,mu(w),_,t)}),I[i](h,...l)}function Rj(t,i,r){const l=br(t);pu(l,"iterate",CU);const I=l[i](...r);return(I===-1||I===!1)&&bW(r[0])?(r[0]=br(r[0]),l[i](...r)):I}function QL(t,i,r=[]){aD(),RW();const l=br(t)[i].apply(t,r);return wW(),gD(),l}const BsA=DW("__proto__,__v_isRef,__isVue"),k6=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(Cm));function QsA(t){Cm(t)||(t=String(t));const i=br(this);return pu(i,"has",t),i.hasOwnProperty(t)}class L6{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const I=this._isReadonly,h=this._isShallow;if(r==="__v_isReactive")return!I;if(r==="__v_isReadonly")return I;if(r==="__v_isShallow")return h;if(r==="__v_raw")return l===(I?h?wsA:P6:h?O6:F6).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const f=Ms(i);if(!I){let _;if(f&&(_=CsA[r]))return _;if(r==="hasOwnProperty")return QsA}const w=Reflect.get(i,r,iI(i)?i:l);return(Cm(r)?k6.has(r):BsA(r))||(I||pu(i,"get",r),h)?w:iI(w)?f&&vW(r)?w:w.value:Na(w)?I?PI(w):dv(w):w}}class U6 extends L6{constructor(i=!1){super(!1,i)}set(i,r,l,I){let h=i[r];if(!this._isShallow){const _=Tv(h);if(!th(l)&&!Tv(l)&&(h=br(h),l=br(l)),!Ms(i)&&iI(h)&&!iI(l))return _?!1:(h.value=l,!0)}const f=Ms(i)&&vW(r)?Number(r)t,_1=t=>Reflect.getPrototypeOf(t);function DsA(t,i,r){return function(...l){const I=this.__v_raw,h=br(I),f=q_(h),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,G=I[t](...l),U=r?y3:i?D3:mu;return!i&&pu(h,"iterate",_?f3:Qv),{next(){const{value:j,done:lA}=G.next();return lA?{value:j,done:lA}:{value:w?[U(j[0]),U(j[1])]:U(j),done:lA}},[Symbol.iterator](){return this}}}}function T1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function SsA(t,i){const r={get(I){const h=this.__v_raw,f=br(h),w=br(I);t||(Wy(I,w)&&pu(f,"get",I),pu(f,"get",w));const{has:_}=_1(f),G=i?y3:t?D3:mu;if(_.call(f,I))return G(h.get(I));if(_.call(f,w))return G(h.get(w));h!==f&&h.get(I)},get size(){const I=this.__v_raw;return!t&&pu(br(I),"iterate",Qv),Reflect.get(I,"size",I)},has(I){const h=this.__v_raw,f=br(h),w=br(I);return t||(Wy(I,w)&&pu(f,"has",I),pu(f,"has",w)),I===w?h.has(I):h.has(I)||h.has(w)},forEach(I,h){const f=this,w=f.__v_raw,_=br(w),G=i?y3:t?D3:mu;return!t&&pu(_,"iterate",Qv),w.forEach((U,j)=>I.call(h,G(U),G(j),f))}};return sI(r,t?{add:T1("add"),set:T1("set"),delete:T1("delete"),clear:T1("clear")}:{add(I){!i&&!th(I)&&!Tv(I)&&(I=br(I));const h=br(this);return _1(h).has.call(h,I)||(h.add(I),lm(h,"add",I,I)),this},set(I,h){!i&&!th(h)&&!Tv(h)&&(h=br(h));const f=br(this),{has:w,get:_}=_1(f);let G=w.call(f,I);G||(I=br(I),G=w.call(f,I));const U=_.call(f,I);return f.set(I,h),G?Wy(h,U)&&lm(f,"set",I,h):lm(f,"add",I,h),this},delete(I){const h=br(this),{has:f,get:w}=_1(h);let _=f.call(h,I);_||(I=br(I),_=f.call(h,I)),w&&w.call(h,I);const G=h.delete(I);return _&&lm(h,"delete",I,void 0),G},clear(){const I=br(this),h=I.size!==0,f=I.clear();return h&&lm(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{r[I]=DsA(I,t,i)}),r}function NW(t,i){const r=SsA(t,i);return(l,I,h)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?l:Reflect.get(Wr(r,I)&&I in l?r:l,I,h)}const MsA={get:NW(!1,!1)},vsA={get:NW(!1,!0)},RsA={get:NW(!0,!1)};const F6=new WeakMap,O6=new WeakMap,P6=new WeakMap,wsA=new WeakMap;function _sA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function TsA(t){return t.__v_skip||!Object.isExtensible(t)?0:_sA(AsA(t))}function dv(t){return Tv(t)?t:GW(t,!1,msA,MsA,F6)}function NsA(t){return GW(t,!1,ysA,vsA,O6)}function PI(t){return GW(t,!0,fsA,RsA,P6)}function GW(t,i,r,l,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const h=I.get(t);if(h)return h;const f=TsA(t);if(f===0)return t;const w=new Proxy(t,f===2?l:r);return I.set(t,w),w}function K_(t){return Tv(t)?K_(t.__v_raw):!!(t&&t.__v_isReactive)}function Tv(t){return!!(t&&t.__v_isReadonly)}function th(t){return!!(t&&t.__v_isShallow)}function bW(t){return t?!!t.__v_raw:!1}function br(t){const i=t&&t.__v_raw;return i?br(i):t}function GsA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&y6(t,"__v_skip",!0),t}const mu=t=>Na(t)?dv(t):t,D3=t=>Na(t)?PI(t):t;function iI(t){return t?t.__v_isRef===!0:!1}function ze(t){return bsA(t,!1)}function bsA(t,i){return iI(t)?t:new ksA(t,i)}class ksA{constructor(i,r){this.dep=new TW,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:br(i),this._value=r?i:mu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||th(i)||Tv(i);i=l?i:br(i),Wy(i,r)&&(this._rawValue=i,this._value=l?i:mu(i),this.dep.trigger())}}function aA(t){return iI(t)?t.value:t}const LsA={get:(t,i,r)=>i==="__v_raw"?t:aA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const I=t[i];return iI(I)&&!iI(r)?(I.value=r,!0):Reflect.set(t,i,r,l)}};function x6(t){return K_(t)?t:new Proxy(t,LsA)}function Gs(t){const i=Ms(t)?new Array(t.length):{};for(const r in t)i[r]=Y6(t,r);return i}class UsA{constructor(i,r,l){this._object=i,this._key=r,this._defaultValue=l,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return dsA(br(this._object),this._key)}}class FsA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function wj(t,i,r){return iI(t)?t:$s(t)?new FsA(t):Na(t)&&arguments.length>1?Y6(t,i,r):ze(t)}function Y6(t,i,r){const l=t[i];return iI(l)?l:new UsA(t,i,r)}class OsA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new TW(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=dU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return w6(this,!0),!0}get value(){const i=this.dep.track();return N6(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function PsA(t,i,r=!1){let l,I;return $s(t)?l=t:(l=t.get,I=t.set),new OsA(l,I,r)}const N1={},hY=new WeakMap;let av;function xsA(t,i=!1,r=av){if(r){let l=hY.get(r);l||hY.set(r,l=[]),l.push(t)}}function YsA(t,i,r=Da){const{immediate:l,deep:I,once:h,scheduler:f,augmentJob:w,call:_}=r,G=Ce=>I?Ce:th(Ce)||I===!1||I===0?Im(Ce,1):Im(Ce);let U,j,lA,sA,mA=!1,IA=!1;if(iI(t)?(j=()=>t.value,mA=th(t)):K_(t)?(j=()=>G(t),mA=!0):Ms(t)?(IA=!0,mA=t.some(Ce=>K_(Ce)||th(Ce)),j=()=>t.map(Ce=>{if(iI(Ce))return Ce.value;if(K_(Ce))return G(Ce);if($s(Ce))return _?_(Ce,2):Ce()})):$s(t)?i?j=_?()=>_(t,2):t:j=()=>{if(lA){aD();try{lA()}finally{gD()}}const Ce=av;av=U;try{return _?_(t,3,[sA]):t(sA)}finally{av=Ce}}:j=RQ,i&&I){const Ce=j,xe=I===!0?1/0:I;j=()=>Im(Ce(),xe)}const cA=IsA(),TA=()=>{U.stop(),cA&&cA.active&&MW(cA.effects,U)};if(h&&i){const Ce=i;i=(...xe)=>{Ce(...xe),TA()}}let WA=IA?new Array(t.length).fill(N1):N1;const ue=Ce=>{if(!(!(U.flags&1)||!U.dirty&&!Ce))if(i){const xe=U.run();if(I||mA||(IA?xe.some((Qe,ut)=>Wy(Qe,WA[ut])):Wy(xe,WA))){lA&&lA();const Qe=av;av=U;try{const ut=[xe,WA===N1?void 0:IA&&WA[0]===N1?[]:WA,sA];_?_(i,3,ut):i(...ut),WA=xe}finally{av=Qe}}}else U.run()};return w&&w(ue),U=new v6(j),U.scheduler=f?()=>f(ue,!1):ue,sA=Ce=>xsA(Ce,!1,U),lA=U.onStop=()=>{const Ce=hY.get(U);if(Ce){if(_)_(Ce,4);else for(const xe of Ce)xe();hY.delete(U)}},i?l?ue(!0):WA=U.run():f?f(ue.bind(null,!0),!0):U.run(),TA.pause=U.pause.bind(U),TA.resume=U.resume.bind(U),TA.stop=TA,TA}function Im(t,i=1/0,r){if(i<=0||!Na(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,iI(t))Im(t.value,i,r);else if(Ms(t))for(let l=0;l{Im(l,i,r)});else if(f6(t)){for(const l in t)Im(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&Im(t[l],i,r)}return t}/** +**/let iC;class PsA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=iC,!i&&iC&&(this.index=(iC.scopes||(iC.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let i,n;if(this.scopes)for(i=0,n=this.scopes.length;i0)return;if(oU){let i=oU;for(oU=void 0;i;){const n=i.next;i.next=void 0,i.flags&=-9,i=n}}let t;for(;iU;){let i=iU;for(iU=void 0;i;){const n=i.next;if(i.next=void 0,i.flags&=-9,i.flags&1)try{i.trigger()}catch(c){t||(t=c)}i=n}}if(t)throw t}function A9(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function e9(t){let i,n=t.depsTail,c=n;for(;c;){const I=c.prevDep;c.version===-1?(c===n&&(n=I),XW(c),YsA(c)):i=c,c.dep.activeLink=c.prevActiveLink,c.prevActiveLink=void 0,c=I}t.deps=i,t.depsTail=n}function U3(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(t9(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function t9(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===DU))return;t.globalVersion=DU;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!U3(t)){t.flags&=-3;return}const n=_a,c=aB;_a=t,aB=!0;try{A9(t);const I=t.fn(t._value);(i.version===0||zy(I,t._value))&&(t._value=I,i.version++)}catch(I){throw i.version++,I}finally{_a=n,aB=c,e9(t),t.flags&=-3}}function XW(t,i=!1){const{dep:n,prevSub:c,nextSub:I}=t;if(c&&(c.nextSub=I,t.prevSub=void 0),I&&(I.prevSub=c,t.nextSub=void 0),n.subs===t&&(n.subs=c,!c&&n.computed)){n.computed.flags&=-5;for(let C=n.computed.deps;C;C=C.nextDep)XW(C,!0)}!i&&!--n.sc&&n.map&&n.map.delete(n.key)}function YsA(t){const{prevDep:i,nextDep:n}=t;i&&(i.nextDep=n,t.prevDep=void 0),n&&(n.prevDep=i,t.nextDep=void 0)}let aB=!0;const i9=[];function lD(){i9.push(aB),aB=!1}function ID(){const t=i9.pop();aB=t===void 0?!0:t}function G8(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const n=_a;_a=void 0;try{i()}finally{_a=n}}}let DU=0;class VsA{constructor(i,n){this.sub=i,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class $W{constructor(i){this.computed=i,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0}track(i){if(!_a||!aB||_a===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==_a)n=this.activeLink=new VsA(_a,this),_a.deps?(n.prevDep=_a.depsTail,_a.depsTail.nextDep=n,_a.depsTail=n):_a.deps=_a.depsTail=n,o9(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const c=n.nextDep;c.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=c),n.prevDep=_a.depsTail,n.nextDep=void 0,_a.depsTail.nextDep=n,_a.depsTail=n,_a.deps===n&&(_a.deps=c)}return n}trigger(i){this.version++,DU++,this.notify(i)}notify(i){zW();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{ZW()}}}function o9(t){if(t.dep.sc++,t.sub.flags&4){const i=t.dep.computed;if(i&&!t.dep.subs){i.flags|=20;for(let c=i.deps;c;c=c.nextDep)o9(c)}const n=t.dep.subs;n!==t&&(t.prevSub=n,n&&(n.nextSub=t)),t.dep.subs=t}}const RY=new WeakMap,fv=Symbol(""),F3=Symbol(""),SU=Symbol("");function mu(t,i,n){if(aB&&_a){let c=RY.get(t);c||RY.set(t,c=new Map);let I=c.get(n);I||(c.set(n,I=new $W),I.map=c,I.key=n),I.track()}}function Em(t,i,n,c,I,C){const f=RY.get(t);if(!f){DU++;return}const w=_=>{_&&_.trigger()};if(zW(),i==="clear")f.forEach(w);else{const _=vs(t),N=_&&WW(n);if(_&&n==="length"){const L=Number(c);f.forEach((q,lA)=>{(lA==="length"||lA===SU||!Qm(lA)&&lA>=L)&&w(q)})}else switch((n!==void 0||f.has(void 0))&&w(f.get(n)),N&&w(f.get(SU)),i){case"add":_?N&&w(f.get("length")):(w(f.get(fv)),W_(t)&&w(f.get(F3)));break;case"delete":_||(w(f.get(fv)),W_(t)&&w(f.get(F3)));break;case"set":W_(t)&&w(f.get(fv));break}}ZW()}function JsA(t,i){const n=RY.get(t);return n&&n.get(i)}function S_(t){const i=br(t);return i===t?i:(mu(i,"iterate",SU),nh(t)?i:i.map(fu))}function BV(t){return mu(t=br(t),"iterate",SU),t}const HsA={__proto__:null,[Symbol.iterator](){return Yj(this,Symbol.iterator,fu)},concat(...t){return S_(this).concat(...t.map(i=>vs(i)?S_(i):i))},entries(){return Yj(this,"entries",t=>(t[1]=fu(t[1]),t))},every(t,i){return nm(this,"every",t,i,void 0,arguments)},filter(t,i){return nm(this,"filter",t,i,n=>n.map(fu),arguments)},find(t,i){return nm(this,"find",t,i,fu,arguments)},findIndex(t,i){return nm(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return nm(this,"findLast",t,i,fu,arguments)},findLastIndex(t,i){return nm(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return nm(this,"forEach",t,i,void 0,arguments)},includes(...t){return Vj(this,"includes",t)},indexOf(...t){return Vj(this,"indexOf",t)},join(t){return S_(this).join(t)},lastIndexOf(...t){return Vj(this,"lastIndexOf",t)},map(t,i){return nm(this,"map",t,i,void 0,arguments)},pop(){return SL(this,"pop")},push(...t){return SL(this,"push",t)},reduce(t,...i){return b8(this,"reduce",t,i)},reduceRight(t,...i){return b8(this,"reduceRight",t,i)},shift(){return SL(this,"shift")},some(t,i){return nm(this,"some",t,i,void 0,arguments)},splice(...t){return SL(this,"splice",t)},toReversed(){return S_(this).toReversed()},toSorted(t){return S_(this).toSorted(t)},toSpliced(...t){return S_(this).toSpliced(...t)},unshift(...t){return SL(this,"unshift",t)},values(){return Yj(this,"values",fu)}};function Yj(t,i,n){const c=BV(t),I=c[i]();return c!==t&&!nh(t)&&(I._next=I.next,I.next=()=>{const C=I._next();return C.value&&(C.value=n(C.value)),C}),I}const qsA=Array.prototype;function nm(t,i,n,c,I,C){const f=BV(t),w=f!==t&&!nh(t),_=f[i];if(_!==qsA[i]){const q=_.apply(t,C);return w?fu(q):q}let N=n;f!==t&&(w?N=function(q,lA){return n.call(this,fu(q),lA,t)}:n.length>2&&(N=function(q,lA){return n.call(this,q,lA,t)}));const L=_.call(f,N,c);return w&&I?I(L):L}function b8(t,i,n,c){const I=BV(t);let C=n;return I!==t&&(nh(t)?n.length>3&&(C=function(f,w,_){return n.call(this,f,w,_,t)}):C=function(f,w,_){return n.call(this,f,fu(w),_,t)}),I[i](C,...c)}function Vj(t,i,n){const c=br(t);mu(c,"iterate",SU);const I=c[i](...n);return(I===-1||I===!1)&&t4(n[0])?(n[0]=br(n[0]),c[i](...n)):I}function SL(t,i,n=[]){lD(),zW();const c=br(t)[i].apply(t,n);return ZW(),ID(),c}const KsA=qW("__proto__,__v_isRef,__isVue"),s9=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(Qm));function jsA(t){Qm(t)||(t=String(t));const i=br(this);return mu(i,"has",t),i.hasOwnProperty(t)}class n9{constructor(i=!1,n=!1){this._isReadonly=i,this._isShallow=n}get(i,n,c){if(n==="__v_skip")return i.__v_skip;const I=this._isReadonly,C=this._isShallow;if(n==="__v_isReactive")return!I;if(n==="__v_isReadonly")return I;if(n==="__v_isShallow")return C;if(n==="__v_raw")return c===(I?C?onA:c9:C?g9:a9).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(c)?i:void 0;const f=vs(i);if(!I){let _;if(f&&(_=HsA[n]))return _;if(n==="hasOwnProperty")return jsA}const w=Reflect.get(i,n,oI(i)?i:c);return(Qm(n)?s9.has(n):KsA(n))||(I||mu(i,"get",n),C)?w:oI(w)?f&&WW(n)?w:w.value:Na(w)?I?Ql(w):Bv(w):w}}class r9 extends n9{constructor(i=!1){super(!1,i)}set(i,n,c,I){let C=i[n];if(!this._isShallow){const _=bv(C);if(!nh(c)&&!bv(c)&&(C=br(C),c=br(c)),!vs(i)&&oI(C)&&!oI(c))return _?!1:(C.value=c,!0)}const f=vs(i)&&WW(n)?Number(n)t,P1=t=>Reflect.getPrototypeOf(t);function $sA(t,i,n){return function(...c){const I=this.__v_raw,C=br(I),f=W_(C),w=t==="entries"||t===Symbol.iterator&&f,_=t==="keys"&&f,N=I[t](...c),L=n?O3:i?P3:fu;return!i&&mu(C,"iterate",_?F3:fv),{next(){const{value:q,done:lA}=N.next();return lA?{value:q,done:lA}:{value:w?[L(q[0]),L(q[1])]:L(q),done:lA}},[Symbol.iterator](){return this}}}}function x1(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function AnA(t,i){const n={get(I){const C=this.__v_raw,f=br(C),w=br(I);t||(zy(I,w)&&mu(f,"get",I),mu(f,"get",w));const{has:_}=P1(f),N=i?O3:t?P3:fu;if(_.call(f,I))return N(C.get(I));if(_.call(f,w))return N(C.get(w));C!==f&&C.get(I)},get size(){const I=this.__v_raw;return!t&&mu(br(I),"iterate",fv),Reflect.get(I,"size",I)},has(I){const C=this.__v_raw,f=br(C),w=br(I);return t||(zy(I,w)&&mu(f,"has",I),mu(f,"has",w)),I===w?C.has(I):C.has(I)||C.has(w)},forEach(I,C){const f=this,w=f.__v_raw,_=br(w),N=i?O3:t?P3:fu;return!t&&mu(_,"iterate",fv),w.forEach((L,q)=>I.call(C,N(L),N(q),f))}};return nI(n,t?{add:x1("add"),set:x1("set"),delete:x1("delete"),clear:x1("clear")}:{add(I){!i&&!nh(I)&&!bv(I)&&(I=br(I));const C=br(this);return P1(C).has.call(C,I)||(C.add(I),Em(C,"add",I,I)),this},set(I,C){!i&&!nh(C)&&!bv(C)&&(C=br(C));const f=br(this),{has:w,get:_}=P1(f);let N=w.call(f,I);N||(I=br(I),N=w.call(f,I));const L=_.call(f,I);return f.set(I,C),N?zy(C,L)&&Em(f,"set",I,C):Em(f,"add",I,C),this},delete(I){const C=br(this),{has:f,get:w}=P1(C);let _=f.call(C,I);_||(I=br(I),_=f.call(C,I)),w&&w.call(C,I);const N=C.delete(I);return _&&Em(C,"delete",I,void 0),N},clear(){const I=br(this),C=I.size!==0,f=I.clear();return C&&Em(I,"clear",void 0,void 0),f}}),["keys","values","entries",Symbol.iterator].forEach(I=>{n[I]=$sA(I,t,i)}),n}function A4(t,i){const n=AnA(t,i);return(c,I,C)=>I==="__v_isReactive"?!t:I==="__v_isReadonly"?t:I==="__v_raw"?c:Reflect.get(Wr(n,I)&&I in c?n:c,I,C)}const enA={get:A4(!1,!1)},tnA={get:A4(!1,!0)},inA={get:A4(!0,!1)};const a9=new WeakMap,g9=new WeakMap,c9=new WeakMap,onA=new WeakMap;function snA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function nnA(t){return t.__v_skip||!Object.isExtensible(t)?0:snA(wsA(t))}function Bv(t){return bv(t)?t:e4(t,!1,zsA,enA,a9)}function rnA(t){return e4(t,!1,XsA,tnA,g9)}function Ql(t){return e4(t,!0,ZsA,inA,c9)}function e4(t,i,n,c,I){if(!Na(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const C=I.get(t);if(C)return C;const f=nnA(t);if(f===0)return t;const w=new Proxy(t,f===2?c:n);return I.set(t,w),w}function z_(t){return bv(t)?z_(t.__v_raw):!!(t&&t.__v_isReactive)}function bv(t){return!!(t&&t.__v_isReadonly)}function nh(t){return!!(t&&t.__v_isShallow)}function t4(t){return t?!!t.__v_raw:!1}function br(t){const i=t&&t.__v_raw;return i?br(i):t}function anA(t){return!Wr(t,"__v_skip")&&Object.isExtensible(t)&&K6(t,"__v_skip",!0),t}const fu=t=>Na(t)?Bv(t):t,P3=t=>Na(t)?Ql(t):t;function oI(t){return t?t.__v_isRef===!0:!1}function xe(t){return gnA(t,!1)}function gnA(t,i){return oI(t)?t:new cnA(t,i)}class cnA{constructor(i,n){this.dep=new $W,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?i:br(i),this._value=n?i:fu(i),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(i){const n=this._rawValue,c=this.__v_isShallow||nh(i)||bv(i);i=c?i:br(i),zy(i,n)&&(this._rawValue=i,this._value=c?i:fu(i),this.dep.trigger())}}function aA(t){return oI(t)?t.value:t}const lnA={get:(t,i,n)=>i==="__v_raw"?t:aA(Reflect.get(t,i,n)),set:(t,i,n,c)=>{const I=t[i];return oI(I)&&!oI(n)?(I.value=n,!0):Reflect.set(t,i,n,c)}};function l9(t){return z_(t)?t:new Proxy(t,lnA)}function Gs(t){const i=vs(t)?new Array(t.length):{};for(const n in t)i[n]=I9(t,n);return i}class InA{constructor(i,n,c){this._object=i,this._key=n,this._defaultValue=c,this.__v_isRef=!0,this._value=void 0}get value(){const i=this._object[this._key];return this._value=i===void 0?this._defaultValue:i}set value(i){this._object[this._key]=i}get dep(){return JsA(br(this._object),this._key)}}class unA{constructor(i){this._getter=i,this.__v_isRef=!0,this.__v_isReadonly=!0,this._value=void 0}get value(){return this._value=this._getter()}}function Jj(t,i,n){return oI(t)?t:$s(t)?new unA(t):Na(t)&&arguments.length>1?I9(t,i,n):xe(t)}function I9(t,i,n){const c=t[i];return oI(c)?c:new InA(t,i,n)}class EnA{constructor(i,n,c){this.fn=i,this.setter=n,this._value=void 0,this.dep=new $W(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=DU-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=c}notify(){if(this.flags|=16,!(this.flags&8)&&_a!==this)return $6(this,!0),!0}get value(){const i=this.dep.track();return t9(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function dnA(t,i,n=!1){let c,I;return $s(t)?c=t:(c=t.get,I=t.set),new EnA(c,I,n)}const Y1={},wY=new WeakMap;let lv;function CnA(t,i=!1,n=lv){if(n){let c=wY.get(n);c||wY.set(n,c=[]),c.push(t)}}function hnA(t,i,n=Da){const{immediate:c,deep:I,once:C,scheduler:f,augmentJob:w,call:_}=n,N=KA=>I?KA:nh(KA)||I===!1||I===0?dm(KA,1):dm(KA);let L,q,lA,tA,BA=!1,IA=!1;if(oI(t)?(q=()=>t.value,BA=nh(t)):z_(t)?(q=()=>N(t),BA=!0):vs(t)?(IA=!0,BA=t.some(KA=>z_(KA)||nh(KA)),q=()=>t.map(KA=>{if(oI(KA))return KA.value;if(z_(KA))return N(KA);if($s(KA))return _?_(KA,2):KA()})):$s(t)?i?q=_?()=>_(t,2):t:q=()=>{if(lA){lD();try{lA()}finally{ID()}}const KA=lv;lv=L;try{return _?_(t,3,[tA]):t(tA)}finally{lv=KA}}:q=TQ,i&&I){const KA=q,me=I===!0?1/0:I;q=()=>dm(KA(),me)}const gA=xsA(),RA=()=>{L.stop(),gA&&gA.active&&jW(gA.effects,L)};if(C&&i){const KA=i;i=(...me)=>{KA(...me),RA()}}let HA=IA?new Array(t.length).fill(Y1):Y1;const ZA=KA=>{if(!(!(L.flags&1)||!L.dirty&&!KA))if(i){const me=L.run();if(I||BA||(IA?me.some((ae,gt)=>zy(ae,HA[gt])):zy(me,HA))){lA&&lA();const ae=lv;lv=L;try{const gt=[me,HA===Y1?void 0:IA&&HA[0]===Y1?[]:HA,tA];_?_(i,3,gt):i(...gt),HA=me}finally{lv=ae}}}else L.run()};return w&&w(ZA),L=new Z6(q),L.scheduler=f?()=>f(ZA,!1):ZA,tA=KA=>CnA(KA,!1,L),lA=L.onStop=()=>{const KA=wY.get(L);if(KA){if(_)_(KA,4);else for(const me of KA)me();wY.delete(L)}},i?c?ZA(!0):HA=L.run():f?f(ZA.bind(null,!0),!0):L.run(),RA.pause=L.pause.bind(L),RA.resume=L.resume.bind(L),RA.stop=RA,RA}function dm(t,i=1/0,n){if(i<=0||!Na(t)||t.__v_skip||(n=n||new Set,n.has(t)))return t;if(n.add(t),i--,oI(t))dm(t.value,i,n);else if(vs(t))for(let c=0;c{dm(c,i,n)});else if(q6(t)){for(const c in t)dm(t[c],i,n);for(const c of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,c)&&dm(t[c],i,n)}return t}/** * @vue/runtime-core v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/function LU(t,i,r,l){try{return l?t(...l):t()}catch(I){sV(I,i,r)}}function rB(t,i,r,l){if($s(t)){const I=LU(t,i,r,l);return I&&p6(I)&&I.catch(h=>{sV(h,i,r)}),I}if(Ms(t)){const I=[];for(let h=0;h>>1,I=pE[l],h=hU(I);h=hU(r)?pE.push(t):pE.splice(JsA(i),0,t),t.flags|=1,J6()}}function J6(){BY||(BY=V6.then(q6))}function HsA(t){Ms(t)?j_.push(...t):Ly&&t.id===-1?Ly.splice(v_+1,0,t):t.flags&1||(j_.push(t),t.flags|=1),J6()}function I8(t,i,r=QQ+1){for(;rhU(r)-hU(l));if(j_.length=0,Ly){Ly.push(...i);return}for(Ly=i,v_=0;v_t.id==null?t.flags&2?-1:1/0:t.id;function q6(t){try{for(QQ=0;QQ{l._d&&M8(-1);const h=QY(i);let f;try{f=t(...I)}finally{QY(h),l._d&&M8(1)}return f};return l._n=!0,l._c=!0,l._d=!0,l}function Ta(t,i){if(tI===null)return t;const r=lV(tI),l=t.dirs||(t.dirs=[]);for(let I=0;It.__isTeleport,ZL=t=>t&&(t.disabled||t.disabled===""),u8=t=>t&&(t.defer||t.defer===""),E8=t=>typeof SVGElement<"u"&&t instanceof SVGElement,d8=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,S3=(t,i)=>{const r=t&&t.to;return fg(r)?i?i(r):null:r},W6={name:"Teleport",__isTeleport:!0,process(t,i,r,l,I,h,f,w,_,G){const{mc:U,pc:j,pbc:lA,o:{insert:sA,querySelector:mA,createText:IA,createComment:cA}}=G,TA=ZL(i.props);let{shapeFlag:WA,children:ue,dynamicChildren:Ce}=i;if(t==null){const xe=i.el=IA(""),Qe=i.anchor=IA("");sA(xe,r,l),sA(Qe,r,l);const ut=(je,Mt)=>{WA&16&&(I&&I.isCE&&(I.ce._teleportTarget=je),U(ue,je,Mt,I,h,f,w,_))},ft=()=>{const je=i.target=S3(i.props,mA),Mt=z6(je,i,IA,sA);je&&(f!=="svg"&&E8(je)?f="svg":f!=="mathml"&&d8(je)&&(f="mathml"),TA||(ut(je,Mt),$1(i,!1)))};TA&&(ut(r,Qe),$1(i,!0)),u8(i.props)?BE(()=>{ft(),i.el.__isMounted=!0},h):ft()}else{if(u8(i.props)&&!t.el.__isMounted){BE(()=>{W6.process(t,i,r,l,I,h,f,w,_,G),delete t.el.__isMounted},h);return}i.el=t.el,i.targetStart=t.targetStart;const xe=i.anchor=t.anchor,Qe=i.target=t.target,ut=i.targetAnchor=t.targetAnchor,ft=ZL(t.props),je=ft?r:Qe,Mt=ft?xe:ut;if(f==="svg"||E8(Qe)?f="svg":(f==="mathml"||d8(Qe))&&(f="mathml"),Ce?(lA(t.dynamicChildren,Ce,je,I,h,f,w),FW(t,i,!0)):_||j(t,i,je,Mt,I,h,f,w,!1),TA)ft?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):G1(i,r,xe,G,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const jt=i.target=S3(i.props,mA);jt&&G1(i,jt,null,G,0)}else ft&&G1(i,Qe,ut,G,1);$1(i,TA)}},remove(t,i,r,{um:l,o:{remove:I}},h){const{shapeFlag:f,children:w,anchor:_,targetStart:G,targetAnchor:U,target:j,props:lA}=t;if(j&&(I(G),I(U)),h&&I(_),f&16){const sA=h||!ZL(lA);for(let mA=0;mA{t.isMounted=!0}),LW(()=>{t.isUnmounting=!0}),t}const JC=[Function,Array],Z6={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:JC,onEnter:JC,onAfterEnter:JC,onEnterCancelled:JC,onBeforeLeave:JC,onLeave:JC,onAfterLeave:JC,onLeaveCancelled:JC,onBeforeAppear:JC,onAppear:JC,onAfterAppear:JC,onAppearCancelled:JC},X6=t=>{const i=t.subTree;return i.component?X6(i.component):i},WsA={name:"BaseTransition",props:Z6,setup(t,{slots:i}){const r=HnA(),l=jsA();return()=>{const I=i.default&&e9(i.default(),!0);if(!I||!I.length)return;const h=$6(I),f=br(t),{mode:w}=f;if(l.isLeaving)return _j(h);const _=C8(h);if(!_)return _j(h);let G=M3(_,f,l,r,j=>G=j);_.type!==mE&&BU(_,G);let U=r.subTree&&C8(r.subTree);if(U&&U.type!==mE&&!cv(_,U)&&X6(r).type!==mE){let j=M3(U,f,l,r);if(BU(U,j),w==="out-in"&&_.type!==mE)return l.isLeaving=!0,j.afterLeave=()=>{l.isLeaving=!1,r.job.flags&8||r.update(),delete j.afterLeave,U=void 0},_j(h);w==="in-out"&&_.type!==mE?j.delayLeave=(lA,sA,mA)=>{const IA=A9(l,U);IA[String(U.key)]=U,lA[Uy]=()=>{sA(),lA[Uy]=void 0,delete G.delayedLeave,U=void 0},G.delayedLeave=()=>{mA(),delete G.delayedLeave,U=void 0}}:U=void 0}else U&&(U=void 0);return h}}};function $6(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==mE){i=r;break}}return i}const zsA=WsA;function A9(t,i){const{leavingVNodes:r}=t;let l=r.get(i.type);return l||(l=Object.create(null),r.set(i.type,l)),l}function M3(t,i,r,l,I){const{appear:h,mode:f,persisted:w=!1,onBeforeEnter:_,onEnter:G,onAfterEnter:U,onEnterCancelled:j,onBeforeLeave:lA,onLeave:sA,onAfterLeave:mA,onLeaveCancelled:IA,onBeforeAppear:cA,onAppear:TA,onAfterAppear:WA,onAppearCancelled:ue}=i,Ce=String(t.key),xe=A9(r,t),Qe=(je,Mt)=>{je&&rB(je,l,9,Mt)},ut=(je,Mt)=>{const jt=Mt[1];Qe(je,Mt),Ms(je)?je.every(Et=>Et.length<=1)&&jt():je.length<=1&&jt()},ft={mode:f,persisted:w,beforeEnter(je){let Mt=_;if(!r.isMounted)if(h)Mt=cA||_;else return;je[Uy]&&je[Uy](!0);const jt=xe[Ce];jt&&cv(t,jt)&&jt.el[Uy]&&jt.el[Uy](),Qe(Mt,[je])},enter(je){let Mt=G,jt=U,Et=j;if(!r.isMounted)if(h)Mt=TA||G,jt=WA||U,Et=ue||j;else return;let re=!1;const qe=je[b1]=yt=>{re||(re=!0,yt?Qe(Et,[je]):Qe(jt,[je]),ft.delayedLeave&&ft.delayedLeave(),je[b1]=void 0)};Mt?ut(Mt,[je,qe]):qe()},leave(je,Mt){const jt=String(t.key);if(je[b1]&&je[b1](!0),r.isUnmounting)return Mt();Qe(lA,[je]);let Et=!1;const re=je[Uy]=qe=>{Et||(Et=!0,Mt(),qe?Qe(IA,[je]):Qe(mA,[je]),je[Uy]=void 0,xe[jt]===t&&delete xe[jt])};xe[jt]=t,sA?ut(sA,[je,re]):re()},clone(je){const Mt=M3(je,i,r,l,I);return I&&I(Mt),Mt}};return ft}function _j(t){if(rV(t))return t=eD(t),t.children=null,t}function C8(t){if(!rV(t))return j6(t.type)&&t.children?$6(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&$s(r.default))return r.default()}}function BU(t,i){t.shapeFlag&6&&t.component?(t.transition=i,BU(t.component.subTree,i)):t.shapeFlag&128?(t.ssContent.transition=i.clone(t.ssContent),t.ssFallback.transition=i.clone(t.ssFallback)):t.transition=i}function e9(t,i=!1,r){let l=[],I=0;for(let h=0;h1)for(let h=0;hpY(mA,i&&(Ms(i)?i[IA]:i),r,l,I));return}if(W_(l)&&!I){l.shapeFlag&512&&l.type.__asyncResolved&&l.component.subTree.component&&pY(t,i,r,l.component.subTree);return}const h=l.shapeFlag&4?lV(l.component):l.el,f=I?null:h,{i:w,r:_}=t,G=i&&i.r,U=w.refs===Da?w.refs={}:w.refs,j=w.setupState,lA=br(j),sA=j===Da?()=>!1:mA=>Wr(lA,mA);if(G!=null&&G!==_&&(fg(G)?(U[G]=null,sA(G)&&(j[G]=null)):iI(G)&&(G.value=null)),$s(_))LU(_,w,12,[f,U]);else{const mA=fg(_),IA=iI(_);if(mA||IA){const cA=()=>{if(t.f){const TA=mA?sA(_)?j[_]:U[_]:_.value;I?Ms(TA)&&MW(TA,h):Ms(TA)?TA.includes(h)||TA.push(h):mA?(U[_]=[h],sA(_)&&(j[_]=U[_])):(_.value=[h],t.k&&(U[t.k]=_.value))}else mA?(U[_]=f,sA(_)&&(j[_]=f)):IA&&(_.value=f,t.k&&(U[t.k]=f))};f?(cA.id=-1,BE(cA,r)):cA()}}}iV().requestIdleCallback;iV().cancelIdleCallback;const W_=t=>!!t.type.__asyncLoader,rV=t=>t.type.__isKeepAlive;function ZsA(t,i){i9(t,"a",i)}function XsA(t,i){i9(t,"da",i)}function i9(t,i,r=xI){const l=t.__wdc||(t.__wdc=()=>{let I=r;for(;I;){if(I.isDeactivated)return;I=I.parent}return t()});if(aV(i,l,r),r){let I=r.parent;for(;I&&I.parent;)rV(I.parent.vnode)&&$sA(l,i,r,I),I=I.parent}}function $sA(t,i,r,l){const I=aV(i,t,l,!0);Kg(()=>{MW(l[i],I)},r)}function aV(t,i,r=xI,l=!1){if(r){const I=r[t]||(r[t]=[]),h=i.__weh||(i.__weh=(...f)=>{aD();const w=UU(r),_=rB(i,r,t,f);return w(),gD(),_});return l?I.unshift(h):I.push(h),h}}const hm=t=>(i,r=xI)=>{(!mU||t==="sp")&&aV(t,(...l)=>i(...l),r)},AnA=hm("bm"),hc=hm("m"),enA=hm("bu"),tnA=hm("u"),LW=hm("bum"),Kg=hm("um"),inA=hm("sp"),onA=hm("rtg"),snA=hm("rtc");function nnA(t,i=xI){aV("ec",t,i)}const rnA="components";function anA(t,i){return cnA(rnA,t,!0,i)||t}const gnA=Symbol.for("v-ndc");function cnA(t,i,r=!0,l=!1){const I=tI||xI;if(I){const h=I.type;{const w=znA(h,!1);if(w&&(w===i||w===sh(i)||w===tV(sh(i))))return h}const f=h8(I[t]||h[t],i)||h8(I.appContext[t],i);return!f&&l?h:f}}function h8(t,i){return t&&(t[i]||t[sh(i)]||t[tV(sh(i))])}function yE(t,i,r,l){let I;const h=r,f=Ms(t);if(f||fg(t)){const w=f&&K_(t);let _=!1;w&&(_=!th(t),t=oV(t)),I=new Array(t.length);for(let G=0,U=t.length;Gi(w,_,void 0,h));else{const w=Object.keys(t);I=new Array(w.length);for(let _=0,G=w.length;_pU(i)?!(i.type===mE||i.type===vr&&!o9(i.children)):!0)?t:null}const v3=t=>t?y9(t)?lV(t):v3(t.parent):null,XL=sI(Object.create(null),{$:t=>t,$el:t=>t.vnode.el,$data:t=>t.data,$props:t=>t.props,$attrs:t=>t.attrs,$slots:t=>t.slots,$refs:t=>t.refs,$parent:t=>v3(t.parent),$root:t=>v3(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>n9(t),$forceUpdate:t=>t.f||(t.f=()=>{kW(t.update)}),$nextTick:t=>t.n||(t.n=Vy.bind(t.proxy)),$watch:t=>TnA.bind(t)}),Tj=(t,i)=>t!==Da&&!t.__isScriptSetup&&Wr(t,i),lnA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:l,data:I,props:h,accessCache:f,type:w,appContext:_}=t;let G;if(i[0]!=="$"){const sA=f[i];if(sA!==void 0)switch(sA){case 1:return l[i];case 2:return I[i];case 4:return r[i];case 3:return h[i]}else{if(Tj(l,i))return f[i]=1,l[i];if(I!==Da&&Wr(I,i))return f[i]=2,I[i];if((G=t.propsOptions[0])&&Wr(G,i))return f[i]=3,h[i];if(r!==Da&&Wr(r,i))return f[i]=4,r[i];R3&&(f[i]=0)}}const U=XL[i];let j,lA;if(U)return i==="$attrs"&&pu(t.attrs,"get",""),U(t);if((j=w.__cssModules)&&(j=j[i]))return j;if(r!==Da&&Wr(r,i))return f[i]=4,r[i];if(lA=_.config.globalProperties,Wr(lA,i))return lA[i]},set({_:t},i,r){const{data:l,setupState:I,ctx:h}=t;return Tj(I,i)?(I[i]=r,!0):l!==Da&&Wr(l,i)?(l[i]=r,!0):Wr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(h[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:l,appContext:I,propsOptions:h}},f){let w;return!!r[f]||t!==Da&&Wr(t,f)||Tj(i,f)||(w=h[0])&&Wr(w,f)||Wr(l,f)||Wr(XL,f)||Wr(I.config.globalProperties,f)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:Wr(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function B8(t){return Ms(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let R3=!0;function InA(t){const i=n9(t),r=t.proxy,l=t.ctx;R3=!1,i.beforeCreate&&Q8(i.beforeCreate,t,"bc");const{data:I,computed:h,methods:f,watch:w,provide:_,inject:G,created:U,beforeMount:j,mounted:lA,beforeUpdate:sA,updated:mA,activated:IA,deactivated:cA,beforeDestroy:TA,beforeUnmount:WA,destroyed:ue,unmounted:Ce,render:xe,renderTracked:Qe,renderTriggered:ut,errorCaptured:ft,serverPrefetch:je,expose:Mt,inheritAttrs:jt,components:Et,directives:re,filters:qe}=i;if(G&&unA(G,l,null),f)for(const Oe in f){const gt=f[Oe];$s(gt)&&(l[Oe]=gt.bind(r))}if(I){const Oe=I.call(r,r);Na(Oe)&&(t.data=dv(Oe))}if(R3=!0,h)for(const Oe in h){const gt=h[Oe],Fi=$s(gt)?gt.bind(r,r):$s(gt.get)?gt.get.bind(r,r):RQ,To=!$s(gt)&&$s(gt.set)?gt.set.bind(r):RQ,io=Tt({get:Fi,set:To});Object.defineProperty(l,Oe,{enumerable:!0,configurable:!0,get:()=>io.value,set:Eo=>io.value=Eo})}if(w)for(const Oe in w)s9(w[Oe],l,r,Oe);if(_){const Oe=$s(_)?_.call(r):_;Reflect.ownKeys(Oe).forEach(gt=>{cd(gt,Oe[gt])})}U&&Q8(U,t,"c");function Me(Oe,gt){Ms(gt)?gt.forEach(Fi=>Oe(Fi.bind(r))):gt&&Oe(gt.bind(r))}if(Me(AnA,j),Me(hc,lA),Me(enA,sA),Me(tnA,mA),Me(ZsA,IA),Me(XsA,cA),Me(nnA,ft),Me(snA,Qe),Me(onA,ut),Me(LW,WA),Me(Kg,Ce),Me(inA,je),Ms(Mt))if(Mt.length){const Oe=t.exposed||(t.exposed={});Mt.forEach(gt=>{Object.defineProperty(Oe,gt,{get:()=>r[gt],set:Fi=>r[gt]=Fi})})}else t.exposed||(t.exposed={});xe&&t.render===RQ&&(t.render=xe),jt!=null&&(t.inheritAttrs=jt),Et&&(t.components=Et),re&&(t.directives=re),je&&t9(t)}function unA(t,i,r=RQ){Ms(t)&&(t=w3(t));for(const l in t){const I=t[l];let h;Na(I)?"default"in I?h=JI(I.from||l,I.default,!0):h=JI(I.from||l):h=JI(I),iI(h)?Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>h.value,set:f=>h.value=f}):i[l]=h}}function Q8(t,i,r){rB(Ms(t)?t.map(l=>l.bind(i.proxy)):t.bind(i.proxy),i,r)}function s9(t,i,r,l){let I=l.includes(".")?B9(r,l):()=>r[l];if(fg(t)){const h=i[t];$s(h)&&Rr(I,h)}else if($s(t))Rr(I,t.bind(r));else if(Na(t))if(Ms(t))t.forEach(h=>s9(h,i,r,l));else{const h=$s(t.handler)?t.handler.bind(r):i[t.handler];$s(h)&&Rr(I,h,t)}}function n9(t){const i=t.type,{mixins:r,extends:l}=i,{mixins:I,optionsCache:h,config:{optionMergeStrategies:f}}=t.appContext,w=h.get(i);let _;return w?_=w:!I.length&&!r&&!l?_=i:(_={},I.length&&I.forEach(G=>mY(_,G,f,!0)),mY(_,i,f)),Na(i)&&h.set(i,_),_}function mY(t,i,r,l=!1){const{mixins:I,extends:h}=i;h&&mY(t,h,r,!0),I&&I.forEach(f=>mY(t,f,r,!0));for(const f in i)if(!(l&&f==="expose")){const w=EnA[f]||r&&r[f];t[f]=w?w(t[f],i[f]):i[f]}return t}const EnA={data:p8,props:m8,emits:m8,methods:wL,computed:wL,beforeCreate:dE,created:dE,beforeMount:dE,mounted:dE,beforeUpdate:dE,updated:dE,beforeDestroy:dE,beforeUnmount:dE,destroyed:dE,unmounted:dE,activated:dE,deactivated:dE,errorCaptured:dE,serverPrefetch:dE,components:wL,directives:wL,watch:CnA,provide:p8,inject:dnA};function p8(t,i){return i?t?function(){return sI($s(t)?t.call(this,this):t,$s(i)?i.call(this,this):i)}:i:t}function dnA(t,i){return wL(w3(t),w3(i))}function w3(t){if(Ms(t)){const i={};for(let r=0;r1)return r&&$s(i)?i.call(l&&l.proxy):i}}const a9={},g9=()=>Object.create(a9),c9=t=>Object.getPrototypeOf(t)===a9;function QnA(t,i,r,l=!1){const I={},h=g9();t.propsDefaults=Object.create(null),l9(t,i,I,h);for(const f in t.propsOptions[0])f in I||(I[f]=void 0);r?t.props=l?I:NsA(I):t.type.props?t.props=I:t.props=h,t.attrs=h}function pnA(t,i,r,l){const{props:I,attrs:h,vnode:{patchFlag:f}}=t,w=br(I),[_]=t.propsOptions;let G=!1;if((l||f>0)&&!(f&16)){if(f&8){const U=t.vnode.dynamicProps;for(let j=0;j{_=!0;const[lA,sA]=I9(j,i,!0);sI(f,lA),sA&&w.push(...sA)};!r&&i.mixins.length&&i.mixins.forEach(U),t.extends&&U(t.extends),t.mixins&&t.mixins.forEach(U)}if(!h&&!_)return Na(t)&&l.set(t,H_),H_;if(Ms(h))for(let U=0;Ut[0]==="_"||t==="$stable",UW=t=>Ms(t)?t.map(fQ):[fQ(t)],fnA=(t,i,r)=>{if(i._n)return i;const l=Li((...I)=>UW(i(...I)),r);return l._c=!1,l},E9=(t,i,r)=>{const l=t._ctx;for(const I in t){if(u9(I))continue;const h=t[I];if($s(h))i[I]=fnA(I,h,l);else if(h!=null){const f=UW(h);i[I]=()=>f}}},d9=(t,i)=>{const r=UW(i);t.slots.default=()=>r},C9=(t,i,r)=>{for(const l in i)(r||l!=="_")&&(t[l]=i[l])},ynA=(t,i,r)=>{const l=t.slots=g9();if(t.vnode.shapeFlag&32){const I=i._;I?(C9(l,i,r),r&&y6(l,"_",I,!0)):E9(i,l)}else i&&d9(t,i)},DnA=(t,i,r)=>{const{vnode:l,slots:I}=t;let h=!0,f=Da;if(l.shapeFlag&32){const w=i._;w?r&&w===1?h=!1:C9(I,i,r):(h=!i.$stable,E9(i,I)),f=i}else i&&(d9(t,i),f={default:1});if(h)for(const w in I)!u9(w)&&f[w]==null&&delete I[w]},BE=FnA;function SnA(t){return MnA(t)}function MnA(t,i){const r=iV();r.__VUE__=!0;const{insert:l,remove:I,patchProp:h,createElement:f,createText:w,createComment:_,setText:G,setElementText:U,parentNode:j,nextSibling:lA,setScopeId:sA=RQ,insertStaticContent:mA}=t,IA=(HA,ce,Ve,Ot=null,nt=null,It=null,ei=void 0,ti=null,be=!!ce.dynamicChildren)=>{if(HA===ce)return;HA&&!cv(HA,ce)&&(Ot=Ao(HA),Eo(HA,nt,It,!0),HA=null),ce.patchFlag===-2&&(be=!1,ce.dynamicChildren=null);const{type:Ze,ref:wt,shapeFlag:Nt}=ce;switch(Ze){case cV:cA(HA,ce,Ve,Ot);break;case mE:TA(HA,ce,Ve,Ot);break;case Gj:HA==null&&WA(ce,Ve,Ot,ei);break;case vr:Et(HA,ce,Ve,Ot,nt,It,ei,ti,be);break;default:Nt&1?xe(HA,ce,Ve,Ot,nt,It,ei,ti,be):Nt&6?re(HA,ce,Ve,Ot,nt,It,ei,ti,be):(Nt&64||Nt&128)&&Ze.process(HA,ce,Ve,Ot,nt,It,ei,ti,be,bi)}wt!=null&&nt&&pY(wt,HA&&HA.ref,It,ce||HA,!ce)},cA=(HA,ce,Ve,Ot)=>{if(HA==null)l(ce.el=w(ce.children),Ve,Ot);else{const nt=ce.el=HA.el;ce.children!==HA.children&&G(nt,ce.children)}},TA=(HA,ce,Ve,Ot)=>{HA==null?l(ce.el=_(ce.children||""),Ve,Ot):ce.el=HA.el},WA=(HA,ce,Ve,Ot)=>{[HA.el,HA.anchor]=mA(HA.children,ce,Ve,Ot,HA.el,HA.anchor)},ue=({el:HA,anchor:ce},Ve,Ot)=>{let nt;for(;HA&&HA!==ce;)nt=lA(HA),l(HA,Ve,Ot),HA=nt;l(ce,Ve,Ot)},Ce=({el:HA,anchor:ce})=>{let Ve;for(;HA&&HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},xe=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{ce.type==="svg"?ei="svg":ce.type==="math"&&(ei="mathml"),HA==null?Qe(ce,Ve,Ot,nt,It,ei,ti,be):je(HA,ce,nt,It,ei,ti,be)},Qe=(HA,ce,Ve,Ot,nt,It,ei,ti)=>{let be,Ze;const{props:wt,shapeFlag:Nt,transition:Oi,dirs:po}=HA;if(be=HA.el=f(HA.type,It,wt&&wt.is,wt),Nt&8?U(be,HA.children):Nt&16&&ft(HA.children,be,null,Ot,nt,Nj(HA,It),ei,ti),po&&ev(HA,null,Ot,"created"),ut(be,HA,HA.scopeId,ei,Ot),wt){for(const so in wt)so!=="value"&&!jL(so)&&h(be,so,null,wt[so],It,Ot);"value"in wt&&h(be,"value",null,wt.value,It),(Ze=wt.onVnodeBeforeMount)&&BQ(Ze,Ot,HA)}po&&ev(HA,null,Ot,"beforeMount");const No=vnA(nt,Oi);No&&Oi.beforeEnter(be),l(be,ce,Ve),((Ze=wt&&wt.onVnodeMounted)||No||po)&&BE(()=>{Ze&&BQ(Ze,Ot,HA),No&&Oi.enter(be),po&&ev(HA,null,Ot,"mounted")},nt)},ut=(HA,ce,Ve,Ot,nt)=>{if(Ve&&sA(HA,Ve),Ot)for(let It=0;It{for(let Ze=be;Ze{const ti=ce.el=HA.el;let{patchFlag:be,dynamicChildren:Ze,dirs:wt}=ce;be|=HA.patchFlag&16;const Nt=HA.props||Da,Oi=ce.props||Da;let po;if(Ve&&tv(Ve,!1),(po=Oi.onVnodeBeforeUpdate)&&BQ(po,Ve,ce,HA),wt&&ev(ce,HA,Ve,"beforeUpdate"),Ve&&tv(Ve,!0),(Nt.innerHTML&&Oi.innerHTML==null||Nt.textContent&&Oi.textContent==null)&&U(ti,""),Ze?Mt(HA.dynamicChildren,Ze,ti,Ve,Ot,Nj(ce,nt),It):ei||gt(HA,ce,ti,null,Ve,Ot,Nj(ce,nt),It,!1),be>0){if(be&16)jt(ti,Nt,Oi,Ve,nt);else if(be&2&&Nt.class!==Oi.class&&h(ti,"class",null,Oi.class,nt),be&4&&h(ti,"style",Nt.style,Oi.style,nt),be&8){const No=ce.dynamicProps;for(let so=0;so{po&&BQ(po,Ve,ce,HA),wt&&ev(ce,HA,Ve,"updated")},Ot)},Mt=(HA,ce,Ve,Ot,nt,It,ei)=>{for(let ti=0;ti{if(ce!==Ve){if(ce!==Da)for(const It in ce)!jL(It)&&!(It in Ve)&&h(HA,It,ce[It],null,nt,Ot);for(const It in Ve){if(jL(It))continue;const ei=Ve[It],ti=ce[It];ei!==ti&&It!=="value"&&h(HA,It,ti,ei,nt,Ot)}"value"in Ve&&h(HA,"value",ce.value,Ve.value,nt)}},Et=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{const Ze=ce.el=HA?HA.el:w(""),wt=ce.anchor=HA?HA.anchor:w("");let{patchFlag:Nt,dynamicChildren:Oi,slotScopeIds:po}=ce;po&&(ti=ti?ti.concat(po):po),HA==null?(l(Ze,Ve,Ot),l(wt,Ve,Ot),ft(ce.children||[],Ve,wt,nt,It,ei,ti,be)):Nt>0&&Nt&64&&Oi&&HA.dynamicChildren?(Mt(HA.dynamicChildren,Oi,Ve,nt,It,ei,ti),(ce.key!=null||nt&&ce===nt.subTree)&&FW(HA,ce,!0)):gt(HA,ce,Ve,wt,nt,It,ei,ti,be)},re=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{ce.slotScopeIds=ti,HA==null?ce.shapeFlag&512?nt.ctx.activate(ce,Ve,Ot,ei,be):qe(ce,Ve,Ot,nt,It,ei,be):yt(HA,ce,be)},qe=(HA,ce,Ve,Ot,nt,It,ei)=>{const ti=HA.component=JnA(HA,Ot,nt);if(rV(HA)&&(ti.ctx.renderer=bi),qnA(ti,!1,ei),ti.asyncDep){if(nt&&nt.registerDep(ti,Me,ei),!HA.el){const be=ti.subTree=Lt(mE);TA(null,be,ce,Ve)}}else Me(ti,HA,ce,Ve,nt,It,ei)},yt=(HA,ce,Ve)=>{const Ot=ce.component=HA.component;if(LnA(HA,ce,Ve))if(Ot.asyncDep&&!Ot.asyncResolved){Oe(Ot,ce,Ve);return}else Ot.next=ce,Ot.update();else ce.el=HA.el,Ot.vnode=ce},Me=(HA,ce,Ve,Ot,nt,It,ei)=>{const ti=()=>{if(HA.isMounted){let{next:Nt,bu:Oi,u:po,parent:No,vnode:so}=HA;{const an=h9(HA);if(an){Nt&&(Nt.el=so.el,Oe(HA,Nt,ei)),an.asyncDep.then(()=>{HA.isUnmounted||ti()});return}}let Go=Nt,An;tv(HA,!1),Nt?(Nt.el=so.el,Oe(HA,Nt,ei)):Nt=so,Oi&&X1(Oi),(An=Nt.props&&Nt.props.onVnodeBeforeUpdate)&&BQ(An,No,Nt,so),tv(HA,!0);const rn=D8(HA),Es=HA.subTree;HA.subTree=rn,IA(Es,rn,j(Es.el),Ao(Es),HA,nt,It),Nt.el=rn.el,Go===null&&UnA(HA,rn.el),po&&BE(po,nt),(An=Nt.props&&Nt.props.onVnodeUpdated)&&BE(()=>BQ(An,No,Nt,so),nt)}else{let Nt;const{el:Oi,props:po}=ce,{bm:No,m:so,parent:Go,root:An,type:rn}=HA,Es=W_(ce);tv(HA,!1),No&&X1(No),!Es&&(Nt=po&&po.onVnodeBeforeMount)&&BQ(Nt,Go,ce),tv(HA,!0);{An.ce&&An.ce._injectChildStyle(rn);const an=HA.subTree=D8(HA);IA(null,an,Ve,Ot,HA,nt,It),ce.el=an.el}if(so&&BE(so,nt),!Es&&(Nt=po&&po.onVnodeMounted)){const an=ce;BE(()=>BQ(Nt,Go,an),nt)}(ce.shapeFlag&256||Go&&W_(Go.vnode)&&Go.vnode.shapeFlag&256)&&HA.a&&BE(HA.a,nt),HA.isMounted=!0,ce=Ve=Ot=null}};HA.scope.on();const be=HA.effect=new v6(ti);HA.scope.off();const Ze=HA.update=be.run.bind(be),wt=HA.job=be.runIfDirty.bind(be);wt.i=HA,wt.id=HA.uid,be.scheduler=()=>kW(wt),tv(HA,!0),Ze()},Oe=(HA,ce,Ve)=>{ce.component=HA;const Ot=HA.vnode.props;HA.vnode=ce,HA.next=null,pnA(HA,ce.props,Ot,Ve),DnA(HA,ce.children,Ve),aD(),I8(HA),gD()},gt=(HA,ce,Ve,Ot,nt,It,ei,ti,be=!1)=>{const Ze=HA&&HA.children,wt=HA?HA.shapeFlag:0,Nt=ce.children,{patchFlag:Oi,shapeFlag:po}=ce;if(Oi>0){if(Oi&128){To(Ze,Nt,Ve,Ot,nt,It,ei,ti,be);return}else if(Oi&256){Fi(Ze,Nt,Ve,Ot,nt,It,ei,ti,be);return}}po&8?(wt&16&&jo(Ze,nt,It),Nt!==Ze&&U(Ve,Nt)):wt&16?po&16?To(Ze,Nt,Ve,Ot,nt,It,ei,ti,be):jo(Ze,nt,It,!0):(wt&8&&U(Ve,""),po&16&&ft(Nt,Ve,Ot,nt,It,ei,ti,be))},Fi=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{HA=HA||H_,ce=ce||H_;const Ze=HA.length,wt=ce.length,Nt=Math.min(Ze,wt);let Oi;for(Oi=0;Oiwt?jo(HA,nt,It,!0,!1,Nt):ft(ce,Ve,Ot,nt,It,ei,ti,be,Nt)},To=(HA,ce,Ve,Ot,nt,It,ei,ti,be)=>{let Ze=0;const wt=ce.length;let Nt=HA.length-1,Oi=wt-1;for(;Ze<=Nt&&Ze<=Oi;){const po=HA[Ze],No=ce[Ze]=be?Fy(ce[Ze]):fQ(ce[Ze]);if(cv(po,No))IA(po,No,Ve,null,nt,It,ei,ti,be);else break;Ze++}for(;Ze<=Nt&&Ze<=Oi;){const po=HA[Nt],No=ce[Oi]=be?Fy(ce[Oi]):fQ(ce[Oi]);if(cv(po,No))IA(po,No,Ve,null,nt,It,ei,ti,be);else break;Nt--,Oi--}if(Ze>Nt){if(Ze<=Oi){const po=Oi+1,No=poOi)for(;Ze<=Nt;)Eo(HA[Ze],nt,It,!0),Ze++;else{const po=Ze,No=Ze,so=new Map;for(Ze=No;Ze<=Oi;Ze++){const Jn=ce[Ze]=be?Fy(ce[Ze]):fQ(ce[Ze]);Jn.key!=null&&so.set(Jn.key,Ze)}let Go,An=0;const rn=Oi-No+1;let Es=!1,an=0;const Do=new Array(rn);for(Ze=0;Ze=rn){Eo(Jn,nt,It,!0);continue}let Qr;if(Jn.key!=null)Qr=so.get(Jn.key);else for(Go=No;Go<=Oi;Go++)if(Do[Go-No]===0&&cv(Jn,ce[Go])){Qr=Go;break}Qr===void 0?Eo(Jn,nt,It,!0):(Do[Qr-No]=Ze+1,Qr>=an?an=Qr:Es=!0,IA(Jn,ce[Qr],Ve,null,nt,It,ei,ti,be),An++)}const pA=Es?RnA(Do):H_;for(Go=pA.length-1,Ze=rn-1;Ze>=0;Ze--){const Jn=No+Ze,Qr=ce[Jn],ds=Jn+1{const{el:It,type:ei,transition:ti,children:be,shapeFlag:Ze}=HA;if(Ze&6){io(HA.component.subTree,ce,Ve,Ot);return}if(Ze&128){HA.suspense.move(ce,Ve,Ot);return}if(Ze&64){ei.move(HA,ce,Ve,bi);return}if(ei===vr){l(It,ce,Ve);for(let Nt=0;Ntti.enter(It),nt);else{const{leave:Nt,delayLeave:Oi,afterLeave:po}=ti,No=()=>l(It,ce,Ve),so=()=>{Nt(It,()=>{No(),po&&po()})};Oi?Oi(It,No,so):so()}else l(It,ce,Ve)},Eo=(HA,ce,Ve,Ot=!1,nt=!1)=>{const{type:It,props:ei,ref:ti,children:be,dynamicChildren:Ze,shapeFlag:wt,patchFlag:Nt,dirs:Oi,cacheIndex:po}=HA;if(Nt===-2&&(nt=!1),ti!=null&&pY(ti,null,Ve,HA,!0),po!=null&&(ce.renderCache[po]=void 0),wt&256){ce.ctx.deactivate(HA);return}const No=wt&1&&Oi,so=!W_(HA);let Go;if(so&&(Go=ei&&ei.onVnodeBeforeUnmount)&&BQ(Go,ce,HA),wt&6)ns(HA.component,Ve,Ot);else{if(wt&128){HA.suspense.unmount(Ve,Ot);return}No&&ev(HA,null,ce,"beforeUnmount"),wt&64?HA.type.remove(HA,ce,Ve,bi,Ot):Ze&&!Ze.hasOnce&&(It!==vr||Nt>0&&Nt&64)?jo(Ze,ce,Ve,!1,!0):(It===vr&&Nt&384||!nt&&wt&16)&&jo(be,ce,Ve),Ot&&Vs(HA)}(so&&(Go=ei&&ei.onVnodeUnmounted)||No)&&BE(()=>{Go&&BQ(Go,ce,HA),No&&ev(HA,null,ce,"unmounted")},Ve)},Vs=HA=>{const{type:ce,el:Ve,anchor:Ot,transition:nt}=HA;if(ce===vr){ki(Ve,Ot);return}if(ce===Gj){Ce(HA);return}const It=()=>{I(Ve),nt&&!nt.persisted&&nt.afterLeave&&nt.afterLeave()};if(HA.shapeFlag&1&&nt&&!nt.persisted){const{leave:ei,delayLeave:ti}=nt,be=()=>ei(Ve,It);ti?ti(HA.el,It,be):be()}else It()},ki=(HA,ce)=>{let Ve;for(;HA!==ce;)Ve=lA(HA),I(HA),HA=Ve;I(ce)},ns=(HA,ce,Ve)=>{const{bum:Ot,scope:nt,job:It,subTree:ei,um:ti,m:be,a:Ze}=HA;y8(be),y8(Ze),Ot&&X1(Ot),nt.stop(),It&&(It.flags|=8,Eo(ei,HA,ce,Ve)),ti&&BE(ti,ce),BE(()=>{HA.isUnmounted=!0},ce),ce&&ce.pendingBranch&&!ce.isUnmounted&&HA.asyncDep&&!HA.asyncResolved&&HA.suspenseId===ce.pendingId&&(ce.deps--,ce.deps===0&&ce.resolve())},jo=(HA,ce,Ve,Ot=!1,nt=!1,It=0)=>{for(let ei=It;ei{if(HA.shapeFlag&6)return Ao(HA.component.subTree);if(HA.shapeFlag&128)return HA.suspense.next();const ce=lA(HA.anchor||HA.el),Ve=ce&&ce[K6];return Ve?lA(Ve):ce};let Zt=!1;const oo=(HA,ce,Ve)=>{HA==null?ce._vnode&&Eo(ce._vnode,null,null,!0):IA(ce._vnode||null,HA,ce,null,null,null,Ve),ce._vnode=HA,Zt||(Zt=!0,I8(),H6(),Zt=!1)},bi={p:IA,um:Eo,m:io,r:Vs,mt:qe,mc:ft,pc:gt,pbc:Mt,n:Ao,o:t};return{render:oo,hydrate:void 0,createApp:BnA(oo)}}function Nj({type:t,props:i},r){return r==="svg"&&t==="foreignObject"||r==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:r}function tv({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function vnA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function FW(t,i,r=!1){const l=t.children,I=i.children;if(Ms(l)&&Ms(I))for(let h=0;h>1,t[r[w]]0&&(i[l]=r[h-1]),r[h]=l)}}for(h=r.length,f=r[h-1];h-- >0;)r[h]=f,f=i[f];return r}function h9(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:h9(i)}function y8(t){if(t)for(let i=0;iJI(wnA);function ET(t,i){return OW(t,null,i)}function Rr(t,i,r){return OW(t,i,r)}function OW(t,i,r=Da){const{immediate:l,deep:I,flush:h,once:f}=r,w=sI({},r),_=i&&l||!i&&h!=="post";let G;if(mU){if(h==="sync"){const sA=_nA();G=sA.__watcherHandles||(sA.__watcherHandles=[])}else if(!_){const sA=()=>{};return sA.stop=RQ,sA.resume=RQ,sA.pause=RQ,sA}}const U=xI;w.call=(sA,mA,IA)=>rB(sA,U,mA,IA);let j=!1;h==="post"?w.scheduler=sA=>{BE(sA,U&&U.suspense)}:h!=="sync"&&(j=!0,w.scheduler=(sA,mA)=>{mA?sA():kW(sA)}),w.augmentJob=sA=>{i&&(sA.flags|=4),j&&(sA.flags|=2,U&&(sA.id=U.uid,sA.i=U))};const lA=YsA(t,i,w);return mU&&(G?G.push(lA):_&&lA()),lA}function TnA(t,i,r){const l=this.proxy,I=fg(t)?t.includes(".")?B9(l,t):()=>l[t]:t.bind(l,l);let h;$s(i)?h=i:(h=i.handler,r=i);const f=UU(this),w=OW(I,h.bind(l),r);return f(),w}function B9(t,i){const r=i.split(".");return()=>{let l=t;for(let I=0;Ii==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${sh(i)}Modifiers`]||t[`${rD(i)}Modifiers`];function GnA(t,i,...r){if(t.isUnmounted)return;const l=t.vnode.props||Da;let I=r;const h=i.startsWith("update:"),f=h&&NnA(l,i.slice(7));f&&(f.trim&&(I=r.map(U=>fg(U)?U.trim():U)),f.number&&(I=r.map(p3)));let w,_=l[w=Dj(i)]||l[w=Dj(sh(i))];!_&&h&&(_=l[w=Dj(rD(i))]),_&&rB(_,t,6,I);const G=l[w+"Once"];if(G){if(!t.emitted)t.emitted={};else if(t.emitted[w])return;t.emitted[w]=!0,rB(G,t,6,I)}}function Q9(t,i,r=!1){const l=i.emitsCache,I=l.get(t);if(I!==void 0)return I;const h=t.emits;let f={},w=!1;if(!$s(t)){const _=G=>{const U=Q9(G,i,!0);U&&(w=!0,sI(f,U))};!r&&i.mixins.length&&i.mixins.forEach(_),t.extends&&_(t.extends),t.mixins&&t.mixins.forEach(_)}return!h&&!w?(Na(t)&&l.set(t,null),null):(Ms(h)?h.forEach(_=>f[_]=null):sI(f,h),Na(t)&&l.set(t,f),f)}function gV(t,i){return!t||!$Y(i)?!1:(i=i.slice(2).replace(/Once$/,""),Wr(t,i[0].toLowerCase()+i.slice(1))||Wr(t,rD(i))||Wr(t,i))}function D8(t){const{type:i,vnode:r,proxy:l,withProxy:I,propsOptions:[h],slots:f,attrs:w,emit:_,render:G,renderCache:U,props:j,data:lA,setupState:sA,ctx:mA,inheritAttrs:IA}=t,cA=QY(t);let TA,WA;try{if(r.shapeFlag&4){const Ce=I||l,xe=Ce;TA=fQ(G.call(xe,Ce,U,j,sA,lA,mA)),WA=w}else{const Ce=i;TA=fQ(Ce.length>1?Ce(j,{attrs:w,slots:f,emit:_}):Ce(j,null)),WA=i.props?w:bnA(w)}}catch(Ce){$L.length=0,sV(Ce,t,1),TA=Lt(mE)}let ue=TA;if(WA&&IA!==!1){const Ce=Object.keys(WA),{shapeFlag:xe}=ue;Ce.length&&xe&7&&(h&&Ce.some(SW)&&(WA=knA(WA,h)),ue=eD(ue,WA,!1,!0))}return r.dirs&&(ue=eD(ue,null,!1,!0),ue.dirs=ue.dirs?ue.dirs.concat(r.dirs):r.dirs),r.transition&&BU(ue,r.transition),TA=ue,QY(cA),TA}const bnA=t=>{let i;for(const r in t)(r==="class"||r==="style"||$Y(r))&&((i||(i={}))[r]=t[r]);return i},knA=(t,i)=>{const r={};for(const l in t)(!SW(l)||!(l.slice(9)in i))&&(r[l]=t[l]);return r};function LnA(t,i,r){const{props:l,children:I,component:h}=t,{props:f,children:w,patchFlag:_}=i,G=h.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&_>=0){if(_&1024)return!0;if(_&16)return l?S8(l,f,G):!!f;if(_&8){const U=i.dynamicProps;for(let j=0;jt.__isSuspense;function FnA(t,i){i&&i.pendingBranch?Ms(t)?i.effects.push(...t):i.effects.push(t):HsA(t)}const vr=Symbol.for("v-fgt"),cV=Symbol.for("v-txt"),mE=Symbol.for("v-cmt"),Gj=Symbol.for("v-stc"),$L=[];let oC=null;function ie(t=!1){$L.push(oC=t?null:[])}function OnA(){$L.pop(),oC=$L[$L.length-1]||null}let QU=1;function M8(t,i=!1){QU+=t,t<0&&oC&&i&&(oC.hasOnce=!0)}function m9(t){return t.dynamicChildren=QU>0?oC||H_:null,OnA(),QU>0&&oC&&oC.push(t),t}function $e(t,i,r,l,I,h){return m9(ne(t,i,r,l,I,h,!0))}function Qi(t,i,r,l,I){return m9(Lt(t,i,r,l,I,!0))}function pU(t){return t?t.__v_isVNode===!0:!1}function cv(t,i){return t.type===i.type&&t.key===i.key}const f9=({key:t})=>t??null,AY=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?fg(t)||iI(t)||$s(t)?{i:tI,r:t,k:i,f:!!r}:t:null);function ne(t,i=null,r=null,l=0,I=null,h=t===vr?0:1,f=!1,w=!1){const _={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&f9(i),ref:i&&AY(i),scopeId:nV,slotScopeIds:null,children:r,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:h,patchFlag:l,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:tI};return w?(PW(_,r),h&128&&t.normalize(_)):r&&(_.shapeFlag|=fg(r)?8:16),QU>0&&!f&&oC&&(_.patchFlag>0||h&6)&&_.patchFlag!==32&&oC.push(_),_}const Lt=PnA;function PnA(t,i=null,r=null,l=0,I=null,h=!1){if((!t||t===gnA)&&(t=mE),pU(t)){const w=eD(t,i,!0);return r&&PW(w,r),QU>0&&!h&&oC&&(w.shapeFlag&6?oC[oC.indexOf(t)]=w:oC.push(w)),w.patchFlag=-2,w}if(ZnA(t)&&(t=t.__vccOpts),i){i=xnA(i);let{class:w,style:_}=i;w&&!fg(w)&&(i.class=qi(w)),Na(_)&&(bW(_)&&!Ms(_)&&(_=sI({},_)),i.style=Br(_))}const f=fg(t)?1:p9(t)?128:j6(t)?64:Na(t)?4:$s(t)?2:0;return ne(t,i,r,l,I,f,h,!0)}function xnA(t){return t?bW(t)||c9(t)?sI({},t):t:null}function eD(t,i,r=!1,l=!1){const{props:I,ref:h,patchFlag:f,children:w,transition:_}=t,G=i?T3(I||{},i):I,U={__v_isVNode:!0,__v_skip:!0,type:t.type,props:G,key:G&&f9(G),ref:i&&i.ref?r&&h?Ms(h)?h.concat(AY(i)):[h,AY(i)]:AY(i):h,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:w,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==vr?f===-1?16:f|16:f,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:_,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&eD(t.ssContent),ssFallback:t.ssFallback&&eD(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return _&&l&&BU(U,_.clone(U)),U}function Ia(t=" ",i=0){return Lt(cV,null,t,i)}function zt(t="",i=!1){return i?(ie(),Qi(mE,null,t)):Lt(mE,null,t)}function fQ(t){return t==null||typeof t=="boolean"?Lt(mE):Ms(t)?Lt(vr,null,t.slice()):pU(t)?Fy(t):Lt(cV,null,String(t))}function Fy(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:eD(t)}function PW(t,i){let r=0;const{shapeFlag:l}=t;if(i==null)i=null;else if(Ms(i))r=16;else if(typeof i=="object")if(l&65){const I=i.default;I&&(I._c&&(I._d=!1),PW(t,I()),I._c&&(I._d=!0));return}else{r=32;const I=i._;!I&&!c9(i)?i._ctx=tI:I===3&&tI&&(tI.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else $s(i)?(i={default:i,_ctx:tI},r=32):(i=String(i),l&64?(r=16,i=[Ia(i)]):r=8);t.children=i,t.shapeFlag|=r}function T3(...t){const i={};for(let r=0;rxI||tI;let fY,N3;{const t=iV(),i=(r,l)=>{let I;return(I=t[r])||(I=t[r]=[]),I.push(l),h=>{I.length>1?I.forEach(f=>f(h)):I[0](h)}};fY=i("__VUE_INSTANCE_SETTERS__",r=>xI=r),N3=i("__VUE_SSR_SETTERS__",r=>mU=r)}const UU=t=>{const i=xI;return fY(t),t.scope.on(),()=>{t.scope.off(),fY(i)}},v8=()=>{xI&&xI.scope.off(),fY(null)};function y9(t){return t.vnode.shapeFlag&4}let mU=!1;function qnA(t,i=!1,r=!1){i&&N3(i);const{props:l,children:I}=t.vnode,h=y9(t);QnA(t,l,h,i),ynA(t,I,r);const f=h?KnA(t,i):void 0;return i&&N3(!1),f}function KnA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,lnA);const{setup:l}=r;if(l){aD();const I=t.setupContext=l.length>1?WnA(t):null,h=UU(t),f=LU(l,t,0,[t.props,I]),w=p6(f);if(gD(),h(),(w||t.sp)&&!W_(t)&&t9(t),w){if(f.then(v8,v8),i)return f.then(_=>{R8(t,_)}).catch(_=>{sV(_,t,0)});t.asyncDep=f}else R8(t,f)}else D9(t)}function R8(t,i,r){$s(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:Na(i)&&(t.setupState=x6(i)),D9(t)}function D9(t,i,r){const l=t.type;t.render||(t.render=l.render||RQ);{const I=UU(t);aD();try{InA(t)}finally{gD(),I()}}}const jnA={get(t,i){return pu(t,"get",""),t[i]}};function WnA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,jnA),slots:t.slots,emit:t.emit,expose:i}}function lV(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(x6(GsA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in XL)return XL[r](t)},has(i,r){return r in i||r in XL}})):t.proxy}function znA(t,i=!0){return $s(t)?t.displayName||t.name:t.name||i&&t.__name}function ZnA(t){return $s(t)&&"__vccOpts"in t}const Tt=(t,i)=>PsA(t,i,mU);function XnA(t,i,r){const l=arguments.length;return l===2?Na(i)&&!Ms(i)?pU(i)?Lt(t,null,[i]):Lt(t,i):Lt(t,null,i):(l>3?r=Array.prototype.slice.call(arguments,2):l===3&&pU(r)&&(r=[r]),Lt(t,i,r))}const G3="3.5.13";/** +**/function qU(t,i,n,c){try{return c?t(...c):t()}catch(I){QV(I,i,n)}}function cB(t,i,n,c){if($s(t)){const I=qU(t,i,n,c);return I&&J6(I)&&I.catch(C=>{QV(C,i,n)}),I}if(vs(t)){const I=[];for(let C=0;C>>1,I=mE[c],C=MU(I);C=MU(n)?mE.push(t):mE.splice(QnA(i),0,t),t.flags|=1,E9()}}function E9(){_Y||(_Y=u9.then(C9))}function pnA(t){vs(t)?Z_.push(...t):Oy&&t.id===-1?Oy.splice(__+1,0,t):t.flags&1||(Z_.push(t),t.flags|=1),E9()}function k8(t,i,n=fQ+1){for(;nMU(n)-MU(c));if(Z_.length=0,Oy){Oy.push(...i);return}for(Oy=i,__=0;__t.id==null?t.flags&2?-1:1/0:t.id;function C9(t){try{for(fQ=0;fQ{c._d&&W8(-1);const C=TY(i);let f;try{f=t(...I)}finally{TY(C),c._d&&W8(1)}return f};return c._n=!0,c._c=!0,c._d=!0,c}function Ta(t,i){if(iI===null)return t;const n=SV(iI),c=t.dirs||(t.dirs=[]);for(let I=0;It.__isTeleport,sU=t=>t&&(t.disabled||t.disabled===""),L8=t=>t&&(t.defer||t.defer===""),U8=t=>typeof SVGElement<"u"&&t instanceof SVGElement,F8=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,x3=(t,i)=>{const n=t&&t.to;return fg(n)?i?i(n):null:n},Q9={name:"Teleport",__isTeleport:!0,process(t,i,n,c,I,C,f,w,_,N){const{mc:L,pc:q,pbc:lA,o:{insert:tA,querySelector:BA,createText:IA,createComment:gA}}=N,RA=sU(i.props);let{shapeFlag:HA,children:ZA,dynamicChildren:KA}=i;if(t==null){const me=i.el=IA(""),ae=i.anchor=IA("");tA(me,n,c),tA(ae,n,c);const gt=(We,lt)=>{HA&16&&(I&&I.isCE&&(I.ce._teleportTarget=We),L(ZA,We,lt,I,C,f,w,_))},dt=()=>{const We=i.target=x3(i.props,BA),lt=p9(We,i,IA,tA);We&&(f!=="svg"&&U8(We)?f="svg":f!=="mathml"&&F8(We)&&(f="mathml"),RA||(gt(We,lt),lY(i,!1)))};RA&&(gt(n,ae),lY(i,!0)),L8(i.props)?QE(()=>{dt(),i.el.__isMounted=!0},C):dt()}else{if(L8(i.props)&&!t.el.__isMounted){QE(()=>{Q9.process(t,i,n,c,I,C,f,w,_,N),delete t.el.__isMounted},C);return}i.el=t.el,i.targetStart=t.targetStart;const me=i.anchor=t.anchor,ae=i.target=t.target,gt=i.targetAnchor=t.targetAnchor,dt=sU(t.props),We=dt?n:ae,lt=dt?me:gt;if(f==="svg"||U8(ae)?f="svg":(f==="mathml"||F8(ae))&&(f="mathml"),KA?(lA(t.dynamicChildren,KA,We,I,C,f,w),s4(t,i,!0)):_||q(t,i,We,lt,I,C,f,w,!1),RA)dt?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):V1(i,n,me,N,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const wt=i.target=x3(i.props,BA);wt&&V1(i,wt,null,N,0)}else dt&&V1(i,ae,gt,N,1);lY(i,RA)}},remove(t,i,n,{um:c,o:{remove:I}},C){const{shapeFlag:f,children:w,anchor:_,targetStart:N,targetAnchor:L,target:q,props:lA}=t;if(q&&(I(N),I(L)),C&&I(_),f&16){const tA=C||!sU(lA);for(let BA=0;BA{t.isMounted=!0}),nU(()=>{t.isUnmounting=!0}),t}const KC=[Function,Array],m9={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:KC,onEnter:KC,onAfterEnter:KC,onEnterCancelled:KC,onBeforeLeave:KC,onLeave:KC,onAfterLeave:KC,onLeaveCancelled:KC,onBeforeAppear:KC,onAppear:KC,onAfterAppear:KC,onAppearCancelled:KC},f9=t=>{const i=t.subTree;return i.component?f9(i.component):i},DnA={name:"BaseTransition",props:m9,setup(t,{slots:i}){const n=prA(),c=ynA();return()=>{const I=i.default&&S9(i.default(),!0);if(!I||!I.length)return;const C=y9(I),f=br(t),{mode:w}=f;if(c.isLeaving)return Hj(C);const _=O8(C);if(!_)return Hj(C);let N=Y3(_,f,c,n,q=>N=q);_.type!==fE&&vU(_,N);let L=n.subTree&&O8(n.subTree);if(L&&L.type!==fE&&!uv(_,L)&&f9(n).type!==fE){let q=Y3(L,f,c,n);if(vU(L,q),w==="out-in"&&_.type!==fE)return c.isLeaving=!0,q.afterLeave=()=>{c.isLeaving=!1,n.job.flags&8||n.update(),delete q.afterLeave,L=void 0},Hj(C);w==="in-out"&&_.type!==fE?q.delayLeave=(lA,tA,BA)=>{const IA=D9(c,L);IA[String(L.key)]=L,lA[Py]=()=>{tA(),lA[Py]=void 0,delete N.delayedLeave,L=void 0},N.delayedLeave=()=>{BA(),delete N.delayedLeave,L=void 0}}:L=void 0}else L&&(L=void 0);return C}}};function y9(t){let i=t[0];if(t.length>1){for(const n of t)if(n.type!==fE){i=n;break}}return i}const SnA=DnA;function D9(t,i){const{leavingVNodes:n}=t;let c=n.get(i.type);return c||(c=Object.create(null),n.set(i.type,c)),c}function Y3(t,i,n,c,I){const{appear:C,mode:f,persisted:w=!1,onBeforeEnter:_,onEnter:N,onAfterEnter:L,onEnterCancelled:q,onBeforeLeave:lA,onLeave:tA,onAfterLeave:BA,onLeaveCancelled:IA,onBeforeAppear:gA,onAppear:RA,onAfterAppear:HA,onAppearCancelled:ZA}=i,KA=String(t.key),me=D9(n,t),ae=(We,lt)=>{We&&cB(We,c,9,lt)},gt=(We,lt)=>{const wt=lt[1];ae(We,lt),vs(We)?We.every(ct=>ct.length<=1)&&wt():We.length<=1&&wt()},dt={mode:f,persisted:w,beforeEnter(We){let lt=_;if(!n.isMounted)if(C)lt=gA||_;else return;We[Py]&&We[Py](!0);const wt=me[KA];wt&&uv(t,wt)&&wt.el[Py]&&wt.el[Py](),ae(lt,[We])},enter(We){let lt=N,wt=L,ct=q;if(!n.isMounted)if(C)lt=RA||N,wt=HA||L,ct=ZA||q;else return;let ce=!1;const Ve=We[J1]=Dt=>{ce||(ce=!0,Dt?ae(ct,[We]):ae(wt,[We]),dt.delayedLeave&&dt.delayedLeave(),We[J1]=void 0)};lt?gt(lt,[We,Ve]):Ve()},leave(We,lt){const wt=String(t.key);if(We[J1]&&We[J1](!0),n.isUnmounting)return lt();ae(lA,[We]);let ct=!1;const ce=We[Py]=Ve=>{ct||(ct=!0,lt(),Ve?ae(IA,[We]):ae(BA,[We]),We[Py]=void 0,me[wt]===t&&delete me[wt])};me[wt]=t,tA?gt(tA,[We,ce]):ce()},clone(We){const lt=Y3(We,i,n,c,I);return I&&I(lt),lt}};return dt}function Hj(t){if(mV(t))return t=oD(t),t.children=null,t}function O8(t){if(!mV(t))return B9(t.type)&&t.children?y9(t.children):t;const{shapeFlag:i,children:n}=t;if(n){if(i&16)return n[0];if(i&32&&$s(n.default))return n.default()}}function vU(t,i){t.shapeFlag&6&&t.component?(t.transition=i,vU(t.component.subTree,i)):t.shapeFlag&128?(t.ssContent.transition=i.clone(t.ssContent),t.ssFallback.transition=i.clone(t.ssFallback)):t.transition=i}function S9(t,i=!1,n){let c=[],I=0;for(let C=0;C1)for(let C=0;CNY(BA,i&&(vs(i)?i[IA]:i),n,c,I));return}if(X_(c)&&!I){c.shapeFlag&512&&c.type.__asyncResolved&&c.component.subTree.component&&NY(t,i,n,c.component.subTree);return}const C=c.shapeFlag&4?SV(c.component):c.el,f=I?null:C,{i:w,r:_}=t,N=i&&i.r,L=w.refs===Da?w.refs={}:w.refs,q=w.setupState,lA=br(q),tA=q===Da?()=>!1:BA=>Wr(lA,BA);if(N!=null&&N!==_&&(fg(N)?(L[N]=null,tA(N)&&(q[N]=null)):oI(N)&&(N.value=null)),$s(_))qU(_,w,12,[f,L]);else{const BA=fg(_),IA=oI(_);if(BA||IA){const gA=()=>{if(t.f){const RA=BA?tA(_)?q[_]:L[_]:_.value;I?vs(RA)&&jW(RA,C):vs(RA)?RA.includes(C)||RA.push(C):BA?(L[_]=[C],tA(_)&&(q[_]=L[_])):(_.value=[C],t.k&&(L[t.k]=_.value))}else BA?(L[_]=f,tA(_)&&(q[_]=f)):IA&&(_.value=f,t.k&&(L[t.k]=f))};f?(gA.id=-1,QE(gA,n)):gA()}}}hV().requestIdleCallback;hV().cancelIdleCallback;const X_=t=>!!t.type.__asyncLoader,mV=t=>t.type.__isKeepAlive;function MnA(t,i){v9(t,"a",i)}function vnA(t,i){v9(t,"da",i)}function v9(t,i,n=xI){const c=t.__wdc||(t.__wdc=()=>{let I=n;for(;I;){if(I.isDeactivated)return;I=I.parent}return t()});if(fV(i,c,n),n){let I=n.parent;for(;I&&I.parent;)mV(I.parent.vnode)&&RnA(c,i,n,I),I=I.parent}}function RnA(t,i,n,c){const I=fV(i,t,c,!0);Kg(()=>{jW(c[i],I)},n)}function fV(t,i,n=xI,c=!1){if(n){const I=n[t]||(n[t]=[]),C=i.__weh||(i.__weh=(...f)=>{lD();const w=KU(n),_=cB(i,n,t,f);return w(),ID(),_});return c?I.unshift(C):I.push(C),C}}const pm=t=>(i,n=xI)=>{(!_U||t==="sp")&&fV(t,(...c)=>i(...c),n)},wnA=pm("bm"),hc=pm("m"),_nA=pm("bu"),TnA=pm("u"),nU=pm("bum"),Kg=pm("um"),NnA=pm("sp"),GnA=pm("rtg"),bnA=pm("rtc");function knA(t,i=xI){fV("ec",t,i)}const LnA="components";function UnA(t,i){return OnA(LnA,t,!0,i)||t}const FnA=Symbol.for("v-ndc");function OnA(t,i,n=!0,c=!1){const I=iI||xI;if(I){const C=I.type;{const w=SrA(C,!1);if(w&&(w===i||w===gh(i)||w===CV(gh(i))))return C}const f=P8(I[t]||C[t],i)||P8(I.appContext[t],i);return!f&&c?C:f}}function P8(t,i){return t&&(t[i]||t[gh(i)]||t[CV(gh(i))])}function JI(t,i,n,c){let I;const C=n,f=vs(t);if(f||fg(t)){const w=f&&z_(t);let _=!1;w&&(_=!nh(t),t=BV(t)),I=new Array(t.length);for(let N=0,L=t.length;Ni(w,_,void 0,C));else{const w=Object.keys(t);I=new Array(w.length);for(let _=0,N=w.length;_wU(i)?!(i.type===fE||i.type===tr&&!R9(i.children)):!0)?t:null}const V3=t=>t?K9(t)?SV(t):V3(t.parent):null,rU=nI(Object.create(null),{$:t=>t,$el:t=>t.vnode.el,$data:t=>t.data,$props:t=>t.props,$attrs:t=>t.attrs,$slots:t=>t.slots,$refs:t=>t.refs,$parent:t=>V3(t.parent),$root:t=>V3(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>_9(t),$forceUpdate:t=>t.f||(t.f=()=>{i4(t.update)}),$nextTick:t=>t.n||(t.n=oC.bind(t.proxy)),$watch:t=>nrA.bind(t)}),qj=(t,i)=>t!==Da&&!t.__isScriptSetup&&Wr(t,i),PnA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:n,setupState:c,data:I,props:C,accessCache:f,type:w,appContext:_}=t;let N;if(i[0]!=="$"){const tA=f[i];if(tA!==void 0)switch(tA){case 1:return c[i];case 2:return I[i];case 4:return n[i];case 3:return C[i]}else{if(qj(c,i))return f[i]=1,c[i];if(I!==Da&&Wr(I,i))return f[i]=2,I[i];if((N=t.propsOptions[0])&&Wr(N,i))return f[i]=3,C[i];if(n!==Da&&Wr(n,i))return f[i]=4,n[i];J3&&(f[i]=0)}}const L=rU[i];let q,lA;if(L)return i==="$attrs"&&mu(t.attrs,"get",""),L(t);if((q=w.__cssModules)&&(q=q[i]))return q;if(n!==Da&&Wr(n,i))return f[i]=4,n[i];if(lA=_.config.globalProperties,Wr(lA,i))return lA[i]},set({_:t},i,n){const{data:c,setupState:I,ctx:C}=t;return qj(I,i)?(I[i]=n,!0):c!==Da&&Wr(c,i)?(c[i]=n,!0):Wr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(C[i]=n,!0)},has({_:{data:t,setupState:i,accessCache:n,ctx:c,appContext:I,propsOptions:C}},f){let w;return!!n[f]||t!==Da&&Wr(t,f)||qj(i,f)||(w=C[0])&&Wr(w,f)||Wr(c,f)||Wr(rU,f)||Wr(I.config.globalProperties,f)},defineProperty(t,i,n){return n.get!=null?t._.accessCache[i]=0:Wr(n,"value")&&this.set(t,i,n.value,null),Reflect.defineProperty(t,i,n)}};function x8(t){return vs(t)?t.reduce((i,n)=>(i[n]=null,i),{}):t}let J3=!0;function xnA(t){const i=_9(t),n=t.proxy,c=t.ctx;J3=!1,i.beforeCreate&&Y8(i.beforeCreate,t,"bc");const{data:I,computed:C,methods:f,watch:w,provide:_,inject:N,created:L,beforeMount:q,mounted:lA,beforeUpdate:tA,updated:BA,activated:IA,deactivated:gA,beforeDestroy:RA,beforeUnmount:HA,destroyed:ZA,unmounted:KA,render:me,renderTracked:ae,renderTriggered:gt,errorCaptured:dt,serverPrefetch:We,expose:lt,inheritAttrs:wt,components:ct,directives:ce,filters:Ve}=i;if(N&&YnA(N,c,null),f)for(const Pt in f){const oi=f[Pt];$s(oi)&&(c[Pt]=oi.bind(n))}if(I){const Pt=I.call(n,n);Na(Pt)&&(t.data=Bv(Pt))}if(J3=!0,C)for(const Pt in C){const oi=C[Pt],Ni=$s(oi)?oi.bind(n,n):$s(oi.get)?oi.get.bind(n,n):TQ,Co=!$s(oi)&&$s(oi.set)?oi.set.bind(n):TQ,to=yt({get:Ni,set:Co});Object.defineProperty(c,Pt,{enumerable:!0,configurable:!0,get:()=>to.value,set:so=>to.value=so})}if(w)for(const Pt in w)w9(w[Pt],c,n,Pt);if(_){const Pt=$s(_)?_.call(n):_;Reflect.ownKeys(Pt).forEach(oi=>{gd(oi,Pt[oi])})}L&&Y8(L,t,"c");function ti(Pt,oi){vs(oi)?oi.forEach(Ni=>Pt(Ni.bind(n))):oi&&Pt(oi.bind(n))}if(ti(wnA,q),ti(hc,lA),ti(_nA,tA),ti(TnA,BA),ti(MnA,IA),ti(vnA,gA),ti(knA,dt),ti(bnA,ae),ti(GnA,gt),ti(nU,HA),ti(Kg,KA),ti(NnA,We),vs(lt))if(lt.length){const Pt=t.exposed||(t.exposed={});lt.forEach(oi=>{Object.defineProperty(Pt,oi,{get:()=>n[oi],set:Ni=>n[oi]=Ni})})}else t.exposed||(t.exposed={});me&&t.render===TQ&&(t.render=me),wt!=null&&(t.inheritAttrs=wt),ct&&(t.components=ct),ce&&(t.directives=ce),We&&M9(t)}function YnA(t,i,n=TQ){vs(t)&&(t=H3(t));for(const c in t){const I=t[c];let C;Na(I)?"default"in I?C=HI(I.from||c,I.default,!0):C=HI(I.from||c):C=HI(I),oI(C)?Object.defineProperty(i,c,{enumerable:!0,configurable:!0,get:()=>C.value,set:f=>C.value=f}):i[c]=C}}function Y8(t,i,n){cB(vs(t)?t.map(c=>c.bind(i.proxy)):t.bind(i.proxy),i,n)}function w9(t,i,n,c){let I=c.includes(".")?Y9(n,c):()=>n[c];if(fg(t)){const C=i[t];$s(C)&&Hn(I,C)}else if($s(t))Hn(I,t.bind(n));else if(Na(t))if(vs(t))t.forEach(C=>w9(C,i,n,c));else{const C=$s(t.handler)?t.handler.bind(n):i[t.handler];$s(C)&&Hn(I,C,t)}}function _9(t){const i=t.type,{mixins:n,extends:c}=i,{mixins:I,optionsCache:C,config:{optionMergeStrategies:f}}=t.appContext,w=C.get(i);let _;return w?_=w:!I.length&&!n&&!c?_=i:(_={},I.length&&I.forEach(N=>GY(_,N,f,!0)),GY(_,i,f)),Na(i)&&C.set(i,_),_}function GY(t,i,n,c=!1){const{mixins:I,extends:C}=i;C&&GY(t,C,n,!0),I&&I.forEach(f=>GY(t,f,n,!0));for(const f in i)if(!(c&&f==="expose")){const w=VnA[f]||n&&n[f];t[f]=w?w(t[f],i[f]):i[f]}return t}const VnA={data:V8,props:J8,emits:J8,methods:kL,computed:kL,beforeCreate:CE,created:CE,beforeMount:CE,mounted:CE,beforeUpdate:CE,updated:CE,beforeDestroy:CE,beforeUnmount:CE,destroyed:CE,unmounted:CE,activated:CE,deactivated:CE,errorCaptured:CE,serverPrefetch:CE,components:kL,directives:kL,watch:HnA,provide:V8,inject:JnA};function V8(t,i){return i?t?function(){return nI($s(t)?t.call(this,this):t,$s(i)?i.call(this,this):i)}:i:t}function JnA(t,i){return kL(H3(t),H3(i))}function H3(t){if(vs(t)){const i={};for(let n=0;n1)return n&&$s(i)?i.call(c&&c.proxy):i}}const N9={},G9=()=>Object.create(N9),b9=t=>Object.getPrototypeOf(t)===N9;function jnA(t,i,n,c=!1){const I={},C=G9();t.propsDefaults=Object.create(null),k9(t,i,I,C);for(const f in t.propsOptions[0])f in I||(I[f]=void 0);n?t.props=c?I:rnA(I):t.type.props?t.props=I:t.props=C,t.attrs=C}function WnA(t,i,n,c){const{props:I,attrs:C,vnode:{patchFlag:f}}=t,w=br(I),[_]=t.propsOptions;let N=!1;if((c||f>0)&&!(f&16)){if(f&8){const L=t.vnode.dynamicProps;for(let q=0;q{_=!0;const[lA,tA]=L9(q,i,!0);nI(f,lA),tA&&w.push(...tA)};!n&&i.mixins.length&&i.mixins.forEach(L),t.extends&&L(t.extends),t.mixins&&t.mixins.forEach(L)}if(!C&&!_)return Na(t)&&c.set(t,j_),j_;if(vs(C))for(let L=0;Lt[0]==="_"||t==="$stable",o4=t=>vs(t)?t.map(SQ):[SQ(t)],ZnA=(t,i,n)=>{if(i._n)return i;const c=Oi((...I)=>o4(i(...I)),n);return c._c=!1,c},F9=(t,i,n)=>{const c=t._ctx;for(const I in t){if(U9(I))continue;const C=t[I];if($s(C))i[I]=ZnA(I,C,c);else if(C!=null){const f=o4(C);i[I]=()=>f}}},O9=(t,i)=>{const n=o4(i);t.slots.default=()=>n},P9=(t,i,n)=>{for(const c in i)(n||c!=="_")&&(t[c]=i[c])},XnA=(t,i,n)=>{const c=t.slots=G9();if(t.vnode.shapeFlag&32){const I=i._;I?(P9(c,i,n),n&&K6(c,"_",I,!0)):F9(i,c)}else i&&O9(t,i)},$nA=(t,i,n)=>{const{vnode:c,slots:I}=t;let C=!0,f=Da;if(c.shapeFlag&32){const w=i._;w?n&&w===1?C=!1:P9(I,i,n):(C=!i.$stable,F9(i,I)),f=i}else i&&(O9(t,i),f={default:1});if(C)for(const w in I)!U9(w)&&f[w]==null&&delete I[w]},QE=urA;function ArA(t){return erA(t)}function erA(t,i){const n=hV();n.__VUE__=!0;const{insert:c,remove:I,patchProp:C,createElement:f,createText:w,createComment:_,setText:N,setElementText:L,parentNode:q,nextSibling:lA,setScopeId:tA=TQ,insertStaticContent:BA}=t,IA=(VA,Ee,Je,Ut=null,ot=null,ut=null,$t=void 0,Zt=null,Ge=!!Ee.dynamicChildren)=>{if(VA===Ee)return;VA&&!uv(VA,Ee)&&(Ut=$i(VA),so(VA,ot,ut,!0),VA=null),Ee.patchFlag===-2&&(Ge=!1,Ee.dynamicChildren=null);const{type:Xe,ref:se,shapeFlag:ve}=Ee;switch(Xe){case DV:gA(VA,Ee,Je,Ut);break;case fE:RA(VA,Ee,Je,Ut);break;case jj:VA==null&&HA(Ee,Je,Ut,$t);break;case tr:ct(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge);break;default:ve&1?me(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge):ve&6?ce(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge):(ve&64||ve&128)&&Xe.process(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge,Ri)}se!=null&&ot&&NY(se,VA&&VA.ref,ut,Ee||VA,!Ee)},gA=(VA,Ee,Je,Ut)=>{if(VA==null)c(Ee.el=w(Ee.children),Je,Ut);else{const ot=Ee.el=VA.el;Ee.children!==VA.children&&N(ot,Ee.children)}},RA=(VA,Ee,Je,Ut)=>{VA==null?c(Ee.el=_(Ee.children||""),Je,Ut):Ee.el=VA.el},HA=(VA,Ee,Je,Ut)=>{[VA.el,VA.anchor]=BA(VA.children,Ee,Je,Ut,VA.el,VA.anchor)},ZA=({el:VA,anchor:Ee},Je,Ut)=>{let ot;for(;VA&&VA!==Ee;)ot=lA(VA),c(VA,Je,Ut),VA=ot;c(Ee,Je,Ut)},KA=({el:VA,anchor:Ee})=>{let Je;for(;VA&&VA!==Ee;)Je=lA(VA),I(VA),VA=Je;I(Ee)},me=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge)=>{Ee.type==="svg"?$t="svg":Ee.type==="math"&&($t="mathml"),VA==null?ae(Ee,Je,Ut,ot,ut,$t,Zt,Ge):We(VA,Ee,ot,ut,$t,Zt,Ge)},ae=(VA,Ee,Je,Ut,ot,ut,$t,Zt)=>{let Ge,Xe;const{props:se,shapeFlag:ve,transition:pt,dirs:mo}=VA;if(Ge=VA.el=f(VA.type,ut,se&&se.is,se),ve&8?L(Ge,VA.children):ve&16&&dt(VA.children,Ge,null,Ut,ot,Kj(VA,ut),$t,Zt),mo&&ov(VA,null,Ut,"created"),gt(Ge,VA,VA.scopeId,$t,Ut),se){for(const no in se)no!=="value"&&!tU(no)&&C(Ge,no,null,se[no],ut,Ut);"value"in se&&C(Ge,"value",null,se.value,ut),(Xe=se.onVnodeBeforeMount)&&mQ(Xe,Ut,VA)}mo&&ov(VA,null,Ut,"beforeMount");const No=trA(ot,pt);No&&pt.beforeEnter(Ge),c(Ge,Ee,Je),((Xe=se&&se.onVnodeMounted)||No||mo)&&QE(()=>{Xe&&mQ(Xe,Ut,VA),No&&pt.enter(Ge),mo&&ov(VA,null,Ut,"mounted")},ot)},gt=(VA,Ee,Je,Ut,ot)=>{if(Je&&tA(VA,Je),Ut)for(let ut=0;ut{for(let Xe=Ge;Xe{const Zt=Ee.el=VA.el;let{patchFlag:Ge,dynamicChildren:Xe,dirs:se}=Ee;Ge|=VA.patchFlag&16;const ve=VA.props||Da,pt=Ee.props||Da;let mo;if(Je&&sv(Je,!1),(mo=pt.onVnodeBeforeUpdate)&&mQ(mo,Je,Ee,VA),se&&ov(Ee,VA,Je,"beforeUpdate"),Je&&sv(Je,!0),(ve.innerHTML&&pt.innerHTML==null||ve.textContent&&pt.textContent==null)&&L(Zt,""),Xe?lt(VA.dynamicChildren,Xe,Zt,Je,Ut,Kj(Ee,ot),ut):$t||oi(VA,Ee,Zt,null,Je,Ut,Kj(Ee,ot),ut,!1),Ge>0){if(Ge&16)wt(Zt,ve,pt,Je,ot);else if(Ge&2&&ve.class!==pt.class&&C(Zt,"class",null,pt.class,ot),Ge&4&&C(Zt,"style",ve.style,pt.style,ot),Ge&8){const No=Ee.dynamicProps;for(let no=0;no{mo&&mQ(mo,Je,Ee,VA),se&&ov(Ee,VA,Je,"updated")},Ut)},lt=(VA,Ee,Je,Ut,ot,ut,$t)=>{for(let Zt=0;Zt{if(Ee!==Je){if(Ee!==Da)for(const ut in Ee)!tU(ut)&&!(ut in Je)&&C(VA,ut,Ee[ut],null,ot,Ut);for(const ut in Je){if(tU(ut))continue;const $t=Je[ut],Zt=Ee[ut];$t!==Zt&&ut!=="value"&&C(VA,ut,Zt,$t,ot,Ut)}"value"in Je&&C(VA,"value",Ee.value,Je.value,ot)}},ct=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge)=>{const Xe=Ee.el=VA?VA.el:w(""),se=Ee.anchor=VA?VA.anchor:w("");let{patchFlag:ve,dynamicChildren:pt,slotScopeIds:mo}=Ee;mo&&(Zt=Zt?Zt.concat(mo):mo),VA==null?(c(Xe,Je,Ut),c(se,Je,Ut),dt(Ee.children||[],Je,se,ot,ut,$t,Zt,Ge)):ve>0&&ve&64&&pt&&VA.dynamicChildren?(lt(VA.dynamicChildren,pt,Je,ot,ut,$t,Zt),(Ee.key!=null||ot&&Ee===ot.subTree)&&s4(VA,Ee,!0)):oi(VA,Ee,Je,se,ot,ut,$t,Zt,Ge)},ce=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge)=>{Ee.slotScopeIds=Zt,VA==null?Ee.shapeFlag&512?ot.ctx.activate(Ee,Je,Ut,$t,Ge):Ve(Ee,Je,Ut,ot,ut,$t,Ge):Dt(VA,Ee,Ge)},Ve=(VA,Ee,Je,Ut,ot,ut,$t)=>{const Zt=VA.component=QrA(VA,Ut,ot);if(mV(VA)&&(Zt.ctx.renderer=Ri),mrA(Zt,!1,$t),Zt.asyncDep){if(ot&&ot.registerDep(Zt,ti,$t),!VA.el){const Ge=Zt.subTree=kt(fE);RA(null,Ge,Ee,Je)}}else ti(Zt,VA,Ee,Je,ot,ut,$t)},Dt=(VA,Ee,Je)=>{const Ut=Ee.component=VA.component;if(lrA(VA,Ee,Je))if(Ut.asyncDep&&!Ut.asyncResolved){Pt(Ut,Ee,Je);return}else Ut.next=Ee,Ut.update();else Ee.el=VA.el,Ut.vnode=Ee},ti=(VA,Ee,Je,Ut,ot,ut,$t)=>{const Zt=()=>{if(VA.isMounted){let{next:ve,bu:pt,u:mo,parent:No,vnode:no}=VA;{const an=x9(VA);if(an){ve&&(ve.el=no.el,Pt(VA,ve,$t)),an.asyncDep.then(()=>{VA.isUnmounted||Zt()});return}}let Go=ve,An;sv(VA,!1),ve?(ve.el=no.el,Pt(VA,ve,$t)):ve=no,pt&&cY(pt),(An=ve.props&&ve.props.onVnodeBeforeUpdate)&&mQ(An,No,ve,no),sv(VA,!0);const rn=K8(VA),ds=VA.subTree;VA.subTree=rn,IA(ds,rn,q(ds.el),$i(ds),VA,ot,ut),ve.el=rn.el,Go===null&&IrA(VA,rn.el),mo&&QE(mo,ot),(An=ve.props&&ve.props.onVnodeUpdated)&&QE(()=>mQ(An,No,ve,no),ot)}else{let ve;const{el:pt,props:mo}=Ee,{bm:No,m:no,parent:Go,root:An,type:rn}=VA,ds=X_(Ee);sv(VA,!1),No&&cY(No),!ds&&(ve=mo&&mo.onVnodeBeforeMount)&&mQ(ve,Go,Ee),sv(VA,!0);{An.ce&&An.ce._injectChildStyle(rn);const an=VA.subTree=K8(VA);IA(null,an,Je,Ut,VA,ot,ut),Ee.el=an.el}if(no&&QE(no,ot),!ds&&(ve=mo&&mo.onVnodeMounted)){const an=Ee;QE(()=>mQ(ve,Go,an),ot)}(Ee.shapeFlag&256||Go&&X_(Go.vnode)&&Go.vnode.shapeFlag&256)&&VA.a&&QE(VA.a,ot),VA.isMounted=!0,Ee=Je=Ut=null}};VA.scope.on();const Ge=VA.effect=new Z6(Zt);VA.scope.off();const Xe=VA.update=Ge.run.bind(Ge),se=VA.job=Ge.runIfDirty.bind(Ge);se.i=VA,se.id=VA.uid,Ge.scheduler=()=>i4(se),sv(VA,!0),Xe()},Pt=(VA,Ee,Je)=>{Ee.component=VA;const Ut=VA.vnode.props;VA.vnode=Ee,VA.next=null,WnA(VA,Ee.props,Ut,Je),$nA(VA,Ee.children,Je),lD(),k8(VA),ID()},oi=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge=!1)=>{const Xe=VA&&VA.children,se=VA?VA.shapeFlag:0,ve=Ee.children,{patchFlag:pt,shapeFlag:mo}=Ee;if(pt>0){if(pt&128){Co(Xe,ve,Je,Ut,ot,ut,$t,Zt,Ge);return}else if(pt&256){Ni(Xe,ve,Je,Ut,ot,ut,$t,Zt,Ge);return}}mo&8?(se&16&&Lo(Xe,ot,ut),ve!==Xe&&L(Je,ve)):se&16?mo&16?Co(Xe,ve,Je,Ut,ot,ut,$t,Zt,Ge):Lo(Xe,ot,ut,!0):(se&8&&L(Je,""),mo&16&&dt(ve,Je,Ut,ot,ut,$t,Zt,Ge))},Ni=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge)=>{VA=VA||j_,Ee=Ee||j_;const Xe=VA.length,se=Ee.length,ve=Math.min(Xe,se);let pt;for(pt=0;ptse?Lo(VA,ot,ut,!0,!1,ve):dt(Ee,Je,Ut,ot,ut,$t,Zt,Ge,ve)},Co=(VA,Ee,Je,Ut,ot,ut,$t,Zt,Ge)=>{let Xe=0;const se=Ee.length;let ve=VA.length-1,pt=se-1;for(;Xe<=ve&&Xe<=pt;){const mo=VA[Xe],No=Ee[Xe]=Ge?xy(Ee[Xe]):SQ(Ee[Xe]);if(uv(mo,No))IA(mo,No,Je,null,ot,ut,$t,Zt,Ge);else break;Xe++}for(;Xe<=ve&&Xe<=pt;){const mo=VA[ve],No=Ee[pt]=Ge?xy(Ee[pt]):SQ(Ee[pt]);if(uv(mo,No))IA(mo,No,Je,null,ot,ut,$t,Zt,Ge);else break;ve--,pt--}if(Xe>ve){if(Xe<=pt){const mo=pt+1,No=mopt)for(;Xe<=ve;)so(VA[Xe],ot,ut,!0),Xe++;else{const mo=Xe,No=Xe,no=new Map;for(Xe=No;Xe<=pt;Xe++){const qn=Ee[Xe]=Ge?xy(Ee[Xe]):SQ(Ee[Xe]);qn.key!=null&&no.set(qn.key,Xe)}let Go,An=0;const rn=pt-No+1;let ds=!1,an=0;const So=new Array(rn);for(Xe=0;Xe=rn){so(qn,ot,ut,!0);continue}let mr;if(qn.key!=null)mr=no.get(qn.key);else for(Go=No;Go<=pt;Go++)if(So[Go-No]===0&&uv(qn,Ee[Go])){mr=Go;break}mr===void 0?so(qn,ot,ut,!0):(So[mr-No]=Xe+1,mr>=an?an=mr:ds=!0,IA(qn,Ee[mr],Je,null,ot,ut,$t,Zt,Ge),An++)}const mA=ds?irA(So):j_;for(Go=mA.length-1,Xe=rn-1;Xe>=0;Xe--){const qn=No+Xe,mr=Ee[qn],Cs=qn+1{const{el:ut,type:$t,transition:Zt,children:Ge,shapeFlag:Xe}=VA;if(Xe&6){to(VA.component.subTree,Ee,Je,Ut);return}if(Xe&128){VA.suspense.move(Ee,Je,Ut);return}if(Xe&64){$t.move(VA,Ee,Je,Ri);return}if($t===tr){c(ut,Ee,Je);for(let ve=0;veZt.enter(ut),ot);else{const{leave:ve,delayLeave:pt,afterLeave:mo}=Zt,No=()=>c(ut,Ee,Je),no=()=>{ve(ut,()=>{No(),mo&&mo()})};pt?pt(ut,No,no):no()}else c(ut,Ee,Je)},so=(VA,Ee,Je,Ut=!1,ot=!1)=>{const{type:ut,props:$t,ref:Zt,children:Ge,dynamicChildren:Xe,shapeFlag:se,patchFlag:ve,dirs:pt,cacheIndex:mo}=VA;if(ve===-2&&(ot=!1),Zt!=null&&NY(Zt,null,Je,VA,!0),mo!=null&&(Ee.renderCache[mo]=void 0),se&256){Ee.ctx.deactivate(VA);return}const No=se&1&&pt,no=!X_(VA);let Go;if(no&&(Go=$t&&$t.onVnodeBeforeUnmount)&&mQ(Go,Ee,VA),se&6)As(VA.component,Je,Ut);else{if(se&128){VA.suspense.unmount(Je,Ut);return}No&&ov(VA,null,Ee,"beforeUnmount"),se&64?VA.type.remove(VA,Ee,Je,Ri,Ut):Xe&&!Xe.hasOnce&&(ut!==tr||ve>0&&ve&64)?Lo(Xe,Ee,Je,!1,!0):(ut===tr&&ve&384||!ot&&se&16)&&Lo(Ge,Ee,Je),Ut&&ks(VA)}(no&&(Go=$t&&$t.onVnodeUnmounted)||No)&&QE(()=>{Go&&mQ(Go,Ee,VA),No&&ov(VA,null,Ee,"unmounted")},Je)},ks=VA=>{const{type:Ee,el:Je,anchor:Ut,transition:ot}=VA;if(Ee===tr){Gi(Je,Ut);return}if(Ee===jj){KA(VA);return}const ut=()=>{I(Je),ot&&!ot.persisted&&ot.afterLeave&&ot.afterLeave()};if(VA.shapeFlag&1&&ot&&!ot.persisted){const{leave:$t,delayLeave:Zt}=ot,Ge=()=>$t(Je,ut);Zt?Zt(VA.el,ut,Ge):Ge()}else ut()},Gi=(VA,Ee)=>{let Je;for(;VA!==Ee;)Je=lA(VA),I(VA),VA=Je;I(Ee)},As=(VA,Ee,Je)=>{const{bum:Ut,scope:ot,job:ut,subTree:$t,um:Zt,m:Ge,a:Xe}=VA;q8(Ge),q8(Xe),Ut&&cY(Ut),ot.stop(),ut&&(ut.flags|=8,so($t,VA,Ee,Je)),Zt&&QE(Zt,Ee),QE(()=>{VA.isUnmounted=!0},Ee),Ee&&Ee.pendingBranch&&!Ee.isUnmounted&&VA.asyncDep&&!VA.asyncResolved&&VA.suspenseId===Ee.pendingId&&(Ee.deps--,Ee.deps===0&&Ee.resolve())},Lo=(VA,Ee,Je,Ut=!1,ot=!1,ut=0)=>{for(let $t=ut;$t{if(VA.shapeFlag&6)return $i(VA.component.subTree);if(VA.shapeFlag&128)return VA.suspense.next();const Ee=lA(VA.anchor||VA.el),Je=Ee&&Ee[h9];return Je?lA(Je):Ee};let zt=!1;const Ao=(VA,Ee,Je)=>{VA==null?Ee._vnode&&so(Ee._vnode,null,null,!0):IA(Ee._vnode||null,VA,Ee,null,null,null,Je),Ee._vnode=VA,zt||(zt=!0,k8(),d9(),zt=!1)},Ri={p:IA,um:so,m:to,r:ks,mt:Ve,mc:dt,pc:oi,pbc:lt,n:$i,o:t};return{render:Ao,hydrate:void 0,createApp:KnA(Ao)}}function Kj({type:t,props:i},n){return n==="svg"&&t==="foreignObject"||n==="mathml"&&t==="annotation-xml"&&i&&i.encoding&&i.encoding.includes("html")?void 0:n}function sv({effect:t,job:i},n){n?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function trA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function s4(t,i,n=!1){const c=t.children,I=i.children;if(vs(c)&&vs(I))for(let C=0;C>1,t[n[w]]0&&(i[c]=n[C-1]),n[C]=c)}}for(C=n.length,f=n[C-1];C-- >0;)n[C]=f,f=i[f];return n}function x9(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:x9(i)}function q8(t){if(t)for(let i=0;iHI(orA);function pT(t,i){return n4(t,null,i)}function Hn(t,i,n){return n4(t,i,n)}function n4(t,i,n=Da){const{immediate:c,deep:I,flush:C,once:f}=n,w=nI({},n),_=i&&c||!i&&C!=="post";let N;if(_U){if(C==="sync"){const tA=srA();N=tA.__watcherHandles||(tA.__watcherHandles=[])}else if(!_){const tA=()=>{};return tA.stop=TQ,tA.resume=TQ,tA.pause=TQ,tA}}const L=xI;w.call=(tA,BA,IA)=>cB(tA,L,BA,IA);let q=!1;C==="post"?w.scheduler=tA=>{QE(tA,L&&L.suspense)}:C!=="sync"&&(q=!0,w.scheduler=(tA,BA)=>{BA?tA():i4(tA)}),w.augmentJob=tA=>{i&&(tA.flags|=4),q&&(tA.flags|=2,L&&(tA.id=L.uid,tA.i=L))};const lA=hnA(t,i,w);return _U&&(N?N.push(lA):_&&lA()),lA}function nrA(t,i,n){const c=this.proxy,I=fg(t)?t.includes(".")?Y9(c,t):()=>c[t]:t.bind(c,c);let C;$s(i)?C=i:(C=i.handler,n=i);const f=KU(this),w=n4(I,C.bind(c),n);return f(),w}function Y9(t,i){const n=i.split(".");return()=>{let c=t;for(let I=0;Ii==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${gh(i)}Modifiers`]||t[`${cD(i)}Modifiers`];function arA(t,i,...n){if(t.isUnmounted)return;const c=t.vnode.props||Da;let I=n;const C=i.startsWith("update:"),f=C&&rrA(c,i.slice(7));f&&(f.trim&&(I=n.map(L=>fg(L)?L.trim():L)),f.number&&(I=n.map(L3)));let w,_=c[w=Oj(i)]||c[w=Oj(gh(i))];!_&&C&&(_=c[w=Oj(cD(i))]),_&&cB(_,t,6,I);const N=c[w+"Once"];if(N){if(!t.emitted)t.emitted={};else if(t.emitted[w])return;t.emitted[w]=!0,cB(N,t,6,I)}}function V9(t,i,n=!1){const c=i.emitsCache,I=c.get(t);if(I!==void 0)return I;const C=t.emits;let f={},w=!1;if(!$s(t)){const _=N=>{const L=V9(N,i,!0);L&&(w=!0,nI(f,L))};!n&&i.mixins.length&&i.mixins.forEach(_),t.extends&&_(t.extends),t.mixins&&t.mixins.forEach(_)}return!C&&!w?(Na(t)&&c.set(t,null),null):(vs(C)?C.forEach(_=>f[_]=null):nI(f,C),Na(t)&&c.set(t,f),f)}function yV(t,i){return!t||!uV(i)?!1:(i=i.slice(2).replace(/Once$/,""),Wr(t,i[0].toLowerCase()+i.slice(1))||Wr(t,cD(i))||Wr(t,i))}function K8(t){const{type:i,vnode:n,proxy:c,withProxy:I,propsOptions:[C],slots:f,attrs:w,emit:_,render:N,renderCache:L,props:q,data:lA,setupState:tA,ctx:BA,inheritAttrs:IA}=t,gA=TY(t);let RA,HA;try{if(n.shapeFlag&4){const KA=I||c,me=KA;RA=SQ(N.call(me,KA,L,q,tA,lA,BA)),HA=w}else{const KA=i;RA=SQ(KA.length>1?KA(q,{attrs:w,slots:f,emit:_}):KA(q,null)),HA=i.props?w:grA(w)}}catch(KA){aU.length=0,QV(KA,t,1),RA=kt(fE)}let ZA=RA;if(HA&&IA!==!1){const KA=Object.keys(HA),{shapeFlag:me}=ZA;KA.length&&me&7&&(C&&KA.some(KW)&&(HA=crA(HA,C)),ZA=oD(ZA,HA,!1,!0))}return n.dirs&&(ZA=oD(ZA,null,!1,!0),ZA.dirs=ZA.dirs?ZA.dirs.concat(n.dirs):n.dirs),n.transition&&vU(ZA,n.transition),RA=ZA,TY(gA),RA}const grA=t=>{let i;for(const n in t)(n==="class"||n==="style"||uV(n))&&((i||(i={}))[n]=t[n]);return i},crA=(t,i)=>{const n={};for(const c in t)(!KW(c)||!(c.slice(9)in i))&&(n[c]=t[c]);return n};function lrA(t,i,n){const{props:c,children:I,component:C}=t,{props:f,children:w,patchFlag:_}=i,N=C.emitsOptions;if(i.dirs||i.transition)return!0;if(n&&_>=0){if(_&1024)return!0;if(_&16)return c?j8(c,f,N):!!f;if(_&8){const L=i.dynamicProps;for(let q=0;qt.__isSuspense;function urA(t,i){i&&i.pendingBranch?vs(t)?i.effects.push(...t):i.effects.push(t):pnA(t)}const tr=Symbol.for("v-fgt"),DV=Symbol.for("v-txt"),fE=Symbol.for("v-cmt"),jj=Symbol.for("v-stc"),aU=[];let sC=null;function te(t=!1){aU.push(sC=t?null:[])}function ErA(){aU.pop(),sC=aU[aU.length-1]||null}let RU=1;function W8(t,i=!1){RU+=t,t<0&&sC&&i&&(sC.hasOnce=!0)}function H9(t){return t.dynamicChildren=RU>0?sC||j_:null,ErA(),RU>0&&sC&&sC.push(t),t}function Ye(t,i,n,c,I,C){return H9(Ae(t,i,n,c,I,C,!0))}function Qi(t,i,n,c,I){return H9(kt(t,i,n,c,I,!0))}function wU(t){return t?t.__v_isVNode===!0:!1}function uv(t,i){return t.type===i.type&&t.key===i.key}const q9=({key:t})=>t??null,IY=({ref:t,ref_key:i,ref_for:n})=>(typeof t=="number"&&(t=""+t),t!=null?fg(t)||oI(t)||$s(t)?{i:iI,r:t,k:i,f:!!n}:t:null);function Ae(t,i=null,n=null,c=0,I=null,C=t===tr?0:1,f=!1,w=!1){const _={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&q9(i),ref:i&&IY(i),scopeId:pV,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:C,patchFlag:c,dynamicProps:I,dynamicChildren:null,appContext:null,ctx:iI};return w?(r4(_,n),C&128&&t.normalize(_)):n&&(_.shapeFlag|=fg(n)?8:16),RU>0&&!f&&sC&&(_.patchFlag>0||C&6)&&_.patchFlag!==32&&sC.push(_),_}const kt=drA;function drA(t,i=null,n=null,c=0,I=null,C=!1){if((!t||t===FnA)&&(t=fE),wU(t)){const w=oD(t,i,!0);return n&&r4(w,n),RU>0&&!C&&sC&&(w.shapeFlag&6?sC[sC.indexOf(t)]=w:sC.push(w)),w.patchFlag=-2,w}if(MrA(t)&&(t=t.__vccOpts),i){i=CrA(i);let{class:w,style:_}=i;w&&!fg(w)&&(i.class=xi(w)),Na(_)&&(t4(_)&&!vs(_)&&(_=nI({},_)),i.style=Cr(_))}const f=fg(t)?1:J9(t)?128:B9(t)?64:Na(t)?4:$s(t)?2:0;return Ae(t,i,n,c,I,f,C,!0)}function CrA(t){return t?t4(t)||b9(t)?nI({},t):t:null}function oD(t,i,n=!1,c=!1){const{props:I,ref:C,patchFlag:f,children:w,transition:_}=t,N=i?K3(I||{},i):I,L={__v_isVNode:!0,__v_skip:!0,type:t.type,props:N,key:N&&q9(N),ref:i&&i.ref?n&&C?vs(C)?C.concat(IY(i)):[C,IY(i)]:IY(i):C,scopeId:t.scopeId,slotScopeIds:t.slotScopeIds,children:w,target:t.target,targetStart:t.targetStart,targetAnchor:t.targetAnchor,staticCount:t.staticCount,shapeFlag:t.shapeFlag,patchFlag:i&&t.type!==tr?f===-1?16:f|16:f,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:_,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&oD(t.ssContent),ssFallback:t.ssFallback&&oD(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return _&&c&&vU(L,_.clone(L)),L}function zr(t=" ",i=0){return kt(DV,null,t,i)}function Lt(t="",i=!1){return i?(te(),Qi(fE,null,t)):kt(fE,null,t)}function SQ(t){return t==null||typeof t=="boolean"?kt(fE):vs(t)?kt(tr,null,t.slice()):wU(t)?xy(t):kt(DV,null,String(t))}function xy(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:oD(t)}function r4(t,i){let n=0;const{shapeFlag:c}=t;if(i==null)i=null;else if(vs(i))n=16;else if(typeof i=="object")if(c&65){const I=i.default;I&&(I._c&&(I._d=!1),r4(t,I()),I._c&&(I._d=!0));return}else{n=32;const I=i._;!I&&!b9(i)?i._ctx=iI:I===3&&iI&&(iI.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else $s(i)?(i={default:i,_ctx:iI},n=32):(i=String(i),c&64?(n=16,i=[zr(i)]):n=8);t.children=i,t.shapeFlag|=n}function K3(...t){const i={};for(let n=0;nxI||iI;let bY,j3;{const t=hV(),i=(n,c)=>{let I;return(I=t[n])||(I=t[n]=[]),I.push(c),C=>{I.length>1?I.forEach(f=>f(C)):I[0](C)}};bY=i("__VUE_INSTANCE_SETTERS__",n=>xI=n),j3=i("__VUE_SSR_SETTERS__",n=>_U=n)}const KU=t=>{const i=xI;return bY(t),t.scope.on(),()=>{t.scope.off(),bY(i)}},z8=()=>{xI&&xI.scope.off(),bY(null)};function K9(t){return t.vnode.shapeFlag&4}let _U=!1;function mrA(t,i=!1,n=!1){i&&j3(i);const{props:c,children:I}=t.vnode,C=K9(t);jnA(t,c,C,i),XnA(t,I,n);const f=C?frA(t,i):void 0;return i&&j3(!1),f}function frA(t,i){const n=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,PnA);const{setup:c}=n;if(c){lD();const I=t.setupContext=c.length>1?DrA(t):null,C=KU(t),f=qU(c,t,0,[t.props,I]),w=J6(f);if(ID(),C(),(w||t.sp)&&!X_(t)&&M9(t),w){if(f.then(z8,z8),i)return f.then(_=>{Z8(t,_)}).catch(_=>{QV(_,t,0)});t.asyncDep=f}else Z8(t,f)}else j9(t)}function Z8(t,i,n){$s(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:Na(i)&&(t.setupState=l9(i)),j9(t)}function j9(t,i,n){const c=t.type;t.render||(t.render=c.render||TQ);{const I=KU(t);lD();try{xnA(t)}finally{ID(),I()}}}const yrA={get(t,i){return mu(t,"get",""),t[i]}};function DrA(t){const i=n=>{t.exposed=n||{}};return{attrs:new Proxy(t.attrs,yrA),slots:t.slots,emit:t.emit,expose:i}}function SV(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(l9(anA(t.exposed)),{get(i,n){if(n in i)return i[n];if(n in rU)return rU[n](t)},has(i,n){return n in i||n in rU}})):t.proxy}function SrA(t,i=!0){return $s(t)?t.displayName||t.name:t.name||i&&t.__name}function MrA(t){return $s(t)&&"__vccOpts"in t}const yt=(t,i)=>dnA(t,i,_U);function vrA(t,i,n){const c=arguments.length;return c===2?Na(i)&&!vs(i)?wU(i)?kt(t,null,[i]):kt(t,i):kt(t,null,i):(c>3?n=Array.prototype.slice.call(arguments,2):c===3&&wU(n)&&(n=[n]),kt(t,i,n))}const W3="3.5.13";/** * @vue/runtime-dom v3.5.13 * (c) 2018-present Yuxi (Evan) You and Vue contributors * @license MIT -**/let b3;const w8=typeof window<"u"&&window.trustedTypes;if(w8)try{b3=w8.createPolicy("vue",{createHTML:t=>t})}catch{}const S9=b3?t=>b3.createHTML(t):t=>t,$nA="http://www.w3.org/2000/svg",ArA="http://www.w3.org/1998/Math/MathML",am=typeof document<"u"?document:null,_8=am&&am.createElement("template"),erA={insert:(t,i,r)=>{i.insertBefore(t,r||null)},remove:t=>{const i=t.parentNode;i&&i.removeChild(t)},createElement:(t,i,r,l)=>{const I=i==="svg"?am.createElementNS($nA,t):i==="mathml"?am.createElementNS(ArA,t):r?am.createElement(t,{is:r}):am.createElement(t);return t==="select"&&l&&l.multiple!=null&&I.setAttribute("multiple",l.multiple),I},createText:t=>am.createTextNode(t),createComment:t=>am.createComment(t),setText:(t,i)=>{t.nodeValue=i},setElementText:(t,i)=>{t.textContent=i},parentNode:t=>t.parentNode,nextSibling:t=>t.nextSibling,querySelector:t=>am.querySelector(t),setScopeId(t,i){t.setAttribute(i,"")},insertStaticContent(t,i,r,l,I,h){const f=r?r.previousSibling:i.lastChild;if(I&&(I===h||I.nextSibling))for(;i.insertBefore(I.cloneNode(!0),r),!(I===h||!(I=I.nextSibling)););else{_8.innerHTML=S9(l==="svg"?`${t}`:l==="mathml"?`${t}`:t);const w=_8.content;if(l==="svg"||l==="mathml"){const _=w.firstChild;for(;_.firstChild;)w.appendChild(_.firstChild);w.removeChild(_)}i.insertBefore(w,r)}return[f?f.nextSibling:i.firstChild,r?r.previousSibling:i.lastChild]}},_y="transition",pL="animation",fU=Symbol("_vtc"),M9={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},trA=sI({},Z6,M9),irA=t=>(t.displayName="Transition",t.props=trA,t),orA=irA((t,{slots:i})=>XnA(zsA,srA(t),i)),iv=(t,i=[])=>{Ms(t)?t.forEach(r=>r(...i)):t&&t(...i)},T8=t=>t?Ms(t)?t.some(i=>i.length>1):t.length>1:!1;function srA(t){const i={};for(const Et in t)Et in M9||(i[Et]=t[Et]);if(t.css===!1)return i;const{name:r="v",type:l,duration:I,enterFromClass:h=`${r}-enter-from`,enterActiveClass:f=`${r}-enter-active`,enterToClass:w=`${r}-enter-to`,appearFromClass:_=h,appearActiveClass:G=f,appearToClass:U=w,leaveFromClass:j=`${r}-leave-from`,leaveActiveClass:lA=`${r}-leave-active`,leaveToClass:sA=`${r}-leave-to`}=t,mA=nrA(I),IA=mA&&mA[0],cA=mA&&mA[1],{onBeforeEnter:TA,onEnter:WA,onEnterCancelled:ue,onLeave:Ce,onLeaveCancelled:xe,onBeforeAppear:Qe=TA,onAppear:ut=WA,onAppearCancelled:ft=ue}=i,je=(Et,re,qe,yt)=>{Et._enterCancelled=yt,ov(Et,re?U:w),ov(Et,re?G:f),qe&&qe()},Mt=(Et,re)=>{Et._isLeaving=!1,ov(Et,j),ov(Et,sA),ov(Et,lA),re&&re()},jt=Et=>(re,qe)=>{const yt=Et?ut:WA,Me=()=>je(re,Et,qe);iv(yt,[re,Me]),N8(()=>{ov(re,Et?_:h),om(re,Et?U:w),T8(yt)||G8(re,l,IA,Me)})};return sI(i,{onBeforeEnter(Et){iv(TA,[Et]),om(Et,h),om(Et,f)},onBeforeAppear(Et){iv(Qe,[Et]),om(Et,_),om(Et,G)},onEnter:jt(!1),onAppear:jt(!0),onLeave(Et,re){Et._isLeaving=!0;const qe=()=>Mt(Et,re);om(Et,j),Et._enterCancelled?(om(Et,lA),L8()):(L8(),om(Et,lA)),N8(()=>{Et._isLeaving&&(ov(Et,j),om(Et,sA),T8(Ce)||G8(Et,l,cA,qe))}),iv(Ce,[Et,qe])},onEnterCancelled(Et){je(Et,!1,void 0,!0),iv(ue,[Et])},onAppearCancelled(Et){je(Et,!0,void 0,!0),iv(ft,[Et])},onLeaveCancelled(Et){Mt(Et),iv(xe,[Et])}})}function nrA(t){if(t==null)return null;if(Na(t))return[bj(t.enter),bj(t.leave)];{const i=bj(t);return[i,i]}}function bj(t){return isA(t)}function om(t,i){i.split(/\s+/).forEach(r=>r&&t.classList.add(r)),(t[fU]||(t[fU]=new Set)).add(i)}function ov(t,i){i.split(/\s+/).forEach(l=>l&&t.classList.remove(l));const r=t[fU];r&&(r.delete(i),r.size||(t[fU]=void 0))}function N8(t){requestAnimationFrame(()=>{requestAnimationFrame(t)})}let rrA=0;function G8(t,i,r,l){const I=t._endId=++rrA,h=()=>{I===t._endId&&l()};if(r!=null)return setTimeout(h,r);const{type:f,timeout:w,propCount:_}=arA(t,i);if(!f)return l();const G=f+"end";let U=0;const j=()=>{t.removeEventListener(G,lA),h()},lA=sA=>{sA.target===t&&++U>=_&&j()};setTimeout(()=>{U<_&&j()},w+1),t.addEventListener(G,lA)}function arA(t,i){const r=window.getComputedStyle(t),l=mA=>(r[mA]||"").split(", "),I=l(`${_y}Delay`),h=l(`${_y}Duration`),f=b8(I,h),w=l(`${pL}Delay`),_=l(`${pL}Duration`),G=b8(w,_);let U=null,j=0,lA=0;i===_y?f>0&&(U=_y,j=f,lA=h.length):i===pL?G>0&&(U=pL,j=G,lA=_.length):(j=Math.max(f,G),U=j>0?f>G?_y:pL:null,lA=U?U===_y?h.length:_.length:0);const sA=U===_y&&/\b(transform|all)(,|$)/.test(l(`${_y}Property`).toString());return{type:U,timeout:j,propCount:lA,hasTransform:sA}}function b8(t,i){for(;t.lengthk8(r)+k8(t[l])))}function k8(t){return t==="auto"?0:Number(t.slice(0,-1).replace(",","."))*1e3}function L8(){return document.body.offsetHeight}function grA(t,i,r){const l=t[fU];l&&(i=(i?[i,...l]:[...l]).join(" ")),i==null?t.removeAttribute("class"):r?t.setAttribute("class",i):t.className=i}const yY=Symbol("_vod"),v9=Symbol("_vsh"),Ka={beforeMount(t,{value:i},{transition:r}){t[yY]=t.style.display==="none"?"":t.style.display,r&&i?r.beforeEnter(t):mL(t,i)},mounted(t,{value:i},{transition:r}){r&&i&&r.enter(t)},updated(t,{value:i,oldValue:r},{transition:l}){!i!=!r&&(l?i?(l.beforeEnter(t),mL(t,!0),l.enter(t)):l.leave(t,()=>{mL(t,!1)}):mL(t,i))},beforeUnmount(t,{value:i}){mL(t,i)}};function mL(t,i){t.style.display=i?t[yY]:"none",t[v9]=!i}const crA=Symbol(""),lrA=/(^|;)\s*display\s*:/;function IrA(t,i,r){const l=t.style,I=fg(r);let h=!1;if(r&&!I){if(i)if(fg(i))for(const f of i.split(";")){const w=f.slice(0,f.indexOf(":")).trim();r[w]==null&&eY(l,w,"")}else for(const f in i)r[f]==null&&eY(l,f,"");for(const f in r)f==="display"&&(h=!0),eY(l,f,r[f])}else if(I){if(i!==r){const f=l[crA];f&&(r+=";"+f),l.cssText=r,h=lrA.test(r)}}else i&&t.removeAttribute("style");yY in t&&(t[yY]=h?l.display:"",t[v9]&&(l.display="none"))}const U8=/\s*!important$/;function eY(t,i,r){if(Ms(r))r.forEach(l=>eY(t,i,l));else if(r==null&&(r=""),i.startsWith("--"))t.setProperty(i,r);else{const l=urA(t,i);U8.test(r)?t.setProperty(rD(l),r.replace(U8,""),"important"):t[l]=r}}const F8=["Webkit","Moz","ms"],kj={};function urA(t,i){const r=kj[i];if(r)return r;let l=sh(i);if(l!=="filter"&&l in t)return kj[i]=l;l=tV(l);for(let I=0;ILj||(hrA.then(()=>Lj=0),Lj=Date.now());function QrA(t,i){const r=l=>{if(!l._vts)l._vts=Date.now();else if(l._vts<=r.attached)return;rB(prA(l,r.value),i,5,[l])};return r.value=t,r.attached=BrA(),r}function prA(t,i){if(Ms(i)){const r=t.stopImmediatePropagation;return t.stopImmediatePropagation=()=>{r.call(t),t._stopped=!0},i.map(l=>I=>!I._stopped&&l&&l(I))}else return i}const J8=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)>96&&t.charCodeAt(2)<123,mrA=(t,i,r,l,I,h)=>{const f=I==="svg";i==="class"?grA(t,l,f):i==="style"?IrA(t,r,l):$Y(i)?SW(i)||drA(t,i,r,l,h):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):frA(t,i,l,f))?(x8(t,i,l),!t.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&P8(t,i,l,f,h,i!=="value")):t._isVueCE&&(/[A-Z]/.test(i)||!fg(l))?x8(t,sh(i),l,h,i):(i==="true-value"?t._trueValue=l:i==="false-value"&&(t._falseValue=l),P8(t,i,l,f))};function frA(t,i,r,l){if(l)return!!(i==="innerHTML"||i==="textContent"||i in t&&J8(i)&&$s(r));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&t.tagName==="INPUT"||i==="type"&&t.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const I=t.tagName;if(I==="IMG"||I==="VIDEO"||I==="CANVAS"||I==="SOURCE")return!1}return J8(i)&&fg(r)?!1:i in t}const H8=t=>{const i=t.props["onUpdate:modelValue"]||!1;return Ms(i)?r=>X1(i,r):i};function yrA(t){t.target.composing=!0}function q8(t){const i=t.target;i.composing&&(i.composing=!1,i.dispatchEvent(new Event("input")))}const Uj=Symbol("_assign"),DrA={created(t,{modifiers:{lazy:i,trim:r,number:l}},I){t[Uj]=H8(I);const h=l||I.props&&I.props.type==="number";R_(t,i?"change":"input",f=>{if(f.target.composing)return;let w=t.value;r&&(w=w.trim()),h&&(w=p3(w)),t[Uj](w)}),r&&R_(t,"change",()=>{t.value=t.value.trim()}),i||(R_(t,"compositionstart",yrA),R_(t,"compositionend",q8),R_(t,"change",q8))},mounted(t,{value:i}){t.value=i??""},beforeUpdate(t,{value:i,oldValue:r,modifiers:{lazy:l,trim:I,number:h}},f){if(t[Uj]=H8(f),t.composing)return;const w=(h||t.type==="number")&&!/^0\d/.test(t.value)?p3(t.value):t.value,_=i??"";w!==_&&(document.activeElement===t&&t.type!=="range"&&(l&&i===r||I&&t.value.trim()===_)||(t.value=_))}},SrA=["ctrl","shift","alt","meta"],MrA={stop:t=>t.stopPropagation(),prevent:t=>t.preventDefault(),self:t=>t.target!==t.currentTarget,ctrl:t=>!t.ctrlKey,shift:t=>!t.shiftKey,alt:t=>!t.altKey,meta:t=>!t.metaKey,left:t=>"button"in t&&t.button!==0,middle:t=>"button"in t&&t.button!==1,right:t=>"button"in t&&t.button!==2,exact:(t,i)=>SrA.some(r=>t[`${r}Key`]&&!i.includes(r))},DE=(t,i)=>{const r=t._withMods||(t._withMods={}),l=i.join(".");return r[l]||(r[l]=(I,...h)=>{for(let f=0;f{const r=t._withKeys||(t._withKeys={}),l=i.join(".");return r[l]||(r[l]=I=>{if(!("key"in I))return;const h=rD(I.key);if(i.some(f=>f===h||vrA[f]===h))return t(I)})},RrA=sI({patchProp:mrA},erA);let K8;function w9(){return K8||(K8=SnA(RrA))}const pv=(...t)=>{w9().render(...t)},wrA=(...t)=>{const i=w9().createApp(...t),{mount:r}=i;return i.mount=l=>{const I=TrA(l);if(!I)return;const h=i._component;!$s(h)&&!h.render&&!h.template&&(h.template=I.innerHTML),I.nodeType===1&&(I.textContent="");const f=r(I,!1,_rA(I));return I instanceof Element&&(I.removeAttribute("v-cloak"),I.setAttribute("data-v-app","")),f},i};function _rA(t){if(t instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&t instanceof MathMLElement)return"mathml"}function TrA(t){return fg(t)?document.querySelector(t):t}function NrA(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _L={exports:{}},tY={exports:{}},GrA=tY.exports,j8;function _9(){return j8||(j8=1,function(t,i){(function(r,l){t.exports=l()})(GrA,function(){const r=p=>p===void 0,l=p=>typeof p=="string",I=p=>{var B;return(B=Object.prototype.toString.call(p).match(/^\[object (.*)\]$/))===null||B===void 0?void 0:B[1].toLowerCase()},h=p=>typeof Array.isArray=="function"?Array.isArray(p):I(p)==="array",f=p=>p!==null&&typeof p=="object",w=p=>h(p)||f(p),_=p=>{if(typeof p!="string")return!1;const B=p[0];return!/[^a-zA-Z0-9]/.test(B)},G=p=>{if(typeof p!="object"||p===null)return!1;const B=Object.getPrototypeOf(p);if(B===null)return!0;let v=B;for(;Object.getPrototypeOf(v)!==null;)v=Object.getPrototypeOf(v);return B===v};function U(p=99999999){return Math.round(Math.random()*p)}const j=(p,B,v,N)=>{if(!w(p)||!w(B))return 0;let O=0;const z=Object.keys(B);let X;for(let rA=0,DA=z.length;rA"u"&&typeof uni.requireNativePlugin=="function",io=Et&&typeof wx.miniapp=="object",Eo=typeof uni<"u",Vs=yt&&typeof tt.enterChat=="function",ki=Et||qe||yt||Oe||gt||To||Fi,ns=typeof window>"u"&&!ki&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,jo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),Ao=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,Zt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!jo,oo=qe?qq:yt?tt:Oe?swan:gt?my:Et?wx:To?uni:Fi?jd:{},bi=Zt&&window&&window.navigator&&window.navigator.userAgent||"",vs=/(micromessenger|webbrowser)/i.test(bi),HA=function(){let p="WEB";return vs?p="WEB":qe?p="QQ_MP":yt?p="TT_MP":Oe?p="BAIDU_MP":gt?p="ALI_MP":Et?p=io?"DONUT_NATIVE_APP":"WX_MP":To?p="UNI_NATIVE_APP":ns?p="NS_NATIVE_APP":jo&&(p="RN_NATIVE_APP"),sA[p]}(),ce=/iPad/i.test(bi),Ve=/iPhone/i.test(bi)&&!ce,Ot=/iPod/i.test(bi),nt=Ve||ce||Ot,It=function(){const p=bi.match(/OS (\d+)_/i);return p&&p[1]?p[1]:null}(),ei=/Android/i.test(bi),ti=function(){const p=bi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!p)return null;const B=p[1]&&parseFloat(p[1]),v=p[2]&&parseFloat(p[2]);return B&&v?parseFloat(`${p[1]}.${p[2]}`):B||null}(),be=/Firefox/i.test(bi),Ze=/Edge/i.test(bi),wt=!Ze&&/Chrome/i.test(bi),Nt=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const p=/MSIE\s(\d+)\.\d/.exec(bi);let B=p&&parseFloat(p[1]);return!B&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(B=11),B}(),po=/Safari/i.test(bi)&&!wt&&!ei&&!Ze,No=/Windows/i.test(bi),so=/MAC OS X/i.test(bi),Go=Zt&&typeof Worker<"u"&&!Nt,An=ei||nt,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:p}=window.navigator;return!(!nt||p||po)}();function Es(){let p="unknown";if(so&&(p="mac"),No&&(p="windows"),nt&&(p="ios"),ei&&(p="android"),ki)try{const{platform:B}=oo.getSystemInfoSync();B!==void 0&&(p=B)}catch(B){console.error(B)}return p}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function Do(p,B){var v={};for(var N in p)Object.prototype.hasOwnProperty.call(p,N)&&B.indexOf(N)<0&&(v[N]=p[N]);if(p!=null&&typeof Object.getOwnPropertySymbols=="function"){var O=0;for(N=Object.getOwnPropertySymbols(p);O{oo.request({url:v,data:N,method:B,timeout:O,header:{"content-type":zr},success:rA=>z(rA.data),fail:()=>X(new Error(`{"message":"Network error","code":${Jn}}`))})}):an?void 0:new Promise((z,X)=>{const rA=new XMLHttpRequest,DA=setTimeout(()=>{rA.abort(),X(new Error(`{"message":"Request timeout","code":${Qr}}`))},O);rA.onreadystatechange=function(){if(rA.readyState===4)if(clearTimeout(DA),rA.status===200||rA.status===304)try{z(rA.responseText?JSON.parse(rA.responseText):null)}catch{z(rA.responseText)}else X(new Error(`{"message":"Network error","code":${Jn}}`))},rA.open(B,v,!0),rA.setRequestHeader("Content-type",zr),rA.send(N||null)})})}function Rs(p){if(p==null)return!0;if(typeof p=="boolean")return!1;if(typeof p=="number")return p===0;if(typeof p=="string"||typeof p=="function"||Array.isArray(p))return p.length===0;if(p instanceof Error)return p.message==="";if(G(p)){for(const B in p)if(Object.prototype.hasOwnProperty.call(p,B))return!1;return!0}return(Object.prototype.toString.call(p)==="[object Map]"||Object.prototype.toString.call(p)==="[object Set]"||Object.prototype.toString.call(p)==="[object File]")&&p.size===0}function or(p,B){if(p===null||typeof p!="object")return p;const v=B||new WeakMap;if(v.has(p))return v.get(p);if(p instanceof Date)return new Date(p.getTime());if(p instanceof RegExp)return new RegExp(p.source,p.flags);if(p instanceof Map){const z=new Map;return v.set(p,z),p.forEach((X,rA)=>{z.set(or(rA,v),or(X,v))}),z}if(p instanceof Set){const z=new Set;return v.set(p,z),p.forEach(X=>{z.add(or(X,v))}),z}if(Array.isArray(p)){const z=[];return v.set(p,z),p.forEach(X=>{z.push(or(X,v))}),z}const N=Object.getPrototypeOf(p),O=Object.create(N);return v.set(p,O),[...Object.getOwnPropertyNames(p),...Object.getOwnPropertySymbols(p)].forEach(z=>{if(z==="__ob__"||z==="__v_skip"||z==="__v_isRef"||z==="__v_isReadonly")return;const X=Object.getOwnPropertyDescriptor(p,z);X&&(X.get||X.set?Object.defineProperty(O,z,X):O[z]=or(p[z],v))}),O}function en(p,B,v){const N=new WeakSet,O=(z,X)=>{if(B&&(X=B(z,X)),X===void 0)return"undefined";if(X===null)return null;if(Number.isNaN(X))return"NaN";if(X===1/0)return"Infinity";if(X===-1/0)return"-Infinity";if(typeof X=="function")return`[Function: ${X.name||"anonymous"}]`;if(typeof X=="symbol")return X.toString();if(typeof X=="bigint")return`${X.toString()}n`;if(typeof X=="object"&&X!==null){if(N.has(X))return"[Circular]";N.add(X)}return X instanceof Date?X.toISOString():X instanceof Error?{name:X.name,message:X.message}:X instanceof Map?{dataType:"Map",value:Array.from(X.entries())}:X instanceof Set?{dataType:"Set",value:Array.from(X.values())}:X};try{return JSON.stringify(p,O,v)}catch(z){return console.error("Failed to stringify:",z),""}}function wn(){let p,B;return{promise:new Promise((v,N)=>{p=v,B=N}),resolve:p,reject:B}}var qt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:ti,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gt,IN_BAIDU_MINI_APP:Oe,IN_BROWSER:Zt,IN_DONUT_NATIVE_APP:io,IN_FEISHU_MINI_APP:Vs,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:ns,IN_QQ_MINI_APP:qe,IN_RN_APP:jo,IN_TT_MINI_APP:yt,IN_TT_MINI_GAME:Me,IN_UNI_APP:Eo,IN_UNI_NATIVE_APP:To,IN_WX_MINI_APP:Et,IN_WX_MINI_APP_DESK:jt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:Ao,IOS_VERSION:It,IS_ANDROID:ei,IS_CHROME:wt,IS_EDGE:Ze,IS_FIREFOX:be,IS_IE:Nt,IS_IOS:nt,IS_IPAD:ce,IS_IPHONE:Ve,IS_IPOD:Ot,IS_MAC:so,IS_SAFARI:po,IS_WECHAT:vs,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:oo,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:or,deepMerge:j,generatePromise:wn,getPlatformType:Es,getType:I,httpRequest:Pi,isArray:h,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:p=>p!==null&&(typeof p=="number"&&!Number.isNaN(p-0)||typeof p=="object"&&p.constructor===Number),isObject:f,isPlainObject:G,isString:l,isUndefined:r,isUniIOSApp:function(){return To&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:HA,randomInt:U,randomString:function(){const p="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let B="";for(let v=32;v>0;--v)B+=p[Math.floor(62*Math.random())];return B},safeStringify:en});class On{constructor(){this.listeners={}}on(B,v,N){this.listeners[B]||(this.listeners[B]=[]),this.listeners[B].push({fn:v,context:N})}off(B,v,N){var O;v&&(this.listeners[B]=(O=this.listeners[B])===null||O===void 0?void 0:O.filter(z=>{const X=z.fn===v,rA=!N||z.context===N;return!(X&&rA)}))}emit(B,...v){const N=this.listeners[B];N&&N.forEach(O=>{const{fn:z,context:X}=O;try{z.apply(X,v)}catch(rA){console.warn(`Error in event handler for ${B} error: ${en(rA)}`)}})}once(B,v,N){const O=(...z)=>{v.apply(N,z),this.off(B,O)};this.on(B,O)}}(function(p){p.BUSINESS_COMMAND="business_command",p.C2C_REALTIME_MESSAGE="c2c_realtime_message",p.C2C_MESSAGE_MODIFIED="c2c_message_modified",p.C2C_REVOKED_MESSAGE="c2c_message_revoked",p.GROUP_REALTIME_MESSAGE="group_realtime_message",p.GROUP_MESSAGE_MODIFIED="group_message_modified",p.GROUP_MESSAGE_REVOKED="group_message_revoked",p.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",p.MESSAGE_REACTION_UPDATED="message_reaction_updated",p.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",p.GROUP_AT_TIPS="group_at_tips",p.USER_STATUS_UPDATE="user_status_update",p.FRIEND_LIST_MODIFIED="friend_list_modified",p.PROFILE_MODIFIED="profile_modified",p.CONV_MODIFIED="conversation_modified",p.GROUP_TIPS_NOTIFICATION="group_tips_notification",p.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",p.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",p.GROUP_SYSTEM_NOTIFICATION="group_system_notification",p.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",p.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",p.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",p.FOLLOW_LIST_UPDATED="follow_list_updated",p.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",p.ALL_MESSAGE_READ="all_message_read",p.CONVERSATION_MARK_UPDATED="conversation_mark_updated",p.CONVERSATION_GROUP_ADD="conversation_group_add",p.CONVERSATION_GROUP_DELETED="conversation_group_deleted",p.CONVERSATION_GROUP_UPDATED="conversation_group_updated",p.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",p.TOPIC_AT_TIPS="topic_at_tips",p.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",p.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",p.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",p.TOPIC_LATEST_MESSAGE="topic_latest_message",p.GROUP_MESSAGE_PINNED="group_message_pinned"})(qt||(qt={}));const Gn=[16,17];function Js(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(N=>{var O;N.GroupInfo.MillionGroupFlag===2?v.push(qt.TOPIC_TIPS_NOTIFICATION):Gn.includes((O=N?.MsgBody)===null||O===void 0?void 0:O.OpType)?v.push(qt.GROUP_MESSAGE_PINNED):v.push(qt.GROUP_TIPS_NOTIFICATION)}),v}const pr=[{conditions:[{type:"event",value:100}],subType:qt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:qt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:qt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:qt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:qt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:qt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:qt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:qt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:qt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:qt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(p){var B;const v=[];return(B=p?.C2cNotifyMsgArray)===null||B===void 0||B.forEach(N=>{N.WithdrawC2cMsgNotify&&v.push(qt.C2C_REVOKED_MESSAGE),N.C2cReadedReceipt&&v.push(qt.C2C_MESSAGE_PEER_READ),N.ReadC2cMsgNotify&&v.push(qt.C2C_MESSAGE_READ_SYNC),N.MuteNotificationsSync&&v.push(qt.C2C_REMIND_TYPE_SYNC)}),v}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(N=>{Array.isArray(N.MsgBody.GroupWithdrawInfoArray)?v.push(qt.GROUP_MESSAGE_REVOKED):Array.isArray(N.MsgBody.GroupMsgReceiptList)?v.push(qt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(N.MsgBody.GroupReadInfoArray)?N.MsgBody.GroupReadInfoArray[0].TopicId?v.push(qt.TOPIC_MESSAGE_READ_SYNC):v.push(qt.GROUP_MESSAGE_READ_SYNC):N.GroupInfo.MillionGroupFlag===2?v.push(qt.TOPIC_SYSTEM_NOTIFICATION):v.push(qt.GROUP_SYSTEM_NOTIFICATION)}),v}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(N=>{const{GroupAtTips:{TopicId:O}}=N;O?v.push(qt.TOPIC_AT_TIPS):v.push(qt.GROUP_AT_TIPS)}),v}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(p){var B;const v=[];return(B=p?.RecentContactMod)===null||B===void 0||B.forEach(N=>{switch(N.PushType){case je.CONV_MARK_UPDATED:v.push(qt.CONVERSATION_MARK_UPDATED);break;case je.CONV_GROUP_ADDED:v.push(qt.CONVERSATION_GROUP_ADD);break;case je.CONV_GROUP_DELETED:v.push(qt.CONVERSATION_GROUP_DELETED);break;case je.CONV_GROUP_UPDATED:v.push(qt.CONVERSATION_GROUP_UPDATED);break;default:v.push(qt.CONV_MODIFIED)}}),v}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:qt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:qt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:qt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:qt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:qt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:qt.ALL_MESSAGE_READ}];var Pn;function mr(p){var B;const v=Array.isArray((B=p?.body)===null||B===void 0?void 0:B.EventArray)?p.body.EventArray:[],N=[];return v.forEach(O=>{O.Flag=p.body.Flag;const z=pr.find(rA=>rA.conditions.every(DA=>{switch(DA.type){case"event":return O.Event===DA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(O,DA.value);default:return!1}}));if(!z)return null;let X=[];typeof z.subTypeParser=="function"?X=z.subTypeParser(O):z.subType&&(X=z.subType),Array.isArray(X)?X.forEach(rA=>{N.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${rA}`,data:O})}):N.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${X}`,data:O})}),N}(function(p){p.SERVER_PUSH_MESSAGE="im_open_push.msg_push",p.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",p.ERROR="error"})(Pn||(Pn={}));const mo={[Pn.SERVER_PUSH_MESSAGE]:mr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:mr,[Pn.ERROR]:function(p){const{errorCode:B}=p;return[{type:`error:${B}`,data:p}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=qt}subscribeInnerEvent(p,B,v,N,O){var z;let X,rA,DA,GA;["string","number"].includes(typeof B)?(DA=`${p}:${B}`,GA=v,rA=N,X=O):(DA=p,GA=B,rA=v,X=typeof N=="function"?N:void 0),X?this._subscribeWithFilter(DA,GA,rA,X):(z=this._innerEventEmitter)===null||z===void 0||z.on(DA,GA,rA)}emitInnerEvent(p,B){var v,N;if((v=this._innerEventEmitter)===null||v===void 0||v.emit(p,B),Object.keys(mo).includes(p)){const O=(N=mo[p])===null||N===void 0?void 0:N.call(mo,B);O?.forEach(z=>{var X;z&&((X=this._innerEventEmitter)===null||X===void 0||X.emit(z.type,z.data))})}}subscribeOuterEvent(p,B,v){var N;(N=this._outerEventEmitter)===null||N===void 0||N.on(p,B,v)}unSubscribeOuterEvent(p,B,v){var N;(N=this._outerEventEmitter)===null||N===void 0||N.off(p,B,v)}unSubscribeInnerEvent(p,B,v,N){if(["string","number"].includes(typeof B)){const O=v,z=`${p}:${B}`;this._unsubscribeEvent(z,O,N)}else{const O=B;this._unsubscribeEvent(p,O,v)}}emitOuterEvent(p,B){var v;(v=this._outerEventEmitter)===null||v===void 0||v.emit(p,B)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(p,B,v,N){var O;const z=X=>{N.call(v,X)&&B.call(v,X)};this._filteredCallbackMap.has(p)||this._filteredCallbackMap.set(p,[]),this._filteredCallbackMap.get(p).push({originalCallback:B,filteredCallback:z,filter:N,context:v}),(O=this._innerEventEmitter)===null||O===void 0||O.on(p,z,v)}_unsubscribeEvent(p,B,v){var N,O;const z=this._filteredCallbackMap.get(p);if(z){const X=z.findIndex(rA=>rA.originalCallback===B&&rA.context===v);if(X!==-1){const{filteredCallback:rA}=z[X];return(N=this._innerEventEmitter)===null||N===void 0||N.off(p,rA,v),z.splice(X,1),void(z.length===0&&this._filteredCallbackMap.delete(p))}}(O=this._innerEventEmitter)===null||O===void 0||O.off(p,B,v)}};class Sl{constructor(){this._socket=null}connectSocket(B){return this._socket=new WebSocket(B),this._socket}send(B){var v,N;try{(v=this._socket)===null||v===void 0||v.send(B)}catch(O){(N=this._onSendFail)===null||N===void 0||N.call(this,O)}}bindSocketHandlers(B){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=v,this._socket.onmessage=N,this._socket.onclose=O,this._socket.onerror=z,this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(B){this._onError=B.onError}connectSocket(B){const v=this;return this._socket=oo.connectSocket({url:B,header:{"content-type":"application/json"},complete:()=>{},fail:N=>v._onError(N)}),this._socket}send(B){var v;(v=this._socket)===null||v===void 0||v.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(v),this._socket.onMessage(N),this._socket.onError(z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const fr="CONNECT",Ls="SEND",Jc="DISCONNECT",ms="OPEN",as="MESSAGE",Ru="CLOSE",Wa="ERROR",Cs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(B){const v=new Blob([` +**/let z3;const X8=typeof window<"u"&&window.trustedTypes;if(X8)try{z3=X8.createPolicy("vue",{createHTML:t=>t})}catch{}const W9=z3?t=>z3.createHTML(t):t=>t,RrA="http://www.w3.org/2000/svg",wrA="http://www.w3.org/1998/Math/MathML",lm=typeof document<"u"?document:null,$8=lm&&lm.createElement("template"),_rA={insert:(t,i,n)=>{i.insertBefore(t,n||null)},remove:t=>{const i=t.parentNode;i&&i.removeChild(t)},createElement:(t,i,n,c)=>{const I=i==="svg"?lm.createElementNS(RrA,t):i==="mathml"?lm.createElementNS(wrA,t):n?lm.createElement(t,{is:n}):lm.createElement(t);return t==="select"&&c&&c.multiple!=null&&I.setAttribute("multiple",c.multiple),I},createText:t=>lm.createTextNode(t),createComment:t=>lm.createComment(t),setText:(t,i)=>{t.nodeValue=i},setElementText:(t,i)=>{t.textContent=i},parentNode:t=>t.parentNode,nextSibling:t=>t.nextSibling,querySelector:t=>lm.querySelector(t),setScopeId(t,i){t.setAttribute(i,"")},insertStaticContent(t,i,n,c,I,C){const f=n?n.previousSibling:i.lastChild;if(I&&(I===C||I.nextSibling))for(;i.insertBefore(I.cloneNode(!0),n),!(I===C||!(I=I.nextSibling)););else{$8.innerHTML=W9(c==="svg"?`${t}`:c==="mathml"?`${t}`:t);const w=$8.content;if(c==="svg"||c==="mathml"){const _=w.firstChild;for(;_.firstChild;)w.appendChild(_.firstChild);w.removeChild(_)}i.insertBefore(w,n)}return[f?f.nextSibling:i.firstChild,n?n.previousSibling:i.lastChild]}},Gy="transition",ML="animation",TU=Symbol("_vtc"),z9={name:String,type:String,css:{type:Boolean,default:!0},duration:[String,Number,Object],enterFromClass:String,enterActiveClass:String,enterToClass:String,appearFromClass:String,appearActiveClass:String,appearToClass:String,leaveFromClass:String,leaveActiveClass:String,leaveToClass:String},TrA=nI({},m9,z9),NrA=t=>(t.displayName="Transition",t.props=TrA,t),GrA=NrA((t,{slots:i})=>vrA(SnA,brA(t),i)),nv=(t,i=[])=>{vs(t)?t.forEach(n=>n(...i)):t&&t(...i)},AZ=t=>t?vs(t)?t.some(i=>i.length>1):t.length>1:!1;function brA(t){const i={};for(const ct in t)ct in z9||(i[ct]=t[ct]);if(t.css===!1)return i;const{name:n="v",type:c,duration:I,enterFromClass:C=`${n}-enter-from`,enterActiveClass:f=`${n}-enter-active`,enterToClass:w=`${n}-enter-to`,appearFromClass:_=C,appearActiveClass:N=f,appearToClass:L=w,leaveFromClass:q=`${n}-leave-from`,leaveActiveClass:lA=`${n}-leave-active`,leaveToClass:tA=`${n}-leave-to`}=t,BA=krA(I),IA=BA&&BA[0],gA=BA&&BA[1],{onBeforeEnter:RA,onEnter:HA,onEnterCancelled:ZA,onLeave:KA,onLeaveCancelled:me,onBeforeAppear:ae=RA,onAppear:gt=HA,onAppearCancelled:dt=ZA}=i,We=(ct,ce,Ve,Dt)=>{ct._enterCancelled=Dt,rv(ct,ce?L:w),rv(ct,ce?N:f),Ve&&Ve()},lt=(ct,ce)=>{ct._isLeaving=!1,rv(ct,q),rv(ct,tA),rv(ct,lA),ce&&ce()},wt=ct=>(ce,Ve)=>{const Dt=ct?gt:HA,ti=()=>We(ce,ct,Ve);nv(Dt,[ce,ti]),eZ(()=>{rv(ce,ct?_:C),rm(ce,ct?L:w),AZ(Dt)||tZ(ce,c,IA,ti)})};return nI(i,{onBeforeEnter(ct){nv(RA,[ct]),rm(ct,C),rm(ct,f)},onBeforeAppear(ct){nv(ae,[ct]),rm(ct,_),rm(ct,N)},onEnter:wt(!1),onAppear:wt(!0),onLeave(ct,ce){ct._isLeaving=!0;const Ve=()=>lt(ct,ce);rm(ct,q),ct._enterCancelled?(rm(ct,lA),sZ()):(sZ(),rm(ct,lA)),eZ(()=>{ct._isLeaving&&(rv(ct,q),rm(ct,tA),AZ(KA)||tZ(ct,c,gA,Ve))}),nv(KA,[ct,Ve])},onEnterCancelled(ct){We(ct,!1,void 0,!0),nv(ZA,[ct])},onAppearCancelled(ct){We(ct,!0,void 0,!0),nv(dt,[ct])},onLeaveCancelled(ct){lt(ct),nv(me,[ct])}})}function krA(t){if(t==null)return null;if(Na(t))return[Wj(t.enter),Wj(t.leave)];{const i=Wj(t);return[i,i]}}function Wj(t){return NsA(t)}function rm(t,i){i.split(/\s+/).forEach(n=>n&&t.classList.add(n)),(t[TU]||(t[TU]=new Set)).add(i)}function rv(t,i){i.split(/\s+/).forEach(c=>c&&t.classList.remove(c));const n=t[TU];n&&(n.delete(i),n.size||(t[TU]=void 0))}function eZ(t){requestAnimationFrame(()=>{requestAnimationFrame(t)})}let LrA=0;function tZ(t,i,n,c){const I=t._endId=++LrA,C=()=>{I===t._endId&&c()};if(n!=null)return setTimeout(C,n);const{type:f,timeout:w,propCount:_}=UrA(t,i);if(!f)return c();const N=f+"end";let L=0;const q=()=>{t.removeEventListener(N,lA),C()},lA=tA=>{tA.target===t&&++L>=_&&q()};setTimeout(()=>{L<_&&q()},w+1),t.addEventListener(N,lA)}function UrA(t,i){const n=window.getComputedStyle(t),c=BA=>(n[BA]||"").split(", "),I=c(`${Gy}Delay`),C=c(`${Gy}Duration`),f=iZ(I,C),w=c(`${ML}Delay`),_=c(`${ML}Duration`),N=iZ(w,_);let L=null,q=0,lA=0;i===Gy?f>0&&(L=Gy,q=f,lA=C.length):i===ML?N>0&&(L=ML,q=N,lA=_.length):(q=Math.max(f,N),L=q>0?f>N?Gy:ML:null,lA=L?L===Gy?C.length:_.length:0);const tA=L===Gy&&/\b(transform|all)(,|$)/.test(c(`${Gy}Property`).toString());return{type:L,timeout:q,propCount:lA,hasTransform:tA}}function iZ(t,i){for(;t.lengthoZ(n)+oZ(t[c])))}function oZ(t){return t==="auto"?0:Number(t.slice(0,-1).replace(",","."))*1e3}function sZ(){return document.body.offsetHeight}function FrA(t,i,n){const c=t[TU];c&&(i=(i?[i,...c]:[...c]).join(" ")),i==null?t.removeAttribute("class"):n?t.setAttribute("class",i):t.className=i}const kY=Symbol("_vod"),Z9=Symbol("_vsh"),Ka={beforeMount(t,{value:i},{transition:n}){t[kY]=t.style.display==="none"?"":t.style.display,n&&i?n.beforeEnter(t):vL(t,i)},mounted(t,{value:i},{transition:n}){n&&i&&n.enter(t)},updated(t,{value:i,oldValue:n},{transition:c}){!i!=!n&&(c?i?(c.beforeEnter(t),vL(t,!0),c.enter(t)):c.leave(t,()=>{vL(t,!1)}):vL(t,i))},beforeUnmount(t,{value:i}){vL(t,i)}};function vL(t,i){t.style.display=i?t[kY]:"none",t[Z9]=!i}const OrA=Symbol(""),PrA=/(^|;)\s*display\s*:/;function xrA(t,i,n){const c=t.style,I=fg(n);let C=!1;if(n&&!I){if(i)if(fg(i))for(const f of i.split(";")){const w=f.slice(0,f.indexOf(":")).trim();n[w]==null&&uY(c,w,"")}else for(const f in i)n[f]==null&&uY(c,f,"");for(const f in n)f==="display"&&(C=!0),uY(c,f,n[f])}else if(I){if(i!==n){const f=c[OrA];f&&(n+=";"+f),c.cssText=n,C=PrA.test(n)}}else i&&t.removeAttribute("style");kY in t&&(t[kY]=C?c.display:"",t[Z9]&&(c.display="none"))}const nZ=/\s*!important$/;function uY(t,i,n){if(vs(n))n.forEach(c=>uY(t,i,c));else if(n==null&&(n=""),i.startsWith("--"))t.setProperty(i,n);else{const c=YrA(t,i);nZ.test(n)?t.setProperty(cD(c),n.replace(nZ,""),"important"):t[c]=n}}const rZ=["Webkit","Moz","ms"],zj={};function YrA(t,i){const n=zj[i];if(n)return n;let c=gh(i);if(c!=="filter"&&c in t)return zj[i]=c;c=CV(c);for(let I=0;IZj||(qrA.then(()=>Zj=0),Zj=Date.now());function jrA(t,i){const n=c=>{if(!c._vts)c._vts=Date.now();else if(c._vts<=n.attached)return;cB(WrA(c,n.value),i,5,[c])};return n.value=t,n.attached=KrA(),n}function WrA(t,i){if(vs(i)){const n=t.stopImmediatePropagation;return t.stopImmediatePropagation=()=>{n.call(t),t._stopped=!0},i.map(c=>I=>!I._stopped&&c&&c(I))}else return i}const uZ=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)>96&&t.charCodeAt(2)<123,zrA=(t,i,n,c,I,C)=>{const f=I==="svg";i==="class"?FrA(t,c,f):i==="style"?xrA(t,n,c):uV(i)?KW(i)||JrA(t,i,n,c,C):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):ZrA(t,i,c,f))?(cZ(t,i,c),!t.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&gZ(t,i,c,f,C,i!=="value")):t._isVueCE&&(/[A-Z]/.test(i)||!fg(c))?cZ(t,gh(i),c,C,i):(i==="true-value"?t._trueValue=c:i==="false-value"&&(t._falseValue=c),gZ(t,i,c,f))};function ZrA(t,i,n,c){if(c)return!!(i==="innerHTML"||i==="textContent"||i in t&&uZ(i)&&$s(n));if(i==="spellcheck"||i==="draggable"||i==="translate"||i==="form"||i==="list"&&t.tagName==="INPUT"||i==="type"&&t.tagName==="TEXTAREA")return!1;if(i==="width"||i==="height"){const I=t.tagName;if(I==="IMG"||I==="VIDEO"||I==="CANVAS"||I==="SOURCE")return!1}return uZ(i)&&fg(n)?!1:i in t}const EZ=t=>{const i=t.props["onUpdate:modelValue"]||!1;return vs(i)?n=>cY(i,n):i};function XrA(t){t.target.composing=!0}function dZ(t){const i=t.target;i.composing&&(i.composing=!1,i.dispatchEvent(new Event("input")))}const Xj=Symbol("_assign"),$rA={created(t,{modifiers:{lazy:i,trim:n,number:c}},I){t[Xj]=EZ(I);const C=c||I.props&&I.props.type==="number";T_(t,i?"change":"input",f=>{if(f.target.composing)return;let w=t.value;n&&(w=w.trim()),C&&(w=L3(w)),t[Xj](w)}),n&&T_(t,"change",()=>{t.value=t.value.trim()}),i||(T_(t,"compositionstart",XrA),T_(t,"compositionend",dZ),T_(t,"change",dZ))},mounted(t,{value:i}){t.value=i??""},beforeUpdate(t,{value:i,oldValue:n,modifiers:{lazy:c,trim:I,number:C}},f){if(t[Xj]=EZ(f),t.composing)return;const w=(C||t.type==="number")&&!/^0\d/.test(t.value)?L3(t.value):t.value,_=i??"";w!==_&&(document.activeElement===t&&t.type!=="range"&&(c&&i===n||I&&t.value.trim()===_)||(t.value=_))}},AaA=["ctrl","shift","alt","meta"],eaA={stop:t=>t.stopPropagation(),prevent:t=>t.preventDefault(),self:t=>t.target!==t.currentTarget,ctrl:t=>!t.ctrlKey,shift:t=>!t.shiftKey,alt:t=>!t.altKey,meta:t=>!t.metaKey,left:t=>"button"in t&&t.button!==0,middle:t=>"button"in t&&t.button!==1,right:t=>"button"in t&&t.button!==2,exact:(t,i)=>AaA.some(n=>t[`${n}Key`]&&!i.includes(n))},cd=(t,i)=>{const n=t._withMods||(t._withMods={}),c=i.join(".");return n[c]||(n[c]=(I,...C)=>{for(let f=0;f{const n=t._withKeys||(t._withKeys={}),c=i.join(".");return n[c]||(n[c]=I=>{if(!("key"in I))return;const C=cD(I.key);if(i.some(f=>f===C||taA[f]===C))return t(I)})},oaA=nI({patchProp:zrA},_rA);let CZ;function X9(){return CZ||(CZ=ArA(oaA))}const yv=(...t)=>{X9().render(...t)},saA=(...t)=>{const i=X9().createApp(...t),{mount:n}=i;return i.mount=c=>{const I=raA(c);if(!I)return;const C=i._component;!$s(C)&&!C.render&&!C.template&&(C.template=I.innerHTML),I.nodeType===1&&(I.textContent="");const f=n(I,!1,naA(I));return I instanceof Element&&(I.removeAttribute("v-cloak"),I.setAttribute("data-v-app","")),f},i};function naA(t){if(t instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&t instanceof MathMLElement)return"mathml"}function raA(t){return fg(t)?document.querySelector(t):t}function aaA(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var LL={exports:{}},EY={exports:{}},gaA=EY.exports,hZ;function $9(){return hZ||(hZ=1,function(t,i){(function(n,c){t.exports=c()})(gaA,function(){const n=p=>p===void 0,c=p=>typeof p=="string",I=p=>{var B;return(B=Object.prototype.toString.call(p).match(/^\[object (.*)\]$/))===null||B===void 0?void 0:B[1].toLowerCase()},C=p=>typeof Array.isArray=="function"?Array.isArray(p):I(p)==="array",f=p=>p!==null&&typeof p=="object",w=p=>C(p)||f(p),_=p=>{if(typeof p!="string")return!1;const B=p[0];return!/[^a-zA-Z0-9]/.test(B)},N=p=>{if(typeof p!="object"||p===null)return!1;const B=Object.getPrototypeOf(p);if(B===null)return!0;let v=B;for(;Object.getPrototypeOf(v)!==null;)v=Object.getPrototypeOf(v);return B===v};function L(p=99999999){return Math.round(Math.random()*p)}const q=(p,B,v,G)=>{if(!w(p)||!w(B))return 0;let O=0;const z=Object.keys(B);let X;for(let rA=0,DA=z.length;rA"u"&&typeof uni.requireNativePlugin=="function",to=ct&&typeof wx.miniapp=="object",so=typeof uni<"u",ks=Dt&&typeof tt.enterChat=="function",Gi=ct||Ve||Dt||Pt||oi||Co||Ni,As=typeof window>"u"&&!Gi&&typeof mg<"u"&&mg.NativeScriptGlobals!==void 0,Lo=typeof mg<"u"&&(mg.nativeModuleProxy!==void 0||mg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,zt=typeof uni<"u"?!Gi:typeof window<"u"&&!Gi&&!Lo,Ao=Ve?qq:Dt?tt:Pt?swan:oi?my:ct?wx:Co?uni:Ni?jd:{},Ri=zt&&window&&window.navigator&&window.navigator.userAgent||"",Es=/(micromessenger|webbrowser)/i.test(Ri),VA=function(){let p="WEB";return Es?p="WEB":Ve?p="QQ_MP":Dt?p="TT_MP":Pt?p="BAIDU_MP":oi?p="ALI_MP":ct?p=to?"DONUT_NATIVE_APP":"WX_MP":Co?p="UNI_NATIVE_APP":As?p="NS_NATIVE_APP":Lo&&(p="RN_NATIVE_APP"),tA[p]}(),Ee=/iPad/i.test(Ri),Je=/iPhone/i.test(Ri)&&!Ee,Ut=/iPod/i.test(Ri),ot=Je||Ee||Ut,ut=function(){const p=Ri.match(/OS (\d+)_/i);return p&&p[1]?p[1]:null}(),$t=/Android/i.test(Ri),Zt=function(){const p=Ri.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!p)return null;const B=p[1]&&parseFloat(p[1]),v=p[2]&&parseFloat(p[2]);return B&&v?parseFloat(`${p[1]}.${p[2]}`):B||null}(),Ge=/Firefox/i.test(Ri),Xe=/Edge/i.test(Ri),se=!Xe&&/Chrome/i.test(Ri),ve=/MSIE/.test(Ri)||Ri.indexOf("Trident")>-1&&Ri.indexOf("rv:11.0")>-1,pt=function(){const p=/MSIE\s(\d+)\.\d/.exec(Ri);let B=p&&parseFloat(p[1]);return!B&&/Trident\/7.0/i.test(Ri)&&/rv:11.0/.test(Ri)&&(B=11),B}(),mo=/Safari/i.test(Ri)&&!se&&!$t&&!Xe,No=/Windows/i.test(Ri),no=/MAC OS X/i.test(Ri),Go=zt&&typeof Worker<"u"&&!ve,An=$t||ot,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:p}=window.navigator;return!(!ot||p||mo)}();function ds(){let p="unknown";if(no&&(p="mac"),No&&(p="windows"),ot&&(p="ios"),$t&&(p="android"),Gi)try{const{platform:B}=Ao.getSystemInfoSync();B!==void 0&&(p=B)}catch(B){console.error(B)}return p}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function So(p,B){var v={};for(var G in p)Object.prototype.hasOwnProperty.call(p,G)&&B.indexOf(G)<0&&(v[G]=p[G]);if(p!=null&&typeof Object.getOwnPropertySymbols=="function"){var O=0;for(G=Object.getOwnPropertySymbols(p);O{Ao.request({url:v,data:G,method:B,timeout:O,header:{"content-type":Zr},success:rA=>z(rA.data),fail:()=>X(new Error(`{"message":"Network error","code":${qn}}`))})}):an?void 0:new Promise((z,X)=>{const rA=new XMLHttpRequest,DA=setTimeout(()=>{rA.abort(),X(new Error(`{"message":"Request timeout","code":${mr}}`))},O);rA.onreadystatechange=function(){if(rA.readyState===4)if(clearTimeout(DA),rA.status===200||rA.status===304)try{z(rA.responseText?JSON.parse(rA.responseText):null)}catch{z(rA.responseText)}else X(new Error(`{"message":"Network error","code":${qn}}`))},rA.open(B,v,!0),rA.setRequestHeader("Content-type",Zr),rA.send(G||null)})})}function Rs(p){if(p==null)return!0;if(typeof p=="boolean")return!1;if(typeof p=="number")return p===0;if(typeof p=="string"||typeof p=="function"||Array.isArray(p))return p.length===0;if(p instanceof Error)return p.message==="";if(N(p)){for(const B in p)if(Object.prototype.hasOwnProperty.call(p,B))return!1;return!0}return(Object.prototype.toString.call(p)==="[object Map]"||Object.prototype.toString.call(p)==="[object Set]"||Object.prototype.toString.call(p)==="[object File]")&&p.size===0}function rr(p,B){if(p===null||typeof p!="object")return p;const v=B||new WeakMap;if(v.has(p))return v.get(p);if(p instanceof Date)return new Date(p.getTime());if(p instanceof RegExp)return new RegExp(p.source,p.flags);if(p instanceof Map){const z=new Map;return v.set(p,z),p.forEach((X,rA)=>{z.set(rr(rA,v),rr(X,v))}),z}if(p instanceof Set){const z=new Set;return v.set(p,z),p.forEach(X=>{z.add(rr(X,v))}),z}if(Array.isArray(p)){const z=[];return v.set(p,z),p.forEach(X=>{z.push(rr(X,v))}),z}const G=Object.getPrototypeOf(p),O=Object.create(G);return v.set(p,O),[...Object.getOwnPropertyNames(p),...Object.getOwnPropertySymbols(p)].forEach(z=>{if(z==="__ob__"||z==="__v_skip"||z==="__v_isRef"||z==="__v_isReadonly")return;const X=Object.getOwnPropertyDescriptor(p,z);X&&(X.get||X.set?Object.defineProperty(O,z,X):O[z]=rr(p[z],v))}),O}function en(p,B,v){const G=new WeakSet,O=(z,X)=>{if(B&&(X=B(z,X)),X===void 0)return"undefined";if(X===null)return null;if(Number.isNaN(X))return"NaN";if(X===1/0)return"Infinity";if(X===-1/0)return"-Infinity";if(typeof X=="function")return`[Function: ${X.name||"anonymous"}]`;if(typeof X=="symbol")return X.toString();if(typeof X=="bigint")return`${X.toString()}n`;if(typeof X=="object"&&X!==null){if(G.has(X))return"[Circular]";G.add(X)}return X instanceof Date?X.toISOString():X instanceof Error?{name:X.name,message:X.message}:X instanceof Map?{dataType:"Map",value:Array.from(X.entries())}:X instanceof Set?{dataType:"Set",value:Array.from(X.values())}:X};try{return JSON.stringify(p,O,v)}catch(z){return console.error("Failed to stringify:",z),""}}function wn(){let p,B;return{promise:new Promise((v,G)=>{p=v,B=G}),resolve:p,reject:B}}var jt,yg=Object.freeze({__proto__:null,ANDROID_VERSION:Zt,IE_VERSION:pt,IN_ALIPAY_MINI_APP:oi,IN_BAIDU_MINI_APP:Pt,IN_BROWSER:zt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:ks,IN_JD_MINI_APP:Ni,IN_MINI_APP:Gi,IN_NODE:an,IN_NS_NATIVE_APP:As,IN_QQ_MINI_APP:Ve,IN_RN_APP:Lo,IN_TT_MINI_APP:Dt,IN_TT_MINI_GAME:ti,IN_UNI_APP:so,IN_UNI_NATIVE_APP:Co,IN_WX_MINI_APP:ct,IN_WX_MINI_APP_DESK:wt,IN_WX_MINI_GAME:ce,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:ut,IS_ANDROID:$t,IS_CHROME:se,IS_EDGE:Xe,IS_FIREFOX:Ge,IS_IE:ve,IS_IOS:ot,IS_IPAD:Ee,IS_IPHONE:Je,IS_IPOD:Ut,IS_MAC:no,IS_SAFARI:mo,IS_WECHAT:Es,IS_WIN:No,IS_WORKER_AVAILABLE:Go,MINI_APP_NAMESPACE:Ao,USER_AGENT:Ri,base16EncodeBinaryString:lA,deepCopyWithMethods:rr,deepMerge:q,generatePromise:wn,getPlatformType:ds,getType:I,httpRequest:Yi,isArray:C,isArrayOrObject:w,isEmpty:Rs,isH5:An,isIOSWebView:rn,isNumber:p=>p!==null&&(typeof p=="number"&&!Number.isNaN(p-0)||typeof p=="object"&&p.constructor===Number),isObject:f,isPlainObject:N,isString:c,isUndefined:n,isUniIOSApp:function(){return Co&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:VA,randomInt:L,randomString:function(){const p="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let B="";for(let v=32;v>0;--v)B+=p[Math.floor(62*Math.random())];return B},safeStringify:en});class Pn{constructor(){this.listeners={}}on(B,v,G){this.listeners[B]||(this.listeners[B]=[]),this.listeners[B].push({fn:v,context:G})}off(B,v,G){var O;v&&(this.listeners[B]=(O=this.listeners[B])===null||O===void 0?void 0:O.filter(z=>{const X=z.fn===v,rA=!G||z.context===G;return!(X&&rA)}))}emit(B,...v){const G=this.listeners[B];G&&G.forEach(O=>{const{fn:z,context:X}=O;try{z.apply(X,v)}catch(rA){console.warn(`Error in event handler for ${B} error: ${en(rA)}`)}})}once(B,v,G){const O=(...z)=>{v.apply(G,z),this.off(B,O)};this.on(B,O)}}(function(p){p.BUSINESS_COMMAND="business_command",p.C2C_REALTIME_MESSAGE="c2c_realtime_message",p.C2C_MESSAGE_MODIFIED="c2c_message_modified",p.C2C_REVOKED_MESSAGE="c2c_message_revoked",p.GROUP_REALTIME_MESSAGE="group_realtime_message",p.GROUP_MESSAGE_MODIFIED="group_message_modified",p.GROUP_MESSAGE_REVOKED="group_message_revoked",p.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",p.MESSAGE_REACTION_UPDATED="message_reaction_updated",p.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",p.GROUP_AT_TIPS="group_at_tips",p.USER_STATUS_UPDATE="user_status_update",p.FRIEND_LIST_MODIFIED="friend_list_modified",p.PROFILE_MODIFIED="profile_modified",p.CONV_MODIFIED="conversation_modified",p.GROUP_TIPS_NOTIFICATION="group_tips_notification",p.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",p.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",p.GROUP_SYSTEM_NOTIFICATION="group_system_notification",p.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",p.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",p.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",p.FOLLOW_LIST_UPDATED="follow_list_updated",p.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",p.ALL_MESSAGE_READ="all_message_read",p.CONVERSATION_MARK_UPDATED="conversation_mark_updated",p.CONVERSATION_GROUP_ADD="conversation_group_add",p.CONVERSATION_GROUP_DELETED="conversation_group_deleted",p.CONVERSATION_GROUP_UPDATED="conversation_group_updated",p.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",p.TOPIC_AT_TIPS="topic_at_tips",p.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",p.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",p.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",p.TOPIC_LATEST_MESSAGE="topic_latest_message",p.GROUP_MESSAGE_PINNED="group_message_pinned"})(jt||(jt={}));const bn=[16,17];function Js(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{var O;G.GroupInfo.MillionGroupFlag===2?v.push(jt.TOPIC_TIPS_NOTIFICATION):bn.includes((O=G?.MsgBody)===null||O===void 0?void 0:O.OpType)?v.push(jt.GROUP_MESSAGE_PINNED):v.push(jt.GROUP_TIPS_NOTIFICATION)}),v}const fr=[{conditions:[{type:"event",value:100}],subType:jt.BUSINESS_COMMAND},{conditions:[{type:"event",value:24}],subType:jt.ALL_RECEIVE_MESSAGE_OPTION},{conditions:[{type:"event",value:26}],subType:jt.TOPIC_LATEST_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgArray"}],subType:jt.C2C_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"C2cMsgModNotifys"}],subType:jt.C2C_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"ProfileDataMod"}],subType:jt.PROFILE_MODIFIED},{conditions:[{type:"hasKey",value:"UserStatusList"}],subType:jt.USER_STATUS_UPDATE},{conditions:[{type:"hasKey",value:"FriendListMod"}],subType:jt.FRIEND_LIST_MODIFIED},{conditions:[{type:"hasKey",value:"GroupMsgArray"}],subType:jt.GROUP_REALTIME_MESSAGE},{conditions:[{type:"hasKey",value:"GroupMsgModNotifys"}],subType:jt.GROUP_MESSAGE_MODIFIED},{conditions:[{type:"hasKey",value:"C2cNotifyMsgArray"}],subTypeParser:function(p){var B;const v=[];return(B=p?.C2cNotifyMsgArray)===null||B===void 0||B.forEach(G=>{G.WithdrawC2cMsgNotify&&v.push(jt.C2C_REVOKED_MESSAGE),G.C2cReadedReceipt&&v.push(jt.C2C_MESSAGE_PEER_READ),G.ReadC2cMsgNotify&&v.push(jt.C2C_MESSAGE_READ_SYNC),G.MuteNotificationsSync&&v.push(jt.C2C_REMIND_TYPE_SYNC)}),v}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{Array.isArray(G.MsgBody.GroupWithdrawInfoArray)?v.push(jt.GROUP_MESSAGE_REVOKED):Array.isArray(G.MsgBody.GroupMsgReceiptList)?v.push(jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(G.MsgBody.GroupReadInfoArray)?G.MsgBody.GroupReadInfoArray[0].TopicId?v.push(jt.TOPIC_MESSAGE_READ_SYNC):v.push(jt.GROUP_MESSAGE_READ_SYNC):G.GroupInfo.MillionGroupFlag===2?v.push(jt.TOPIC_SYSTEM_NOTIFICATION):v.push(jt.GROUP_SYSTEM_NOTIFICATION)}),v}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:6}],subTypeParser:Js},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(p){var B;const v=[];return(B=p?.GroupTips)===null||B===void 0||B.forEach(G=>{const{GroupAtTips:{TopicId:O}}=G;O?v.push(jt.TOPIC_AT_TIPS):v.push(jt.GROUP_AT_TIPS)}),v}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(p){var B;const v=[];return(B=p?.RecentContactMod)===null||B===void 0||B.forEach(G=>{switch(G.PushType){case We.CONV_MARK_UPDATED:v.push(jt.CONVERSATION_MARK_UPDATED);break;case We.CONV_GROUP_ADDED:v.push(jt.CONVERSATION_GROUP_ADD);break;case We.CONV_GROUP_DELETED:v.push(jt.CONVERSATION_GROUP_DELETED);break;case We.CONV_GROUP_UPDATED:v.push(jt.CONVERSATION_GROUP_UPDATED);break;default:v.push(jt.CONV_MODIFIED)}}),v}},{conditions:[{type:"hasKey",value:"MsgReactionNotifyList"}],subType:jt.MESSAGE_REACTION_UPDATED},{conditions:[{type:"hasKey",value:"MsgReactionNotify"}],subType:jt.MESSAGE_REACTION_UPDATED_SYNC},{conditions:[{type:"hasKey",value:"C2cMsgInfo"}],subType:jt.C2C_MESSAGE_READ_RECEIPT},{conditions:[{type:"hasKey",value:"FollowChangeList"}],subType:jt.FOLLOW_LIST_UPDATED},{conditions:[{type:"hasKey",value:"MsgExtensionNotify"}],subType:jt.MESSAGE_EXTENSIONS_UPDATED},{conditions:[{type:"hasKey",value:"C2CReadAllMsg"}],subType:jt.ALL_MESSAGE_READ}];var xn;function yr(p){var B;const v=Array.isArray((B=p?.body)===null||B===void 0?void 0:B.EventArray)?p.body.EventArray:[],G=[];return v.forEach(O=>{O.Flag=p.body.Flag;const z=fr.find(rA=>rA.conditions.every(DA=>{switch(DA.type){case"event":return O.Event===DA.value;case"hasKey":return Object.prototype.hasOwnProperty.call(O,DA.value);default:return!1}}));if(!z)return null;let X=[];typeof z.subTypeParser=="function"?X=z.subTypeParser(O):z.subType&&(X=z.subType),Array.isArray(X)?X.forEach(rA=>{G.push({type:`${xn.SERVER_PUSH_MESSAGE}:${rA}`,data:O})}):G.push({type:`${xn.SERVER_PUSH_MESSAGE}:${X}`,data:O})}),G}(function(p){p.SERVER_PUSH_MESSAGE="im_open_push.msg_push",p.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",p.ERROR="error"})(xn||(xn={}));const fo={[xn.SERVER_PUSH_MESSAGE]:yr,[xn.SERVER_PUSH_MESSAGE_MULTIPLE]:yr,[xn.ERROR]:function(p){const{errorCode:B}=p;return[{type:`error:${B}`,data:p}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new Pn,this._innerEventEmitter=new Pn,this.InnerEventSubType=jt}subscribeInnerEvent(p,B,v,G,O){var z;let X,rA,DA,GA;["string","number"].includes(typeof B)?(DA=`${p}:${B}`,GA=v,rA=G,X=O):(DA=p,GA=B,rA=v,X=typeof G=="function"?G:void 0),X?this._subscribeWithFilter(DA,GA,rA,X):(z=this._innerEventEmitter)===null||z===void 0||z.on(DA,GA,rA)}emitInnerEvent(p,B){var v,G;if((v=this._innerEventEmitter)===null||v===void 0||v.emit(p,B),Object.keys(fo).includes(p)){const O=(G=fo[p])===null||G===void 0?void 0:G.call(fo,B);O?.forEach(z=>{var X;z&&((X=this._innerEventEmitter)===null||X===void 0||X.emit(z.type,z.data))})}}subscribeOuterEvent(p,B,v){var G;(G=this._outerEventEmitter)===null||G===void 0||G.on(p,B,v)}unSubscribeOuterEvent(p,B,v){var G;(G=this._outerEventEmitter)===null||G===void 0||G.off(p,B,v)}unSubscribeInnerEvent(p,B,v,G){if(["string","number"].includes(typeof B)){const O=v,z=`${p}:${B}`;this._unsubscribeEvent(z,O,G)}else{const O=B;this._unsubscribeEvent(p,O,v)}}emitOuterEvent(p,B){var v;(v=this._outerEventEmitter)===null||v===void 0||v.emit(p,B)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(p,B,v,G){var O;const z=X=>{G.call(v,X)&&B.call(v,X)};this._filteredCallbackMap.has(p)||this._filteredCallbackMap.set(p,[]),this._filteredCallbackMap.get(p).push({originalCallback:B,filteredCallback:z,filter:G,context:v}),(O=this._innerEventEmitter)===null||O===void 0||O.on(p,z,v)}_unsubscribeEvent(p,B,v){var G,O;const z=this._filteredCallbackMap.get(p);if(z){const X=z.findIndex(rA=>rA.originalCallback===B&&rA.context===v);if(X!==-1){const{filteredCallback:rA}=z[X];return(G=this._innerEventEmitter)===null||G===void 0||G.off(p,rA,v),z.splice(X,1),void(z.length===0&&this._filteredCallbackMap.delete(p))}}(O=this._innerEventEmitter)===null||O===void 0||O.off(p,B,v)}};class Ml{constructor(){this._socket=null}connectSocket(B){return this._socket=new WebSocket(B),this._socket}send(B){var v,G;try{(v=this._socket)===null||v===void 0||v.send(B)}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:v,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=v,this._socket.onmessage=G,this._socket.onclose=O,this._socket.onerror=z,this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onopen=null,this._socket.onmessage=null,this._socket.onclose=null,this._socket.onerror=null)}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}class cn{constructor(B){this._onError=B.onError}connectSocket(B){const v=this;return this._socket=Ao.connectSocket({url:B,header:{"content-type":"application/json"},complete:()=>{},fail:G=>v._onError(G)}),this._socket}send(B){var v;(v=this._socket)===null||v===void 0||v.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:v,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(v),this._socket.onMessage(G),this._socket.onError(z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}const Dr="CONNECT",Us="SEND",Jc="DISCONNECT",fs="OPEN",as="MESSAGE",wu="CLOSE",Wa="ERROR",hs="SEND_FAIL";class sg{constructor(){this._worker=null,this._blobUrl=null}connectSocket(B){const v=new Blob([` let _socket = null; self.onmessage = (event) => { @@ -211,57 +211,57 @@ _socket = null; } } -`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(v)),this._worker.postMessage({type:fr,url:B})}send(B){var v,N;try{(v=this._worker)===null||v===void 0||v.postMessage({type:Ls,data:B})}catch(O){(N=this._onSendFail)===null||N===void 0||N.call(this,O)}}bindSocketHandlers(B){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=B;if(this._worker){const rA={[ms]:v,[as]:N,[Ru]:O,[Wa]:z,[Cs]:X};this._onSendFail=X,this._worker.onmessage=DA=>{var GA;const{type:VA}=DA?.data||{};typeof rA[VA]=="function"&&((GA=rA[VA])===null||GA===void 0||GA.call(rA,DA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class HI{}var As,$i=new class{constructor(){this._store=new Map}get(p){return this._store.get(p)}getStorage(p){return ki?gt?my.getStorageSync({key:p}).data:oo.getStorageSync(p):this._canUseLocalStorage()?localStorage.getItem(p):{}}set(p,B){const v=this._store.get(p)||{};B instanceof Map?this._store.set(p,B):this._store.set(p,Object.assign(Object.assign({},v),B))}setStorage(p,B){ki?gt?my.setStorageSync({key:p,data:JSON.stringify(B)}):oo.setStorageSync(p,JSON.stringify(B)):this._canUseLocalStorage()&&localStorage.setItem(p,JSON.stringify(B))}clear(p){typeof p=="string"?this._store.set(p,{}):this._store.clear()}clearLocalStorage(p){this._canUseLocalStorage()&&(typeof p=="string"?localStorage.setItem(p,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(B){return this._socket=oo.connectSocket({url:B,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(B){var v;(v=this._socket)===null||v===void 0||v.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(v),this._socket.onMessage(rA=>N(rA?.data)),this._socket.onError(()=>z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(p){p[p.CONNECTED=0]="CONNECTED",p[p.CONNECTING=1]="CONNECTING",p[p.DISCONNECTED=2]="DISCONNECTED"})(As||(As={}));class ng{constructor(B){this._url="",this._readyState=As.DISCONNECTED,this._url=B,this._id=U(),this._emitter=new On,gt?this._socket=new pc:Et||To||yt||qe||Fi||Oe?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new HI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Sl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this._readyState=As.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(B){this._readyState!==As.CONNECTED?this.reconnect():this._socket.send(B)}reconnect(){[As.CONNECTED,As.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(B,v,N){this._emitter.on(B,v,N)}off(B,v,N){this._emitter.off(B,v,N)}isConnected(){return this._readyState===As.CONNECTED}disconnect(){this._readyState=As.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(B){this._readyState===As.CONNECTING&&(this._readyState=As.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:B}))}_onMessage(B){this._emitter.emit("message",B)}_onClose(B){this._readyState=As.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:B})}_onError(B){this._readyState=As.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:B})}_onSendFail(B){this._readyState=As.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:B})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const B=$i.get("cloudConfig")||{};return(r(B.isWorkerEnabled)||B.isWorkerEnabled==="1")&&Go}}const Dg={[ut.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ut.KOREA]:[[3e7,4e7],[173e7,174e7]],[ut.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ut.IND]:[[5e7,6e7],[175e7,176e7]],[ut.JPN]:[[6e7,7e7],[176e7,177e7]],[ut.USA]:[[7e7,8e7],[177e7,178e7]],[ut.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ut.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(p){var B;if(!((B=$i.get("instance"))===null||B===void 0)&&B.oversea)return ut.OVERSEA;for(const v of Object.keys(Dg))for(const[N,O]of Dg[v])if(p>=N&&p`${ee}=${VA[ee]}`).join("&"));var VA;return v?`${p}/binfo?${GA}&compress=gzip`:`${p}/info?${GA}`}function Hs(p){const B=$i.get("instance"),{sdkAppId:v,testEnv:N,proxyServer:O}=B,z=ua(v);if(N)return Hn(ft.TEST[z].DEFAULT,{isBinary:p});if(!Rs(O))return Hn(O,{isBinary:p});const X=ft.PRODUCTION[z],rA=Zt&&X.ANYCAST,DA=Zt,GA=!!X.BACKUP_CN;return Hn({[bo.INITIAL]:()=>(_o=bo.DEFAULT,X.DEFAULT),[bo.DEFAULT]:()=>(_o=bo.IPV6,X.IPV6),[bo.IPV6]:()=>(_o=bo.BACKUP,X.BACKUP),[bo.BACKUP]:()=>DA?(_o=bo.BACKUP_WEB_ONLY,function(VA){const ee=Math.floor(10001*Math.random())+1e4;return VA.replace("*",String(ee))}(X.BACKUP_WEB_ONLY)):GA?(_o=bo.BACKUP_CN,X.BACKUP_CN):rA?(_o=bo.ANYCAST,X.ANYCAST):X.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>GA?(_o=bo.BACKUP_CN,X.BACKUP_CN):rA?(_o=bo.ANYCAST,X.ANYCAST):X.DEFAULT,[bo.BACKUP_CN]:()=>(_o=rA?bo.ANYCAST:bo.DEFAULT,X[_o]),[bo.ANYCAST]:()=>(_o=bo.DEFAULT,X.ANYCAST="",X.DEFAULT)}[_o](),{isBinary:p})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(p,B){const v=Date.now(),N=v-p;this._timeOffsetWithServer=B+N-v}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(p){const{id:B}=p;this.removeTask(B),this._tasks.push(p),this._taskMap.set(B,p),this._sort(),this._scheduleNextTask()}_createTask(p){const{id:B,callback:v,context:N,isOnce:O=!1,intervalMs:z=mc}=p,X=Math.max(z,mc);return{id:B,nextExecuteTime:Date.now()+X,intervalMs:z,callback:v,context:N,isOnce:O}}addTask(p){const B=this._createTask(p);this._addTaskToScheduler(B)}addOnceTask(p){const B=this._createTask(Object.assign(Object.assign({},p),{isOnce:!0}));this._addTaskToScheduler(B)}removeTask(p){const B=this._tasks.findIndex(v=>v.id===p);B>-1&&(this._tasks.splice(B,1),this._taskMap.delete(p),this._scheduleNextTask())}updateTaskInterval(p,B){const v=this._taskMap.get(p);v&&(v.intervalMs=B,v.nextExecuteTime=Date.now()+B,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((p,B)=>p.nextExecuteTime-B.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const p=this._tasks[0];if(p){const B=Math.max(0,p.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),B)}}_execute(){const p=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=p;){const B=this._tasks[0];try{B.context?B.callback.call(B.context):B.callback(),B.isOnce?this.removeTask(B.id):(B.nextExecuteTime=p+B.intervalMs,this._sort())}catch(v){console.warn(`Task ${B.id} execution failed:`,v),B.isOnce&&this.removeTask(B.id)}}this._scheduleNextTask()}};function Ga(p){const B=[];for(let v=0;v=55296&&N<=56319){const O=p.charCodeAt(++v)-56320+(N-55296<<10)+65536;B.push(240|O>>18,128|O>>12&63,128|O>>6&63,128|63&O)}else N<=127?B.push(N):N<=2047?B.push(192|N>>6,128|63&N):B.push(224|N>>12,128|N>>6&63,128|63&N)}return new Uint8Array(B)}function In(p){const B=Array.isArray(p)?[]:Object.create(null);for(const v in p)Object.prototype.hasOwnProperty.call(p,v)&&_(v)&&p[v]!=null&&(p[v]===null||typeof p[v]!="object"?B[v]=p[v]:B[v]=In(p[v]));return B}function fs(p,B){if(mA.includes(p))return 0;const v=Ga(JSON.stringify(B));let N=4294967295;const{length:O}=v;for(let z=0;z>>=1:N=N>>>1^3988292384}return(4294967295^N)>>>0}function Ea(p){const{servcmd:B,data:v}=p,N=function(z){const X=$i.get("login")||{},rA=$i.get("instance")||{};return{servcmd:z,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",a2:X.a2Key||void 0,tinyid:X.tinyID||void 0,status_instid:X.statusInstanceId||0,sdkappid:rA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.a2Key?void 0:X.userId,usersig:X.a2Key?void 0:X.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(B),O=In(v);return N.cs=fs(B,O),{head:N,body:O}}function yn(p){const{servcmd:B,data:v}=p,N=function(z){const X=$i.get("login")||{},rA=$i.get("instance")||{};return{servcmd:z,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:rA.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,seq:Sa(),cs:0}}(B),O=In(v);return N.cs=fs(B,O),{head:N,body:O}}let ba=U();function Sa(){return ba=ba<2415919103?ba+1:U(),ba}function $(){var p;const B=$i.get("login")||{},v=$i.get("instance")||{};return{sdk_type:30,sdk_app_id:v.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(B.tinyID),user_id:B.userId||((p=$i.get("webPush"))===null||p===void 0?void 0:p.userId),platform:HA,instance_id:v.instanceId,trace_id:new Date().getTime()}}var K,vA=Object.freeze({__proto__:null,calcBodyCRC:fs,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(p){const{servcmd:B,data:v}=p,N=function(z){const X=$i.get("login")||{},rA=$i.get("instance")||{};return{servcmd:z,ver:"v4",platform:HA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:rA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.userId,usersig:X.userSig,status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,seq:Sa(),cs:0}}(B),O=In(v);return N.cs=fs(B,O),{head:N,body:O}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(p){p[p.info=4]="info",p[p.warning=5]="warning",p[p.error=6]="error"})(K||(K={}));const qA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class Ae{constructor(B){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:v,eventType:N=0,message:O="",costTime:z=0,error:X,uiPlatform:rA,moreMessage:DA="",code:GA=0,startTime:VA=0}=B||{};this.eventType=N,this.method=v,this.message=O,this.costTime=z,this.moreMessage=`${DA} startTime:${VA}`,this.code=GA,X&&this.setError(X),Rs(rA)||(this.uiPlatform=rA)}setMoreMessage(B){this.moreMessage=`${this.moreMessage} ${B}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(B=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),B&&this._ssoLogModule.uploadSSOLogData())}setError(B){var v;return B instanceof Error?this._canSendLog?(!((v=$i.get("netWorkMonitor"))===null||v===void 0)&&v.isNetworkOnline&&(B.errorCode&&(this.code=B.errorCode),B.errorMessage&&this.setMoreMessage(B.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(B){return Object.keys(B).forEach(v=>{Object.keys(qA).includes(v)&&(this[v]=B[v])}),this}setSSOLogModule(B){this._ssoLogModule=B}_convertSSOLogDataKeyToServe(){const B={};return Object.keys(this).forEach(v=>{const N=v;qA[N]&&(B[qA[N]]=this[N])}),B}_getUiPlatform(){var B;const v=(B=$i.get("instance"))===null||B===void 0?void 0:B.scene;if(typeof v=="string"){const N=Number(v);return isNaN(N)?void 0:N}}_getSDKEdition(){var B;return(B=$i.get("instance"))===null||B===void 0?void 0:B.sdkEdition}}var me;(function(p){p.RECONNECTED="reconnected",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.SOCKET_DISCONNECTED="socket_disconnected"})(me||(me={}));var Pe=me;const Fe=20,rt=6e4,Ct=[4,5,6],Rt="report-logger";var Yt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:xe,maxCount:Qe},single:{throttleTime:ue,maxCount:Ce}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:Rt,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(p){const{evt_rpt_threshold:B=Fe,evt_rpt_waiting:v=rt,evt_rpt_level:N=Ct,evt_rpt_sdkappid_bl:O="",evt_rpt_tinyid_wl:z="",evt_rpt_global_throttle_time:X=xe,evt_rpt_global_throttle_count:rA=Qe,evt_rpt_single_throttle_time:DA=ue,evt_rpt_single_throttle_count:GA=Ce}=p||{};this._sdkAppIdBlackList=O.split(",").map(VA=>Number(VA)),this._waitingTime=Number(v),this._minThreshold=B,this._reportLevel=N,this._tinyIdWhiteList=z.split(","),this._throttleConfig={global:{throttleTime:X,maxCount:rA},single:{throttleTime:DA,maxCount:GA}}}createSSOLogData(p){const B=new Ae(p);return B.setSSOLogModule(this),this._ssoLogMap.set(p.method,B),B}getSSOLogData(p){return this._ssoLogMap.get(p)||{}}pushToLogQueue(p){p&&(this._logQueue.push(p),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(p){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(p)&&(this._logLevel=p)}debug(p,B="",v){this._log(IA.DEBUG,p,B,v)}info(p,B="",v){this._log(IA.INFO,p,B,v)}warn(p,B="",v){this._log(IA.WARN,p,B,v)}error(p,B="",v){this._log(IA.ERROR,p,B,v)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return pA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const p=this._logQueue.slice();this._logQueue=[];try{const B=this._filterLogs(p);if(B.length===0)return void(this._lastReportAt=Date.now());const v={Header:$(),Event:B};Rs(v.Header.user_id)||(yield function(N){const O="imopenstat.tim_web_report_v2",z=yn({servcmd:O,data:N}),X=`${z.head.seq}${O}`;return vl.sendPacket(z,{requestId:X})}(v))}catch(B){this._requeueFailedLogs(p),this.debug("uploadSSOLogData",en(B))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(p){this._logQueue=p.concat(this._logQueue);const B=this._logQueue.length-200;B>0&&(this._logQueue.splice(0,B),this.debug("uploadSSOLogData",`log queue overflow, dropped ${B} oldest logs`))}_savePlatFormInfo(){var p,B;if(Et){const v=(B=(p=wx.getAccountInfoSync)===null||p===void 0?void 0:p.call(wx))===null||B===void 0?void 0:B.miniProgram;if(v){const{appId:N,envVersion:O}=v;$i.set("instance",{appId:N,envVersion:O})}}else Zt&&$i.set("instance",{href:window.location.href})}_filterLogs(p){const{tinyID:B}=$i.get("login")||{},{sdkAppId:v}=$i.get("instance")||{};return this._sdkAppIdBlackList.includes(v)&&!this._tinyIdWhiteList.includes(B)?[]:p.filter(N=>this._reportLevel.includes(N.level))}_checkThrottle(p){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(p)}_checkGlobalThrottle(){const p=Date.now();if(p-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=p;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(p){const B=Date.now(),v=this._singleThrottleMap.get(p);return v?B-v.startTime>=this._throttleConfig.single.throttleTime?(v.count=1,v.startTime=B,!1):v.count>=this._throttleConfig.single.maxCount||(v.count++,!1):(this._singleThrottleMap.set(p,{count:1,startTime:B}),!1)}_shouldLog(p){return p>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(p){return this._reportLevel.includes(WA[p])}_formatLog(p,B,v,N){const O=new Date,z=`${O.getHours()}:${O.getMinutes()}:${O.getSeconds()}:${O.getMilliseconds()}`,X=`<${IA[p]}>`;return Nt||ki?[`${cA} [${z}] ${X} [${B}] ${v}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",cA,"",`[${z}] ${X} [${B}] ${v} params: ${en(N)}`]}_log(p,B,v,N){if(this._shouldLog(p)){const O=this._formatLog(p,B,v,N);TA[p].apply(console,O)}if(this._shouldReport(p)){const O=this._getThrottleKey(B,v,N);this._checkThrottle(O)||this.createSSOLogData(Object.assign(Object.assign({message:v},N),{method:B})).end()}}_getThrottleKey(p,B,v){const N=`${p}${B}${en(Object.assign(Object.assign({},v),{costTime:""}))}`,O=Ga(JSON.stringify(N));let z=4294967295;const{length:X}=O;for(let rA=0;rA>>=1:z=z>>>1^3988292384}return`${(4294967295^z)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(Rt),gn.unSubscribeInnerEvent(Pe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Fe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const Ii=15e3,ct="Channel",xt="channel_schedule_task",Ji="channel_reconnect_task",Ki="connected",qs="connecting",Mi="disconnected",zo=1e3,Mg="network_status_change",sr="activity_status_change",yr="send_fail",xn="reconnect_failed",Ml="socket_error",Ks="socket_close";function aI(p){return aI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(B){return typeof B}:function(B){return B&&typeof Symbol=="function"&&B.constructor===Symbol&&B!==Symbol.prototype?"symbol":typeof B},aI(p)}function Wg(p){throw new Error('Could not dynamically require "'+p+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var fc,wu={exports:{}},Ma=(fc||(fc=1,function(p){p.exports=function B(v,N,O){function z(DA,GA){if(!N[DA]){if(!v[DA]){if(!GA&&Wg)return Wg(DA);if(X)return X(DA,!0);var VA=new Error("Cannot find module '"+DA+"'");throw VA.code="MODULE_NOT_FOUND",VA}var ee=N[DA]={exports:{}};v[DA][0].call(ee.exports,function(Ee){return z(v[DA][1][Ee]||Ee)},ee,ee.exports,B,v,N,O)}return N[DA].exports}for(var X=Wg,rA=0;rA>>6:(Ee<65536?ee[at++]=224|Ee>>>12:(ee[at++]=240|Ee>>>18,ee[at++]=128|Ee>>>12&63),ee[at++]=128|Ee>>>6&63),ee[at++]=128|63&Ee);return ee},N.buf2binstring=function(VA){return GA(VA,VA.length)},N.binstring2buf=function(VA){for(var ee=new O.Buf8(VA.length),Ee=0,We=ee.length;Ee>10&1023,Jt[We++]=56320|1023&ot)}return GA(Jt,We)},N.utf8border=function(VA,ee){var Ee;for((ee=ee||VA.length)>VA.length&&(ee=VA.length),Ee=ee-1;0<=Ee&&(192&VA[Ee])==128;)Ee--;return Ee<0||Ee===0?ee:Ee+rA[VA[Ee]]>ee?Ee:ee}},{"./common":1}],3:[function(B,v,N){v.exports=function(O,z,X,rA){for(var DA=65535&O,GA=O>>>16&65535,VA=0;X!==0;){for(X-=VA=2e3>>1:z>>>1;X[rA]=z}return X}();v.exports=function(z,X,rA,DA){var GA=O,VA=DA+rA;z^=-1;for(var ee=DA;ee>>8^GA[255&(z^X[ee])];return-1^z}},{}],6:[function(B,v,N){v.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(B,v,N){v.exports=function(O,z){var X,rA,DA,GA,VA,ee,Ee,We,ot,at,Ut,Jt,Ui,go,Xi,Ei,Po,es,pi,ji,Ws,_e,_t,FA,Xt;X=O.state,rA=O.next_in,FA=O.input,DA=rA+(O.avail_in-5),GA=O.next_out,Xt=O.output,VA=GA-(z-O.avail_out),ee=GA+(O.avail_out-257),Ee=X.dmax,We=X.wsize,ot=X.whave,at=X.wnext,Ut=X.window,Jt=X.hold,Ui=X.bits,go=X.lencode,Xi=X.distcode,Ei=(1<>>=pi=es>>>24,Ui-=pi,(pi=es>>>16&255)==0)Xt[GA++]=65535&es;else{if(!(16&pi)){if(!(64&pi)){es=go[(65535&es)+(Jt&(1<>>=pi,Ui-=pi),Ui<15&&(Jt+=FA[rA++]<>>=pi=es>>>24,Ui-=pi,!(16&(pi=es>>>16&255))){if(!(64&pi)){es=Xi[(65535&es)+(Jt&(1<>>=pi,Ui-=pi,(pi=GA-VA)>3,Jt&=(1<<(Ui-=ji<<3))-1,O.next_in=rA,O.next_out=GA,O.avail_in=rA>>24&255)+(_e>>>8&65280)+((65280&_e)<<8)+((255&_e)<<24)}function Jt(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new O.Buf16(320),this.work=new O.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Ui(_e){var _t;return _e&&_e.state?(_t=_e.state,_e.total_in=_e.total_out=_t.total=0,_e.msg="",_t.wrap&&(_e.adler=1&_t.wrap),_t.mode=We,_t.last=0,_t.havedict=0,_t.dmax=32768,_t.head=null,_t.hold=0,_t.bits=0,_t.lencode=_t.lendyn=new O.Buf32(ot),_t.distcode=_t.distdyn=new O.Buf32(at),_t.sane=1,_t.back=-1,ee):Ee}function go(_e){var _t;return _e&&_e.state?((_t=_e.state).wsize=0,_t.whave=0,_t.wnext=0,Ui(_e)):Ee}function Xi(_e,_t){var FA,Xt;return _e&&_e.state?(Xt=_e.state,_t<0?(FA=0,_t=-_t):(FA=1+(_t>>4),_t<48&&(_t&=15)),_t&&(_t<8||15<_t)?Ee:(Xt.window!==null&&Xt.wbits!==_t&&(Xt.window=null),Xt.wrap=FA,Xt.wbits=_t,go(_e))):Ee}function Ei(_e,_t){var FA,Xt;return _e?(Xt=new Jt,(_e.state=Xt).window=null,(FA=Xi(_e,_t))!==ee&&(_e.state=null),FA):Ee}var Po,es,pi=!0;function ji(_e){if(pi){var _t;for(Po=new O.Buf32(512),es=new O.Buf32(32),_t=0;_t<144;)_e.lens[_t++]=8;for(;_t<256;)_e.lens[_t++]=9;for(;_t<280;)_e.lens[_t++]=7;for(;_t<288;)_e.lens[_t++]=8;for(DA(GA,_e.lens,0,288,Po,0,_e.work,{bits:9}),_t=0;_t<32;)_e.lens[_t++]=5;DA(VA,_e.lens,0,32,es,0,_e.work,{bits:5}),pi=!1}_e.lencode=Po,_e.lenbits=9,_e.distcode=es,_e.distbits=5}function Ws(_e,_t,FA,Xt){var En,Ai=_e.state;return Ai.window===null&&(Ai.wsize=1<=Ai.wsize?(O.arraySet(Ai.window,_t,FA-Ai.wsize,Ai.wsize,0),Ai.wnext=0,Ai.whave=Ai.wsize):(Xt<(En=Ai.wsize-Ai.wnext)&&(En=Xt),O.arraySet(Ai.window,_t,FA-Xt,En,Ai.wnext),(Xt-=En)?(O.arraySet(Ai.window,_t,FA-Xt,Xt,0),Ai.wnext=Xt,Ai.whave=Ai.wsize):(Ai.wnext+=En,Ai.wnext===Ai.wsize&&(Ai.wnext=0),Ai.whave>>8&255,FA.check=X(FA.check,Ne,2,0),Qt=ht=0,FA.mode=2;break}if(FA.flags=0,FA.head&&(FA.head.done=!1),!(1&FA.wrap)||(((255&ht)<<8)+(ht>>8))%31){_e.msg="incorrect header check",FA.mode=30;break}if((15&ht)!=8){_e.msg="unknown compression method",FA.mode=30;break}if(Qt-=4,yA=8+(15&(ht>>>=4)),FA.wbits===0)FA.wbits=yA;else if(yA>FA.wbits){_e.msg="invalid window size",FA.mode=30;break}FA.dmax=1<>8&1),512&FA.flags&&(Ne[0]=255&ht,Ne[1]=ht>>>8&255,FA.check=X(FA.check,Ne,2,0)),Qt=ht=0,FA.mode=3;case 3:for(;Qt<32;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>8&255,Ne[2]=ht>>>16&255,Ne[3]=ht>>>24&255,FA.check=X(FA.check,Ne,4,0)),Qt=ht=0,FA.mode=4;case 4:for(;Qt<16;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>8),512&FA.flags&&(Ne[0]=255&ht,Ne[1]=ht>>>8&255,FA.check=X(FA.check,Ne,2,0)),Qt=ht=0,FA.mode=5;case 5:if(1024&FA.flags){for(;Qt<16;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>8&255,FA.check=X(FA.check,Ne,2,0)),Qt=ht=0}else FA.head&&(FA.head.extra=null);FA.mode=6;case 6:if(1024&FA.flags&&(vi<(Wi=FA.length)&&(Wi=vi),Wi&&(FA.head&&(yA=FA.head.extra_len-FA.length,FA.head.extra||(FA.head.extra=new Array(FA.head.extra_len)),O.arraySet(FA.head.extra,Xt,Ai,Wi,yA)),512&FA.flags&&(FA.check=X(FA.check,Xt,Wi,Ai)),vi-=Wi,Ai+=Wi,FA.length-=Wi),FA.length))break A;FA.length=0,FA.mode=7;case 7:if(2048&FA.flags){if(vi===0)break A;for(Wi=0;yA=Xt[Ai+Wi++],FA.head&&yA&&FA.length<65536&&(FA.head.name+=String.fromCharCode(yA)),yA&&Wi>9&1,FA.head.done=!0),_e.adler=FA.check=0,FA.mode=12;break;case 10:for(;Qt<32;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>=7&Qt,Qt-=7&Qt,FA.mode=27;break}for(;Qt<3;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>=1)){case 0:FA.mode=14;break;case 1:if(ji(FA),FA.mode=20,_t!==6)break;ht>>>=2,Qt-=2;break A;case 2:FA.mode=17;break;case 3:_e.msg="invalid block type",FA.mode=30}ht>>>=2,Qt-=2;break;case 14:for(ht>>>=7&Qt,Qt-=7&Qt;Qt<32;){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>16^65535)){_e.msg="invalid stored block lengths",FA.mode=30;break}if(FA.length=65535&ht,Qt=ht=0,FA.mode=15,_t===6)break A;case 15:FA.mode=16;case 16:if(Wi=FA.length){if(vi>>=5,Qt-=5,FA.ndist=1+(31&ht),ht>>>=5,Qt-=5,FA.ncode=4+(15&ht),ht>>>=4,Qt-=4,286>>=3,Qt-=3}for(;FA.have<19;)FA.lens[ge[FA.have++]]=0;if(FA.lencode=FA.lendyn,FA.lenbits=7,zA={bits:FA.lenbits},NA=DA(0,FA.lens,0,19,FA.lencode,0,FA.work,zA),FA.lenbits=zA.bits,NA){_e.msg="invalid code lengths set",FA.mode=30;break}FA.have=0,FA.mode=19;case 19:for(;FA.have>>16&255,Qa=65535&le,!((is=le>>>24)<=Qt);){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>=is,Qt-=is,FA.lens[FA.have++]=Qa;else{if(Qa===16){for(we=is+2;Qt>>=is,Qt-=is,FA.have===0){_e.msg="invalid bit length repeat",FA.mode=30;break}yA=FA.lens[FA.have-1],Wi=3+(3&ht),ht>>>=2,Qt-=2}else if(Qa===17){for(we=is+3;Qt>>=is)),ht>>>=3,Qt-=3}else{for(we=is+7;Qt>>=is)),ht>>>=7,Qt-=7}if(FA.have+Wi>FA.nlen+FA.ndist){_e.msg="invalid bit length repeat",FA.mode=30;break}for(;Wi--;)FA.lens[FA.have++]=yA}}if(FA.mode===30)break;if(FA.lens[256]===0){_e.msg="invalid code -- missing end-of-block",FA.mode=30;break}if(FA.lenbits=9,zA={bits:FA.lenbits},NA=DA(GA,FA.lens,0,FA.nlen,FA.lencode,0,FA.work,zA),FA.lenbits=zA.bits,NA){_e.msg="invalid literal/lengths set",FA.mode=30;break}if(FA.distbits=6,FA.distcode=FA.distdyn,zA={bits:FA.distbits},NA=DA(VA,FA.lens,FA.nlen,FA.ndist,FA.distcode,0,FA.work,zA),FA.distbits=zA.bits,NA){_e.msg="invalid distances set",FA.mode=30;break}if(FA.mode=20,_t===6)break A;case 20:FA.mode=21;case 21:if(6<=vi&&258<=ho){_e.next_out=us,_e.avail_out=ho,_e.next_in=Ai,_e.avail_in=vi,FA.hold=ht,FA.bits=Qt,rA(_e,ks),us=_e.next_out,En=_e.output,ho=_e.avail_out,Ai=_e.next_in,Xt=_e.input,vi=_e.avail_in,ht=FA.hold,Qt=FA.bits,FA.mode===12&&(FA.back=-1);break}for(FA.back=0;ga=(le=FA.lencode[ht&(1<>>16&255,Qa=65535&le,!((is=le>>>24)<=Qt);){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>ea)])>>>16&255,Qa=65535&le,!(ea+(is=le>>>24)<=Qt);){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>=ea,Qt-=ea,FA.back+=ea}if(ht>>>=is,Qt-=is,FA.back+=is,FA.length=Qa,ga===0){FA.mode=26;break}if(32&ga){FA.back=-1,FA.mode=12;break}if(64&ga){_e.msg="invalid literal/length code",FA.mode=30;break}FA.extra=15&ga,FA.mode=22;case 22:if(FA.extra){for(we=FA.extra;Qt>>=FA.extra,Qt-=FA.extra,FA.back+=FA.extra}FA.was=FA.length,FA.mode=23;case 23:for(;ga=(le=FA.distcode[ht&(1<>>16&255,Qa=65535&le,!((is=le>>>24)<=Qt);){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>ea)])>>>16&255,Qa=65535&le,!(ea+(is=le>>>24)<=Qt);){if(vi===0)break A;vi--,ht+=Xt[Ai++]<>>=ea,Qt-=ea,FA.back+=ea}if(ht>>>=is,Qt-=is,FA.back+=is,64&ga){_e.msg="invalid distance code",FA.mode=30;break}FA.offset=Qa,FA.extra=15&ga,FA.mode=24;case 24:if(FA.extra){for(we=FA.extra;Qt>>=FA.extra,Qt-=FA.extra,FA.back+=FA.extra}if(FA.offset>FA.dmax){_e.msg="invalid distance too far back",FA.mode=30;break}FA.mode=25;case 25:if(ho===0)break A;if(Wi=ks-ho,FA.offset>Wi){if((Wi=FA.offset-Wi)>FA.whave&&FA.sane){_e.msg="invalid distance too far back",FA.mode=30;break}Wi>FA.wnext?(Wi-=FA.wnext,Hr=FA.wsize-Wi):Hr=FA.wnext-Wi,Wi>FA.length&&(Wi=FA.length),oc=FA.window}else oc=En,Hr=us-FA.offset,Wi=FA.length;for(hoPo?(pi=Hr[oc+at[_t]],ji=Qt[ug+at[_t]]):(pi=96,ji=0),Jt=1<<_e-us,FA=Ui=1<>us)+(Ui-=Jt)]=es<<24|pi<<16|ji,Ui!==0;);for(Jt=1<<_e-1;ht&Jt;)Jt>>=1;if(Jt!==0?(ht&=Jt-1,ht+=Jt):ht=0,_t++,--ks[_e]==0){if(_e===Xt)break;_e=VA[ee+at[_t]]}if(En<_e&&(ht&Xi)!==go){for(us===0&&(us=En),Ei+=FA,vi=1<<(Ai=_e-us);Ai+us{const rA=new Uint8Array(X).slice(4);let DA;try{DA=Ma.inflate(rA,{to:"string"})}catch(GA){console.error("inflate error",GA)}return DA})(p.data):function(X){const rA=new Uint8Array(X);let DA="",GA=0;const{length:VA}=rA;for(;GA0)for(let ot=0;ot{var N;const{uplinkData:O,canResend:z,resolve:X,reject:rA,timeout:DA}=B;if(z){this._pendingRequests.set(v,{resolve:X,reject:rA,timestamp:Date.now(),uplinkData:O,timeout:DA,canResend:z});const GA=this._isBinarySupported?Ga(O).buffer:O;(N=this._socketAdapter)===null||N===void 0||N.send(GA)}else this._pendingRequests.delete(v)})}_onConnect(p){const{socketId:B,event:v={}}=p||{};this._connectionId=B,this._connectionEstablishedTime=Date.now();const N=Date.now()-this._connectionStartTime,O=`${ct}.onConnect cost:${N} ms. socketID:${B} res:${JSON.stringify(v)}`;if(this._ssoLog({method:"onConnect",message:O}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const z=`${ct}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:z}),gn.emitInnerEvent(Pe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Ki,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(p){const B=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:p}});this.sendPacket(B)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var p;return((p=this._socketAdapter)===null||p===void 0?void 0:p.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var p;const B=Ea({servcmd:"heartbeat.alive",data:{}});try{const v=`${B.head.seq}${B.head.servcmd}`;yield this.sendPacket(B,{requestId:v,timeout:3e3})}catch(v){const N=(p=$i.get("netWorkMonitor"))===null||p===void 0?void 0:p.isNetworkOnline,O=`${ct}.sendHeartbeat failed. isNetWorkOnline:${N} error: ${en(v)}`;this._ssoLog({method:"sendHeartbeatError",message:O}),this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return pA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=To?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(p){const B=`${ct}.networkStatusChange ${JSON.stringify(p)}`;this._ssoLog({method:"networkStatusChange",message:B});const{isNetworkOnline:v,networkType:N}=p;v&&N!=="none"?this._handleConnectStateChange({state:Ki,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const p=$i.get("instance")||{};return p.proxyServer&&!p.fileDownloadProxy}_handleConnectStateChange(p){const{state:B,shouldAttemptReconnect:v,shouldEmitEvent:N,reason:O}=p,z=`${ct}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${v} shouldEmitEvent: ${N} reason: ${O}`;this._currentConnectState!==B&&(this._ssoLog({method:"handleConnectStateChange",message:z}),N&&(Yt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${B}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:B}}),this._currentConnectState=B,B===Mi&&gn.emitInnerEvent(Pe.SOCKET_DISCONNECTED)),v&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(p){var B,v;const N=(v=(B=this._socketAdapter)===null||B===void 0?void 0:B._ws)===null||v===void 0?void 0:v.readyState,O=`${ct}.activityStatusChange ${JSON.stringify(p)} readyState: ${N}`;Yt.debug("activityStatusChange",O),N===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:sr})}_resetReconnectDelay(){var p;Yt.debug(`${ct}._resetReconnectDelay`),fn.removeTask(Ji);const B=(p=$i.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?zo:1e3}_scheduleReconnectWithBackoff(){var p;const B=(p=$i.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const v=new Date().toTimeString().slice(0,8),N=`${ct}.scheduleReconnectWithBackoff timeStr: ${v} intendedDelay: ${this._intendedDelay}`;Yt.debug(N),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(p){const{method:B,message:v}=p;Yt.info(B,v)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(p){pA(this,void 0,void 0,function*(){const B=p.split("/")[2];if(!B.startsWith("ws"))return;const v=`https://${B}/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:v,data:{}})}catch(N){Yt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${N.message}`)}})}(this._url),function(p){pA(this,void 0,void 0,function*(){const B=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:B,data:{}})}catch(v){Yt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${v.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[p,B]of this._pendingRequests.entries()){const{reject:v,timestamp:N,timeout:O}=B;Date.now()-N>=O&&(this._pendingRequests.delete(p),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),v({errorCode:Qr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:p}}))}}_updateIsBinarySupported(){var p;if(!((p=$i.get("instance"))===null||p===void 0)&&p.devMode)return void(this._isBinarySupported=!1);const B=Es();if((gt||Et&&B==="windows"||Vs)&&(this._isBinarySupported=!1),To){const{uniRuntimeVersion:v=""}=oo.getSystemInfoSync();(function(N){const O=N.split(".").map(Number),[z=0,X=0,rA=0]=O;return z>2||!(z<2)&&(X>2||!(X<2)&&rA>=6)})(v)||(this._isBinarySupported=!1)}}_isCompressedData(p){const B=new Uint8Array(p);return B[0]===67&&B[1]===79&&B[2]===77&&B[3]===80}};const ye={init:function(p){$i.set("instance",p),vl.init()},destroy:function(){vl.dispose(),$i.clear(),fn.dispose()},notificationCenter:gn,channel:vl,store:$i,ssoLog:Yt,utils:yg,common:vA,constants:Mt},fe=p=>typeof p=="function";function vg(p,B,v){const N=v||[];if(!p||!B)return!1;const O=Object.keys(p).filter(X=>!N.includes(X)),z=Object.keys(B).filter(X=>!N.includes(X));return O.length===z.length&&O.every(X=>!!B.hasOwnProperty(X)&&(typeof p[X]=="object"&&p[X]!==null?vg(p[X],B[X],v):p[X]===B[X]))}var rg;(function(p){p.SDK_READY="sdkStateReady",p.SDK_NOT_READY="sdkStateNotReady",p.SDK_DESTROY="sdkDestroy",p.MESSAGE_RECEIVED="onMessageReceived",p.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",p.MESSAGE_MODIFIED="onMessageModified",p.MESSAGE_REVOKED="onMessageRevoked",p.MESSAGE_READ_BY_PEER="onMessageReadByPeer",p.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",p.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",p.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",p.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",p.CONVERSATION_LIST_UPDATED="onConversationListUpdated",p.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",p.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",p.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",p.GROUP_LIST_UPDATED="onGroupListUpdated",p.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",p.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",p.TOPIC_CREATED="onTopicCreated",p.TOPIC_DELETED="onTopicDeleted",p.TOPIC_UPDATED="onTopicUpdated",p.PROFILE_UPDATED="onProfileUpdated",p.USER_STATUS_UPDATED="onUserStatusUpdated",p.BLACKLIST_UPDATED="blacklistUpdated",p.FRIEND_LIST_UPDATED="onFriendListUpdated",p.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",p.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",p.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",p.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",p.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",p.KICKED_OUT="kickedOut",p.ERROR="error",p.NET_STATE_CHANGE="netStateChange",p.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",p.SERVER_CONFIG_UPDATED="onServerConfigUpdated",p.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",p.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",p.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",p.RICH_STATUS_CHANGED="onRichStatusChanged"})(rg||(rg={}));var Rg,Dn=rg;(function(p){p.LOGOUT="logout",p.DESTROY="destroy",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.PROFILE_UPDATE="profile_updated",p.ERROR="error",p.RECONNECTED="reconnected",p.FORCE_OFFLINE="im_open_status.stat_forceoffline",p.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",p.OVERLOAD_PUSH="OverLoadPush.notify2",p.NEW_MESSAGE="new_message",p.MESSAGE_PUSH="im_open_push.msg_push",p.MESSAGE_DELETED="message_deleted",p.MESSAGE_REVOKED="message_revoked",p.MESSAGE_MODIFIED="message_modified",p.SOCKET_DISCONNECTED="socket_disconnected",p.CONVERSATION_UPDATED="conversation_updated",p.TOPIC_MESSAGE_DELETED="topic_message_deleted",p.TOPIC_MESSAGE_REVOKED="topic_message_revoked",p.TOPIC_MESSAGE_MODIFIED="topic_message_modified",p.TOPIC_NEW_MESSAGE="topic_new_message",p.QUALITY_STAT="quality_stat",p.SYNC_CONVERSATION_LIST="sync_conversation_list",p.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Rg||(Rg={}));var Dr,ui=Rg;(function(p){p.NEW_INVITATION_RECEIVED="newInvitationReceived",p.INVITEE_ACCEPTED="ts_invitee_accepted",p.INVITEE_REJECTED="ts_invitee_rejected",p.INVITATION_CANCELLED="ts_invitation_cancelled",p.INVITATION_TIMEOUT="ts_invitation_timeout",p.INVITATION_MODIFIED="ts_invitation_modified"})(Dr||(Dr={}));var no=Dr;const qc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),zg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var wg;(function(p){p.UNSENT="unSend",p.SUCCESS="success",p.FAIL="fail"})(wg||(wg={}));const Yr={modify:ui.MESSAGE_MODIFIED,delete:ui.MESSAGE_DELETED,revoke:ui.MESSAGE_REVOKED};var yc;(function(p){p[p.FORWARD=0]="FORWARD",p[p.BACKWARD=1]="BACKWARD"})(yc||(yc={}));const Kc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:wg,Direction:yc}),ag={[Yr.modify]:ui.TOPIC_MESSAGE_MODIFIED,[Yr.delete]:ui.TOPIC_MESSAGE_DELETED,[Yr.revoke]:ui.TOPIC_MESSAGE_REVOKED},_u={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},SE=Object.assign({},_u),_g={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ka=Object.assign(Object.assign(Object.assign(Object.assign({},_g),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Dc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),ME={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},La={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},sa={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},Tg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ME),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:La,GROUP_TIPS_OPERATION_TYPE:sa}),gI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},hs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},qc),Kc),SE),ka),Dc),Tg),gI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Lo={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},da={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},nr={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Vt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Kt={[nr.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Vt.USER_STATUS_UPDATE},{stepId:Vt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Vt.UNREAD_MESSAGE_SYNC,dependency:Vt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Vt.CONVERSATION_RECOVER},{stepId:Vt.HISTORY_MESSAGE_RECOVER,dependency:Vt.CONVERSATION_RECOVER},{stepId:Vt.BLACKLIST_RECOVER},{stepId:Vt.FRIEND_RECOVER},{stepId:Vt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Vt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Vt.HISTORY_MESSAGE_RECOVER},{stepId:Vt.GROUP_TIPS_RECOVER,dependency:Vt.HISTORY_MESSAGE_RECOVER},{stepId:Vt.TOPIC_REQUEST_INFO_RESET},{stepId:Vt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Vt.UNREAD_MESSAGE_SYNC},{stepId:Vt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Vt.UNREAD_MESSAGE_SYNC},{stepId:Vt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Vt.UNREAD_MESSAGE_SYNC,Vt.CONVERSATION_RECOVER]},{stepId:Vt.EMIT_C2C_MESSAGE_EVENT,dependency:[Vt.UNREAD_MESSAGE_SYNC,Vt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Vt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Vt.CONVERSATION_RECOVER},{stepId:Vt.STREAM_MESSAGE_RECOVER}],[nr.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Vt.COMMERCIAL_CONFIG_UPDATE},{stepId:Vt.CLOUD_CONFIG_SYNC},{stepId:Vt.USER_PROFILE_SYNC},{stepId:Vt.UNREAD_MESSAGE_SYNC},{stepId:Vt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Vt.GROUP_LIST_SYNC},{stepId:Vt.CONVERSATION_LIST_SYNC},{stepId:Vt.SIGNALING_MESSAGE_RECOVER,dependency:Vt.UNREAD_MESSAGE_SYNC},{stepId:Vt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Vt.UNREAD_MESSAGE_SYNC]},{stepId:Vt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Vt.UNREAD_MESSAGE_SYNC,Vt.CONVERSATION_LIST_SYNC]},{stepId:Vt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Vt.GROUP_LIST_SYNC,Vt.CONVERSATION_LIST_SYNC]},{stepId:Vt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Vt.CONVERSATION_GROUP_UPDATE,dependency:[Vt.CONVERSATION_LIST_SYNC,Vt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Vt.QUALITY_REPORT}],[nr.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Vt.HANDLE_C2C_NEW_MESSAGE},{stepId:Vt.UNREAD_MESSAGE_SYNC},{stepId:Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Vt.HANDLE_C2C_NEW_MESSAGE},{stepId:Vt.EMIT_C2C_MESSAGE_EVENT,dependency:[Vt.HANDLE_C2C_NEW_MESSAGE,Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Vt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Vt.UNREAD_MESSAGE_SYNC]}],[nr.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Vt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Vt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Vt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Vt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Vt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Vt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Vt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Vt.HANDLE_GROUP_NEW_MESSAGE,Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[nr.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Vt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Vt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Vt.EMIT_GROUP_TIPS_EVENT,dependency:[Vt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Vt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},Ng={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},cI={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},rr=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var qI=Object.freeze({__proto__:null,ERROR_CODE:Lo,InnerEvent:ui,NEED_LOG_API:rr,OuterConstant:hs,OuterEvent:Dn,PUSH:gI,QUALITY_METRICS:Ng,SDK_EDITION:da,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:cI,SignalingEvent:no,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Kt,WORKFLOW_NAME:nr,WORKFLOW_STEP:Vt}),za,na,un;(function(p){p[p.USER_INITIATED=0]="USER_INITIATED",p[p.KICKED_OUT=1]="KICKED_OUT"})(za||(za={})),function(p){p[p.multipleAccount=1]="multipleAccount",p[p.multipleDevice=2]="multipleDevice",p[p.restApi=3]="restApi"}(na||(na={})),function(p){p[p.multipleDevice=3002]="multipleDevice",p[p.multipleAccount=3003]="multipleAccount",p[p.usersigExpired=70001]="usersigExpired",p[p.restApi=20002]="restApi"}(un||(un={}));const Sn={[na.multipleAccount]:"multipleAccount",[na.multipleDevice]:"multipleDevice",[na.restApi]:"REST_API_Kick",[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[un.usersigExpired]:"userSigExpired"},Tu="login_online_presence_task",{ERROR:Gg,DESTROY:Ua,FORCE_OFFLINE:jc}=ui,{KICKED_OUT_MULT_ACCOUNT:KI,KICKED_OUT_MULT_DEVICE:vE,KICKED_OUT_REST_API:lI,ACCOUNT_A2KEY_EXPIRED:Nu,MSG_A2KEY_EXPIRED:Rl}=Lo;class Sc{init(){const{notificationCenter:B}=ye;B.subscribeInnerEvent(jc,this._handleForceOfflineFromServerPush,this),B.subscribeInnerEvent(Gg,Rl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Gg,Nu,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Gg,KI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Gg,vE,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Gg,lI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ua,this._dispose,this)}_handleForceOfflineFromServerPush(B){var v;if(((v=ye.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)===!0){const{EventArray:N=[]}=B?.body||{};this._extractKickedOutMessages(N).forEach(O=>{const{KickoutMsgNotify:{KickType:z,NewInstInfo:X,Instid:rA}}=O;this._isCurrentInstanceKickedOut(rA)&&this._processKickedOutReasonInfo({kickedOutReasonCode:z,newInstanceInfo:X})})}}_extractKickedOutMessages(B){return B.reduce((v,N)=>[...v,...N.C2cNotifyMsgArray||[]],[]).filter(v=>{var N;return this._isKickedOut((N=v?.KickoutMsgNotify)===null||N===void 0?void 0:N.KickType)})}_handleForceOfflineFromResponse(B){const{errorCode:v}=B;this._processKickedOutReasonInfo({kickedOutReasonCode:v})}_processKickedOutReasonInfo(B){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:v}=B,{ssoLog:N,utils:{safeStringify:O}}=ye;try{this._logKickedOutEvent(B),this._shouldLogoutAfterKickedOut(v)?yield ye.login.loginAction.logout(za.KICKED_OUT):ye.login.loginAction.handleLogoutCompleted()}catch(z){N.debug("_processKickedOutReasonInfo",` fail ${O(z)}`)}finally{ye.notificationCenter.emitOuterEvent(Dn.KICKED_OUT,{data:{type:Sn[v]},name:Dn.KICKED_OUT})}})}_logKickedOutEvent(B){const{kickedOutReasonCode:v,newInstanceInfo:N={}}=B,O=`type:${Sn[v]} newInstanceInfo: ${JSON.stringify(N)}`;ye.ssoLog.warn("kickedOut",O)}_isKickedOut(B){return[na.multipleAccount,na.multipleDevice,na.restApi].includes(B)}_isChatLoginEvent(B){const{requestHead:v}=B||{};return v?.idtype!==1}_shouldLogoutAfterKickedOut(B){return![un.usersigExpired,na.restApi].includes(B)}_isCurrentInstanceKickedOut(B){const{isLoggedIn:v,statusInstanceId:N}=ye.store.get("login")||{};return v===!0&&B===N}_dispose(){const{notificationCenter:B}=ye;B.unSubscribeInnerEvent(jc,this._handleForceOfflineFromServerPush,this),B.unSubscribeInnerEvent(Gg,Nu,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,Rl,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,KI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,vE,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,lI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ua,this._dispose,this)}}function Gu(p){return pA(this,void 0,void 0,function*(){const B="im_open_status.wslogin",v=ye.common.generateProtocolData({servcmd:B,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:p}}),N=`${v.head.seq}${B}`,O=yield ye.channel.sendPacket(v,{timeout:9e4,requestId:N});if(O){const{HelloInterval:z,InstId:X,TinyId:rA,TimeStamp:DA,CustomStatus:GA,PurchaseBits:VA,A2Key:ee,RichMsgAuthKey:Ee,ErrorCode:We,ErrorInfo:ot,ActionStatus:at}=O;return{helloInterval:z,instanceID:X,tinyID:rA,timeStamp:DA,customStatus:GA,purchaseBits:VA,a2Key:ee,authKey:Ee,errorCode:We,errorInfo:ot,actionStatus:at}}})}function bu(){const{store:p}=ye;return ua(p.get("instance").sdkAppId)!==ut.CHINA}function wl(p){var B;try{const v=$i.getStorage("errorMessage");if(!p||!v)return"";const N=((B=JSON.parse(v))===null||B===void 0?void 0:B.errorMessage)||{},{code:O,replacement1:z="",replacement2:X=""}=p;if(!O)return"";const rA=bu()?`${O}_en`:`${O}_cn`;let DA=N[N[rA]?rA:O]||"";return DA&&(z&&(DA=DA.replace("$replacement1",z)),X&&(DA=DA.replace("$replacement2",X))),DA}catch(v){return console.warn("Error parsing stored error messages:",v),""}}class rs extends Error{constructor(B={}){B.code=B.code||B.errorCode;let{functionName:v="Unknown",code:N,message:O="",data:z="",moreMessage:X="",errorMessage:rA=""}=B;rA=(N?wl(B):"")||rA||O;let DA=N?`${v} failed. error: {"message": ${rA}, "code": ${N}}`:`${v} failed. error: {"message": ${rA}}`;DA=`${DA} ${X}`,super(),this.code=N,this.errorCode=N,this.errorMessage=rA,this.message=DA,this.data=z}}function gs(p,B){var v;if(p&&((v=ye.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)!==!0)throw new rs({code:Lo.USER_NOT_LOGGED_IN,functionName:B})}function ud(p,B,v){if(Array.isArray(p))for(let N=0;N{return GA===(VA=N,Object.prototype.toString.call(VA).match(/^\[object (.*)\]$/)[1].toLowerCase());var VA})){for(let VA=0;VA{const{interceptor:O,context:z}=N;O.apply(z,[v])})}(p)}function Sr(p,B){uI.push({interceptor:p,context:B})}function Mc(p){const{params:B,auth:v}=p;B&&typeof B=="object"&&Object.assign(Ed,B),v&&typeof v=="object"&&Object.assign(RE,v)}function Wc(p){return ye.store.get("commercialConfig").get(p)}class tn{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(B,v)=>{const N=Date.now();v?(this._stepStartTimes.set(`${B}-${v}`,N),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${v} started at ${new Date(N).toISOString()}`)):(this._workflowStartTimes.set(B,N),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] started at ${new Date(N).toISOString()}`))},success:(B,v)=>{const N=Date.now();if(v){const O=this._stepStartTimes.get(`${B}-${v}`),z=O?N-O:0;this._stepStartTimes.delete(`${B}-${v}`),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${v} completed successfully at ${new Date(N).toISOString()} (${z}ms)`)}else{const O=this._workflowStartTimes.get(B),z=O?N-O:0;this._workflowStartTimes.delete(B),ye.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] completed successfully at ${new Date(N).toISOString()} (${z}ms)`)}},error:(B,v,N)=>{const{ssoLog:O,utils:{safeStringify:z}}=ye,X=Date.now();if(v){const rA=this._stepStartTimes.get(`${B}-${v}`),DA=rA?X-rA:0;this._stepStartTimes.delete(`${B}-${v}`),O.error("_executeWorkflowStep",`[Workflow ${B}] Step ${v} failed at ${new Date(X).toISOString()} (${DA}ms) ${z(N)}`,{error:N})}else{const rA=this._workflowStartTimes.get(B),DA=rA?X-rA:0;this._workflowStartTimes.delete(B),O.error("_executeWorkflowStep",`[Workflow ${B}] failed at ${new Date(X).toISOString()} (${DA}ms) ${z(N)}`,{error:N})}}}}static getInstance(){return tn._instance||(tn._instance=new tn),tn._instance}static setInstance(B){tn._instance=B}init(){this._initializeWorkflows()}registerWorkflowStep(B,v,N,O){if(!this._handlers.has(B))return void ye.ssoLog.debug("registerWorkflowStep",`Workflow '${B}' not defined in core`);if(!Kt[B].find(X=>X.stepId===v))return void ye.ssoLog.debug("registerWorkflowStep",`Step '${v}' not defined in workflow '${B}'`);const z=this._handlers.get(B);z.has(v)||z.set(v,O?N.bind(O):N)}executeWorkflow(B,v){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(B))return;ye.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Started execution at ${new Date().toISOString()}`);const N=Kt[B],O={},z={cancelled:!1};this._activeWorkflows.set(B,{cancelToken:z});try{const X=new Map;N.forEach(DA=>{X.set(DA.stepId,DA)});const rA={workflowName:B,pendingSteps:new Set(N.map(DA=>DA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:X,stepResults:O,data:v,cancelToken:z};yield new Promise((DA,GA)=>{const VA=()=>{if(z.cancelled)return void DA();this._getExecutableSteps({pendingSteps:rA.pendingSteps,completedSteps:rA.completedSteps,stepMap:rA.stepMap,workflowName:B}).filter(ee=>!rA.runningSteps.has(ee)).forEach(ee=>{rA.completedSteps.has(ee)||rA.runningSteps.has(ee)||this._executeWorkflowStep(ee,rA,{onComplete:()=>{if(rA.pendingSteps.size===0)return void DA();this._getExecutableSteps({pendingSteps:rA.pendingSteps,completedSteps:rA.completedSteps,stepMap:rA.stepMap,workflowName:B}).filter(Ee=>!rA.runningSteps.has(Ee)).length===0&&rA.runningSteps.size===0&&(ye.ssoLog.debug("executeWorkflow",`Workflow ${B} completed with some steps skipped due to dependency failures`),DA())},onError:GA,onStepComplete:VA})})};VA()}),ye.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Completed execution at ${new Date().toISOString()}`)}catch(X){ye.ssoLog.error("executeWorkflow",`[Workflow ${B}] Failed execution at ${new Date().toISOString()}`,{error:X})}finally{this._activeWorkflows.delete(B)}})}_executeWorkflowStep(B,v,N){return pA(this,void 0,void 0,function*(){const{workflowName:O,runningSteps:z,stepMap:X,stepResults:rA,data:DA}=v;z.add(B),this._logWorkflowExecution(O,B,"start");try{const GA=X.get(B);let VA=null;GA?.dependency&&(l(GA.dependency)?VA=rA[GA.dependency]:Array.isArray(GA.dependency)&&(VA={},GA.dependency.forEach(Ee=>{VA[Ee]=rA[Ee]})));const ee=this._handlers.get(O).get(B);if(ee){const Ee=yield Promise.resolve(ee({data:DA,result:VA}));rA[B]=Ee,this._logWorkflowExecution(O,B,"success")}v.completedSteps.add(B)}catch(GA){const VA=`[Workflow].${O}.${B}`,{errorCode:ee,errorInfo:Ee=`${VA} failed`}=GA||{},We=new rs({functionName:VA,code:ee,message:Ee});ye.ssoLog.error(VA,Ee,{error:We}),this._logWorkflowExecution(O,B,"error",GA),N.onError(GA)}finally{z.delete(B),v.pendingSteps.delete(B),N.onStepComplete(),N.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Kt).forEach(B=>{this._handlers.has(B)||this._handlers.set(B,new Map)})}_cancelWorkFlow(B){const v=this._activeWorkflows.get(B);if(!v)return;const{cancelToken:N}=v;N.cancelled=!0,this._activeWorkflows.delete(B)}_cancelAllWorkflows(){Object.keys(Kt).forEach(B=>{this._cancelWorkFlow(B)})}_validateWorkflow(B){return Kt[B]?!!this._handlers.get(B):!1}_getExecutableSteps(B){const{pendingSteps:v,completedSteps:N,stepMap:O,workflowName:z}=B;return Array.from(v).filter(X=>{const rA=O.get(X)||{},{dependency:DA,skipIfDependencyMissing:GA=!0}=rA;if(!DA)return!0;if(l(DA))return this._isStepRegistered({workflowName:z,stepId:DA})?N.has(DA):!GA;if(h(DA)){if(DA.filter(VA=>!this._isStepRegistered({workflowName:z,stepId:VA})).length>0&&GA)return!1;for(const VA of DA)if(!N.has(VA))return!1;return!0}return!1})}_isStepRegistered(B){var v;const{workflowName:N,stepId:O}=B;return(v=this._handlers.get(N))===null||v===void 0?void 0:v.has(O)}_logWorkflowExecution(B,v,N,O){this._logHandlers[N](B,v)}}const ws=new Map,Ca=({type:p,groupID:B})=>p===hs.GRP_COMMUNITY||`${B}`.startsWith(La.COMMUNITY)&&!`${B}`.includes(La.TOPIC),Xr=(p="")=>{const B=p.startsWith("GROUP")?p.replace("GROUP",""):p;return B.startsWith(La.COMMUNITY)&&`${B}`.includes(La.TOPIC)},zc="openim",dd="million_group_open_http_svc";function Zg(p){return pA(this,void 0,void 0,function*(){const{servcmd:B,data:v}=function(z){const{data:X}=z;return gg(X)||wE(X)}(p)?function(z){let{servcmd:X,data:rA}=z;return wE(rA)?function(DA){const{servcmd:GA,data:VA}=DA;let{GroupId:ee=""}=VA;const Ee=ee;return[ee]=Ee.split(La.TOPIC),{servcmd:Xg(GA),data:Object.assign(Object.assign({},VA),{GroupId:ee,TopicId:Ee})}}(z):(gg(rA)&&(X=Xg(X)),{servcmd:X,data:rA})}(p):p,N=ye.common.generateProtocolData({servcmd:B,data:v}),O=`${N.head.seq}${B}`;return ye.channel.sendPacket(N,{requestId:O,timeout:p.timeout})})}function gg(p){const{Type:B,GroupId:v,GroupIdList:N=[]}=p,O=v||N[0]||"";return Ca({type:B,groupID:O})}function wE(p){const{GroupId:B=""}=p;return Xr(B)}function Xg(p){if(p.includes(zc))return p;const B=p.split(".")[1];return`${dd}.${B}`}function qn(){var p;return(p=ye.store.get("login"))===null||p===void 0?void 0:p.userId}const Ar=p=>h(p)||f(p),Fa=(p,B,v,N)=>{if(!Ar(p)||!Ar(B))return 0;let O=0;const z=Object.keys(B);let X;for(let rA=0,DA=z.length;rA{if(r(B))return"";if(p===hs.MSG_TEXT)return B.text||"";const v=ku[p];return v?lC(v):""},Zc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Xc="im_sdk_config_mgr.fetch_config",WI="im_sdk_config_mgr.push_configv2",EI="cloud-config",$c=2996,Al=new class{init(p){this.core=p}};function va(p){return pA(this,void 0,void 0,function*(){const{sdkAppId:B}=Al.core.store.get("instance")||{},v=Al.core.helper.generateProtocolData({servcmd:Xc,data:{uint32_sdkappid:B,uint64_version:p}}),N=`${v.head.seq}${Xc}`;return Al.core.channel.sendPacket(v,{requestId:N})})}var bg=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,helper:N,constants:{WORKFLOW_NAME:O,WORKFLOW_STEP:z},channel:X}=p;B.subscribeInnerEvent(WI,this._handlePushedConfig,this),N.registerWorkflowStep(O.SYNC_SERVER_INFO_AFTER_LOGIN,z.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),N.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Zc),X.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(p){return pA(this,void 0,void 0,function*(){var B;const v={code:0,data:""};return p&&(v.data=((B=this._core.store.get("cloudConfig"))===null||B===void 0?void 0:B[p])||""),v})}checkMethodCallOverLimit(p){if(!this._cmdFrequencyLimitMap.has(p))return;if(!this._methodCallFrequencyMap.has(p))return void this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});const{count:B,interval:v}=this._cmdFrequencyLimitMap.get(p);let{startTime:N,methodCallCounter:O}=this._methodCallFrequencyMap.get(p);if(Date.now()-N>1e3*v)this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});else if(O+=1,this._methodCallFrequencyMap.set(p,{startTime:N,methodCallCounter:O}),O>B)throw new this._core.helper.ChatError({code:$c,replacement1:p})}_handlePushedConfig(p){return pA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=this._core;B.info("_handlePushedConfig",v(p)),yield this._updateCloudConfig(p)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;try{if(this._canFetch()){const v=yield va(this._version);p.info("_fetchCloudConfigIfLogin",B(v)),yield this._updateCloudConfig(v)}this._core.helper.taskScheduler.addTask({id:EI,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(v){p.debug("_fetchCloudConfigIfLogin",B(v))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;if(this._canFetch())try{const v=yield va(this._version);p.info("_fetchCloudConfigIfReady",B(v)),yield this._updateCloudConfig(v)}catch(v){p.error("_fetchCloudConfigIfReady",B(v))}})}_updateCloudConfig(p){return pA(this,void 0,void 0,function*(){const B=this._parseCloudConfig(p);B&&(this._core.store.set("cloudConfig",B),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,B),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:B}}))})}_canFetch(){const{isLoggedIn:p}=this._core.store.get("login")||{};return p&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(p){const{int32_error_code:B,str_error_message:v,str_json_config:N,uint32_expired_time:O,uint32_sdkappid:z,uint64_version:X}=p;let rA=null;if(B===0){if(this._version!==X)try{rA=JSON.parse(N),this._version=X}catch{}this._expirationTime=Date.now()+1e3*O}else this._expirationTime=B===void 0?Date.now()+36e5:Date.now()+12e4;return rA}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var p;let B=(p=yield this.getServerConfig("cmd_frequency_limit"))===null||p===void 0?void 0:p.data;const{isEmpty:v}=this._core.utils;if(!v(B))try{B=JSON.parse(B),this._updateCmdFreqLimitMap(B)}catch(N){console.warn(N)}})}_updateCmdFreqLimitMap(p){p.forEach(B=>{this._cmdFrequencyLimitMap.set(B.cmd,{interval:B.interval,count:B.count})})}_reset(){this._core.helper.taskScheduler.removeTask(EI),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Zc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(WI,this._handlePushedConfig,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}};class ys{constructor(B=0,v=0){this.high=B,this.low=v}equal(B){return B!==null&&this.low===B.low&&this.high===B.high}toString(){const B=Number(this.high).toString(16);let v=Number(this.low).toString(16);if(v.length<8){let N=8-v.length;for(;N;)v=`0${v}`,N--}return B+v}}const Kn={SEARCH_GRP_SNS:new ys(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new ys(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new ys(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new ys(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new ys(0,Math.pow(2,6)).toString(),USER_STATUS:new ys(0,Math.pow(2,7)).toString(),CONV_MARK:new ys(0,Math.pow(2,9)).toString(),CONV_GROUP:new ys(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new ys(0,Math.pow(2,11)).toString(),MSG_EXT:new ys(0,Math.pow(2,13)).toString(),GRP_COUNTER:new ys(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new ys(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new ys(Math.pow(2,7)).toString(),PLUGIN_CS:new ys(Math.pow(2,8)).toString(),PLUGIN_PUSH:new ys(Math.pow(2,9)).toString(),PLUGIN_BOT:new ys(Math.pow(2,10)).toString(),MSG_REACTION:new ys(Math.pow(2,16)).toString(),FOLLOW:new ys(Math.pow(2,20)).toString()},vc="CommercialConfig",zI="commercial-config";var ZI=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(p){this._core=p;const{helper:B,notificationCenter:v,constants:{WORKFLOW_NAME:N,WORKFLOW_STEP:O,InnerEvent:z}}=p;v.subscribeInnerEvent(z.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),v.subscribeInnerEvent(z.LOGOUT,this._handleLogout,this),v.subscribeInnerEvent(z.DESTROY,this._dispose,this),B.registerWorkflowStep(N.SYNC_SERVER_INFO_AFTER_LOGIN,O.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),p.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),p.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(p){return pA(this,void 0,void 0,function*(){const B=parseInt(p,10).toString(2),{length:v}=B;let N,O=!0;for(let z=v-1,X=0;z>=0;z--,X++)if(B.charAt(z)==="1"&&(N=X<32?new ys(0,2**X).toString():new ys(2**(X-32),0).toString(),!this._featureMap.get(N))){O=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${vc}.isFeatureEnabled decimalNumber:${p} key:${N} ret:${O}`),{code:0,data:{enabled:O}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var p;const{ssoLog:B,utils:{safeStringify:v},common:{buildAndSendPacket:N}}=this._core;try{this._isFetching=!0;const O=yield N({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(p=this._core.store.get("instance"))===null||p===void 0?void 0:p.sdkAppId}});O&&(this._parseCommercialConfig(O),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(O){B.error("_fetchAndParseCommercialConfig",v(O))}finally{this._isFetching=!1}})}_syncCommercialConfig(p){return pA(this,void 0,void 0,function*(){const{purchaseBits:B}=p?.data||{};B&&(this._parsePurchaseBits(B),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:zI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var p;const B=(p=this._core.store.get("login"))===null||p===void 0?void 0:p.isLoggedIn,v=Date.now()>=this._expirationTime;return B&&!this._isFetching&&v}_handlePushedConfig(p){p?.body&&(this._parseCommercialConfig(p.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(p){const{ssoLog:B}=this._core;if(typeof p!="object")return;const{int32_error_code:v,str_error_message:N,str_purchase_bits:O,uint32_expired_time:z}=p;v===0?(this._parsePurchaseBits(O),this._expirationTime=Date.now()+1e3*z):v===void 0?(B.warn("_parseCommercialConfig",`${vc}._parseCommercialConfig failed. Invalid message format:`,p),this._expirationTime=Date.now()+36e5):(B.warn("_parseCommercialConfig",`${vc}._parseCommercialConfig errorCode:${v} errorMessage:${N}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(p){return p&&typeof p=="string"&&p.length>=1&&p.length<=64&&/[01]{1,64}/.test(p)}_parsePurchaseBits(p){const{ssoLog:B,utils:{safeStringify:v}}=this._core;if(this._isValidPurchaseBits(p)){this._purchaseBits=p,this._featureMap.clear(),this._methodKeyMap.clear();let N=null;for(let O=p.length-1,z=0;O>=0;O--,z++)if(N=z<32?new ys(0,2**z).toString():new ys(2**(z-32),0).toString(),p[O]==="1"){this._featureMap.set(N,!0);const X=this._getKeyByValue(Kn,N);X&&this._methodKeyMap.set(X,!0)}else{this._featureMap.set(N,!1);const X=this._getKeyByValue(Kn,N);X&&this._methodKeyMap.set(X,!1)}}else B.warn("_parsePurchaseBits",`${vc}.parsePurchaseBits invalid purchases:${v(p)}`)}_getKeyByValue(p,B){const v=Object.entries(p).find(([N,O])=>O===B);return v?v[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(zI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},_E=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,channel:N}=this._core;B.subscribeInnerEvent(v.OVERLOAD_PUSH,this._handleOverLoadPush,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),N.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(p){if(!this._serverOverloadInfoMap.has(p))return;const{overloadStartTimestamp:B,delaySeconds:v}=this._serverOverloadInfoMap.get(p);if(Date.now()-B<=1e3*v)throw new this._core.helper.ChatError({functionName:p,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(p)}_handleOverLoadPush(p){const{OverLoadServCmd:B,DelaySecs:v}=p;this._serverOverloadInfoMap.set(B,{overloadStartTimestamp:Date.now(),delaySeconds:v})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.OVERLOAD_PUSH,this._handleOverLoadPush,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this)}},rh=new class{constructor(){this.name="ConfigCenter"}install(p){Al.init(p),bg.install(p),ZI.install(p),_E.install(p)}},IC=new class{constructor(){this.name="ErrorMessage",this._core=null}install(p){return pA(this,void 0,void 0,function*(){if(this._core=p,this._canFetch()){const B=yield this._fetchErrorMessage();if(!B)return;const v=this._parseResponse(B);this._saveErrorMessage(v)}})}_canFetch(){const p=this._core.store.getStorage("errorMessage");return!p||this._isExpired(p)}_saveErrorMessage(p){this._core.store.setStorage("errorMessage",{errorMessage:p,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return pA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(p){console.error(p)}})}_isExpired(p){if(!p)return!0;const{errorMessageSavedTime:B}=p;return B&&new Date().getTime()-B>=6048e5}_parseResponse(p){if(typeof p=="string"){const B=p.split(`; -`),v={},N=new RegExp(/'/g);for(let O=0;O{var go,Xi,Ei;const Po=function(es,pi){const{From_Account:ji,From_AccountHeadurl:Ws,From_AccountNick:_e,IsNeedReadReceipt:_t,MsgBody:FA,MsgClientTime:Xt,MsgRandom:En,MsgSeq:Ai,MsgTimeStamp:us,SendMsgControl:vi,SupportMessageExtension:ho,To_Account:ht,TinyId:Qt,MsgCheckResult:ug,CloudCustomData:ks,IsPeerRead:Wi,MsgFlagBits:Hr,MsgVersion:oc,EventArray:is}=es;return{from:ji,avatar:Ws,nick:_e,needReadReceipt:_t===1,readReceiptSentByPeer:Wi,clientTime:Xt,messageFlagBits:Hr,random:En,sequence:Ai,time:us,messageControlInfo:vi,isSupportExtension:ho,to:ht,tinyID:Qt,checkResult:ug,cloudCustomData:ks,messageVersion:oc,eventArray:is,elements:pi.message.messageHelper.parseServerPushMessageElement(FA)}}(Ui,at);if(!((Ei=(Xi=(go=Ui?.EventArray)===null||go===void 0?void 0:go[0])===null||Xi===void 0?void 0:Xi.hasOwnProperty)===null||Ei===void 0)&&Ei.call(Xi,"C2cNotifyMsgArray"))Jt.push(...function(es){var pi;const ji=[];return(pi=es.EventArray)===null||pi===void 0||pi.forEach(Ws=>{var _e,_t;const{C2cNotifyMsgArray:FA}=Ws,Xt=(_t=(_e=FA?.[0])===null||_e===void 0?void 0:_e.WithdrawC2cMsgNotify)===null||_t===void 0?void 0:_t.C2cWithdrawInfoArray;Array.isArray(Xt)&&ji.push(...Xt)}),ji}(Ui));else{const es=at.message.messageFactory.createMessage(Object.assign(Object.assign({},Po),{conversationType:"C2C",flow:"in"})),{elements:pi}=Po;es.setElement(pi),Ut.push(es)}}),{unreadMessageList:Ut,revokedMessageList:Jt}}(DA.MsgList,B);return{syncFlag:DA?.SyncFlag,unreadMessageList:Ee,revokedMessageList:We,unreadCountList:GA,overflowUnreadCountList:VA,cookie:DA?.Cookie,groupTipList:ee}}catch(DA){console.warn(DA)}})}var el,kg;(function(p){p[p.START_SYNC=0]="START_SYNC",p[p.SYNCING=1]="SYNCING",p[p.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(el||(el={})),function(p){p[p.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",p[p.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(kg||(kg={}));var ro=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(p){this._core=p;const{constants:B}=p;p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(p){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:B=!1,isAfterNewMessageReceived:v=!1,isAfterLogin:N=!1}=p||{};let O=el.START_SYNC;const z=[],X=[],rA=[],DA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:O});){const GA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:O,syncTriggerEvent:v?kg.NEW_MESSAGE_RECEIVED:kg.LOGIN_SUCCESS});if(!GA)break;const{unreadMessageList:VA=[],revokedMessageList:ee=[],overflowUnreadCountList:Ee,unreadCountList:We,groupTipList:ot}=GA;if(this._cookie=GA?.cookie||"",O=GA?.syncFlag,this._parseAndSaveUnreadMessageList(VA),rA.push(...ee),this._updateConversationUnreadOptions({unreadCountList:We,overflowUnreadCountList:Ee,conversationUpdateFieldList:z}),Array.isArray(ot)&&X.push(...ot),B){const{messages:at}=this._handleNewMessageList(VA);DA.push(...at)}}return B?{conversationUpdateFieldList:z,revokedMessageList:rA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X,messages:DA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:z,isInstantMessage:!N,isUnreadC2CMessage:!0,revokedMessageList:rA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X}})}_syncUnreadDBMessageAfterLogin(){return pA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(p){return pA(this,void 0,void 0,function*(){if(p.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(p){const{unreadCountList:B,overflowUnreadCountList:v,conversationUpdateFieldList:N}=p,{constants:{OuterConstant:{CONV_C2C:O,CONV_SYSTEM:z}}}=this._core;B?.forEach(X=>{const{From_Account:rA,UnreadCount:DA}=X;if(rA!==z){const GA=N.find(({conversationID:VA})=>VA===`${O}${rA}`);GA?GA.unreadCount=DA:N.push({conversationID:`${O}${rA}`,unreadCount:DA,type:O})}}),v?.forEach(X=>{const{From_Account:rA,LastMsgTime:DA}=X;rA!==z&&(N.find(({conversationID:GA})=>GA===`${O}${rA}`)||N.push({conversationID:`${O}${rA}`,type:O,lastMsgTime:DA}))})}_syncUnreadDBMessageAfterReOnline(){return pA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(p){var B;const{messageDataHandler:v}=this._core.message||{},N=(B=this._core.store.get("login"))===null||B===void 0?void 0:B.userId,{from:O,nick:z,avatar:X,conversationID:rA=""}=p;if(O!==N){const DA=v.getLatestMsgSentByPeer(rA);if(DA){const{nick:GA,avatar:VA}=DA;z&&X?z===GA&&X===VA||v.updateNickAndAvatarOfSentMessage({conversationID:rA,latestNick:z,latestAvatar:X,isSentByMe:!1}):(p.nick=GA,p.avatar=VA)}}else{const DA=v.getLatestMsgSentByMe(rA);!DA||z===DA.nick&&X===DA.avatar||v.updateNickAndAvatarOfSentMessage({conversationID:rA,latestNick:z,latestAvatar:X,isSentByMe:!0})}}_handleNewMessageList(p){const{messageDataHandler:B}=this._core.message||{},v=new Map,N=[];return p.forEach(O=>{this._updateMessageProfile(O);let z=O.isModified===1;if(B.isMessageSentByCurrentInstance(O)?O.isModified=z:z=!1,O.isOnlineMessage())O._onlineOnlyFlag=!0,B.isMessageSentByCurrentInstance(O)||N.push(O);else if(this._shouldStoreUnreadMessage(O)){if(B.storeConversationMessage(O)){const{conversationID:X,conversationType:rA,conversationSubType:DA,flow:GA,_isExcludedFromUnreadCount:VA,_isExcludedFromLastMessage:ee}=O,Ee=ee?"":O;v.has(X)?(v.get(X).lastMessage=Ee,GA==="in"&&(VA||v.get(X).unreadCount++)):v.set(X,{conversationID:X,type:rA,subType:DA,unreadCount:VA||GA!=="in"?0:1,lastMessage:Ee})}B.isMessageSentByCurrentInstance(O)&&!z||N.push(O)}}),{messages:N,conversationOptions:v}}_shouldStoreUnreadMessage(p){var B;const{conversationID:v}=p,{message:N,appStore:O,utils:{isEmpty:z}}=this._core||{},X=Array.from(((B=O.conversationStore.getConversationMap())===null||B===void 0?void 0:B.keys())||[]),rA=this._getLocalLastMessageTime(v);return!N.messageDataHandler.isInMessageList(p)&&X.includes(v)&&this._localConversationIDListBeforeDisconnect.includes(v)&&!z(rA)}_fetchUnreadDBMessage(p){return pA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=this._core;try{B.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${v(p)}`);const O=yield ah(p,this._core);if(!O)return null;const{syncFlag:z,unreadMessageList:X,revokedMessageList:rA,cookie:DA,unreadCountList:GA,overflowUnreadCountList:VA,groupTipList:ee}=O;return this._parseAndSaveUnreadMessageList(X),{syncFlag:z,cookie:DA,unreadMessageList:X,revokedMessageList:rA,unreadCountList:GA,overflowUnreadCountList:VA,groupTipList:ee}}catch(N){console.log(N)}})}_canContinueSync({cookie:p,syncFlag:B}){var v;return B===el.START_SYNC||B===el.SYNCING&&!(!((v=this._core)===null||v===void 0)&&v.helper.isEmpty(p))}_parseAndSaveUnreadMessageList(p){p.forEach(B=>{const{ID:v}=B;this._unreadDBMessageMap.set(v,B)})}_handleDisconnect(){var p;const{appStore:B}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((p=B.conversationStore.getConversationMap())===null||p===void 0?void 0:p.keys())||[])}_getLocalLastMessageTime(p){const{message:B}=this._core,v=B.messageDataHandler.getLocalMessageList(p),N=v[v.length-1];return N?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(B=this._core)===null||B===void 0||B.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},uC=new class{init(p){var B;this._core=p,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var p,B;const v=document?.visibilityState==="visible";(p=this._core)===null||p===void 0||p.store.set("activityMonitor",{isActive:v}),(B=this._core)===null||B===void 0||B.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:v})}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(p){var B;this._core=p,this._bindAppActivityEvent(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var p,B,v,N,O;const{MINI_APP_NAMESPACE:z,IN_TT_MINI_GAME:X,IN_WX_MINI_GAME:rA}=((p=this._core)===null||p===void 0?void 0:p.utils)||{};X||rA?((B=z?.onShow)===null||B===void 0||B.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(v=z?.onHide)===null||v===void 0||v.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((N=z?.onAppShow)===null||N===void 0||N.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(O=z?.onAppHide)===null||O===void 0||O.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},NE=new class{init(p){const{IN_MINI_APP:B,IN_WX_MINI_PLUGIN:v}=p.helper;v||(B?TE.init(p):uC.init(p))}};const hd="none",GE="online";var tl=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(p){var B,v;const{isConnected:N,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:N,networkType:O}),(v=this._core)===null||v===void 0||v.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:N,networkType:O})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:GE})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:hd})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},dI=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:p}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),p.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(p){console.error(p)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:p}}=this._core;p.offNetworkStatusChange&&p.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(p){var B,v;const{isConnected:N,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:N,networkType:O}),(v=this._core)===null||v===void 0||v.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:N,networkType:O})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Lu=new class{init(p){const{IN_MINI_APP:B}=p.utils;B?dI.init(p):tl.init(p)}},Uu=new class{constructor(){this.name="SystemStateMonitor"}install(p){NE.init(p),Lu.init(p)}};const EC=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),wr="tui_room_svr.*";var cg=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=EC}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,helper:N}=p;B.subscribeInnerEvent(v.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),B.subscribeInnerEvent("im_open_push.msg_push",B.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),N.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),N.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(p){return pA(this,void 0,void 0,function*(){const B="transferBusinessCommand";try{const{serviceCommand:v=wr}=p||{};if(!this._isValidTransferredCommand(v))throw new this._core.helper.ChatError({code:2995,functionName:B});return{code:0,data:(yield function(O,z){return pA(this,void 0,void 0,function*(){const{helper:X,channel:rA}=z,{serviceCommand:DA=wr,data:GA}=O||{};let VA={};try{VA=typeof GA=="string"?JSON.parse(GA):GA}catch(We){console.warn(We)}const ee=X.generateProtocolData({servcmd:DA,data:VA}),Ee=`${ee.head.seq}${DA}`;return rA.sendPacket(ee,{requestId:Ee,shouldRejectOnError:!1})})}(p,this._core))||{}}}catch(v){throw console.warn(v),new this._core.helper.ChatError({code:v?.errorCode,message:v?.errorInfo,data:{},functionName:B})}})}_onCloudConfigUpdate(p={}){try{if(typeof p.rtc_cmd!="string")return;const B=JSON.parse(p.rtc_cmd);Array.isArray(B)&&(this._transferredCommands=new Set([...this._transferredCommands,...B]))}catch(B){console.log(B)}}_isValidTransferredCommand(p=""){const B=`${p?.split(".")[0]}.*`;return this._transferredCommands.has(B)}_onServerPushBusinessCommand(p){const{OuterEvent:B,notificationCenter:v}=this._core,{MsgContent:N}=p||{},{ROOM_CUSTOM_DATA_RECEIVED:O}=B;v.emitOuterEvent(O,{name:O,data:N})}_reset(){this._transferredCommands=EC}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;this._reset(),p.unSubscribeInnerEvent(B.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),p.unSubscribeInnerEvent("im_open_push.msg_push",p.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Rc=new class{init(p){this.core=p}};function Fu(p){return pA(this,void 0,void 0,function*(){var B;const{message:v,user:N,appStore:O,constants:{OuterConstant:z}}=Rc.core,X=O.conversationStore.getConversationMap();if(X.has(p)){const DA=(B=X.get(p))===null||B===void 0?void 0:B.userProfile;if(DA&&p.startsWith(z.CONV_C2C)){const{avatar:GA,nick:VA}=DA;Rc.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:GA,latestNick:VA,isSentByMe:!1})}}const{data:rA}=(yield N.userProfile.getMyProfile())||{};if(rA){const{avatar:DA,nick:GA}=rA;v.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:DA,latestNick:GA,isSentByMe:!0})}})}function Tl(p){return pA(this,void 0,void 0,function*(){const B=p.map(v=>v.revoker);try{const v=yield function(N){return pA(this,void 0,void 0,function*(){var O,z;const X=yield(O=Rc.core.user.userProfile)===null||O===void 0?void 0:O.getUserProfile({userIDList:N});return X?.data?(z=X.data)===null||z===void 0?void 0:z.reduce((rA,{userID:DA,nick:GA,avatar:VA})=>(rA[DA]={nick:GA||"",avatar:VA||""},rA),{}):null})}(B);v&&p.forEach(N=>{const{revoker:O}=N;v[O]&&(N.revokerInfo.nick=v[O].nick||"",N.revokerInfo.avatar=v[O].avatar||"",N.revokerInfo.userID=O)})}catch(v){console.debug(v)}})}const Bd=1,$r=2,CI=20,_n=2500,dC=1,il=300;function Qd(p){return pA(this,void 0,void 0,function*(){var B,v;const{appStore:N,utils:{isEmpty:O},common:{getCurrentUserID:z},notificationCenter:X,OuterEvent:rA,OuterConstant:{CONV_C2C:DA}}=Rc.core,{messageList:GA,conversationID:VA}=p,ee=N.conversationStore.getConversationMap();let Ee=(B=ee.get(VA))===null||B===void 0?void 0:B.peerReadTime;if(!Ee){const ot=VA.replace(DA,""),at=yield function(Ut){return pA(this,void 0,void 0,function*(){const Jt={To_Account:Ut};return Rc.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:Jt})})}([ot]);if(at){const{ReadTime:Ut}=at;Ee=Ut?.[0],ee.has(VA)&&(ee.get(VA).peerReadTime=Ee)}}if(ee.has(VA)){const ot=(v=ee.get(VA))===null||v===void 0?void 0:v.lastMessage;O(ot)||ot.fromAccount===z()&&ot.lastTime<=Ee&&!ot.isPeerRead&&(ot.isPeerRead=!0,N.conversationStore.updateConversation(VA,{lastMessage:ot}))}const We=[];GA.forEach(ot=>{ot.time<=Ee&&!ot.isPeerRead&&ot.flow==="out"&&(ot.isPeerRead=!0,We.push(ot))}),We.length>0&&X.emitOuterEvent(rA.MESSAGE_READ_BY_PEER,{name:rA.MESSAGE_READ_BY_PEER,data:We})})}var hI=new class{init(p){this._core=p,p.helper.registerApi({apiName:"getMessageList",context:this}),p.helper.registerApi({apiName:"getMessageListHopping",context:this}),p.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(p){return pA(this,void 0,void 0,function*(){try{const{message:B,OuterConstant:{Direction:v,CONV_C2C:N,CONV_GROUP:O},InnerEvent:{HISTORY_MESSAGE_FETCHED:z},notificationCenter:X}=this._core,{conversationID:rA,nextReqMessageID:DA}=p,GA=CI;if(rA==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const VA=this._getAvailableLocalMessagesCount({conversationID:rA,nextReqMessageID:DA});if(this._needFetchHistoryMessageList({conversationID:rA,availableLocalMessagesCount:VA,targetCount:GA})){let ee=null;if(rA.startsWith(O)?ee=yield B.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:Number(DA),count:GA,direction:v.FORWARD,shouldMarkCompleted:!0}):rA.startsWith(N)&&(ee=yield B.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,messageID:DA,count:GA,direction:v.FORWARD,shouldMarkCompleted:!0})),ee){const{nextReqMessageIDFromServer:Ee,hasNoMoreHistoryMessage:We,messageList:ot}=ee,at=B.messageDataHandler.prependLocalMessageList({messageList:ot,conversationID:rA});(function(Xi){const{appStore:Ei,message:Po,OuterConstant:es}=Rc.core,pi=Ei.conversationStore.getConversation(Xi),ji=Po.messageDataHandler.getLocalMessageList(Xi);if(!pi||ji.length===0||Xi===es.CONV_SYSTEM)return;const Ws=[];for(let _t=0;_tFA.isRevoked).length;_e=Ws.length-pi.unreadCount-_t}else _e=Ws.length-pi.unreadCount;for(let _t=0;_t<_e&&!Ws[_t].isRead;_t++)Ws[_t].setIsRead(!0)})(rA),yield Fu(rA),rA.startsWith(N)&&(yield Qd({messageList:ot,conversationID:rA}));const Ut=this._core.message.messageDataHandler.getLocalMessageList(rA).slice(0,at.length+VA),Jt=Ut.filter(Xi=>Xi.isRevoked);yield Tl(Jt),X.emitInnerEvent(z,at);const Ui={nextReqMessageID:We?"":String(Ee),messageList:Ut,isCompleted:We},go=Ut.map(Xi=>Xi.sequence);return{code:0,data:Ui,successLog:{message:`conversationID: ${rA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${VA} sequenceList: ${JSON.stringify(go)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:rA,nextReqMessageID:DA,count:GA}),successLog:{message:`conversationID: ${rA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${VA}}`}}}catch(B){const{code:v,message:N}=B||{};throw new this._core.helper.ChatError({code:v,message:N,moreMessage:`options: ${this._core.utils.safeStringify(p)}`})}})}getMessageListHopping(p){return pA(this,void 0,void 0,function*(){var B,v;const{OuterConstant:{Direction:N,CONV_C2C:O,CONV_GROUP:z},utils:{safeStringify:X}}=this._core,{conversationID:rA,sequence:DA,time:GA,direction:VA=N.FORWARD}=p,{utils:{isEmpty:ee},message:Ee,notificationCenter:We,InnerEvent:{HISTORY_MESSAGE_FETCHED:ot}}=this._core;if(![N.BACKWARD,N.FORWARD].includes(VA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${X(p)}`});let{count:at=CI}=p;at=at>CI?CI:at;let Ut=null;if(rA.startsWith(z)){if(Ut=yield Ee.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:DA,count:at,direction:VA}),Ut){const{nextReqMessageIDFromServer:Jt,hasNoMoreHistoryMessage:Ui,messageList:go,invisibleSequenceList:Xi}=Ut;if(this._core.message.messageDataHandler.storeSparseMessageList(go),We.emitInnerEvent(ot,go),VA===N.FORWARD){const Ei=Ui&&Jt<1;return{code:0,data:{messageList:go,isCompleted:Ei,nextMessageSeq:Ei?"":Jt}}}if(VA===N.BACKWARD){if(ee(go)&&ee(Xi))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const Ei=((B=go?.[go.length-1])===null||B===void 0?void 0:B.sequence)||0,Po=((v=Xi?.[Xi.length-1])===null||v===void 0?void 0:v.sequence)||0;return{code:0,data:{messageList:go.filter(es=>es.sequence>=DA),isCompleted:!Ui,nextMessageSeq:Ui?Math.max(Ei,Po)+1:""}}}return{code:0,data:Ut}}}else if(rA.startsWith(O)&&(Ut=yield Ee.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,count:at+1,time:GA,direction:VA}),Ut)){const{messageList:Jt,lastMessageTime:Ui,hasNoMoreHistoryMessage:go}=Ut;return We.emitInnerEvent(ot,Jt),go||(VA===N.FORWARD?Jt.shift():Jt.pop()),Ee.messageDataHandler.storeSparseMessageList(Jt),yield Qd({messageList:Jt,conversationID:rA}),{code:0,data:{messageList:Jt,isCompleted:go,nextMessageTime:go?"":Ui}}}})}clearHistoryMessage(p){return pA(this,void 0,void 0,function*(){var B;const{appStore:v,common:{ChatError:N,getCurrentUserID:O},OuterConstant:{CONV_C2C:z,CONV_GROUP:X},apiMap:rA,message:DA}=this._core,GA=v.conversationStore.getConversation(p);if(!GA)throw new N({code:_n});const VA={fromAccount:O()},{type:ee}=GA;ee===z?(VA.type=Bd,VA.toAccount=p.replace(z,"")):ee===X&&(VA.type=$r,VA.toGroupID=p.replace(X,""));try{return yield(B=rA?.setMessageRead)===null||B===void 0?void 0:B.call(rA,{conversationID:p}),(yield function(We){return pA(this,void 0,void 0,function*(){const{fromAccount:ot,type:at,toAccount:Ut,toGroupID:Jt}=We,Ui={From_Account:ot,Type:at,To_Account:Ut,ToGroupid:Jt};return Rc.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:Ui})})}(VA))&&(DA.messageDataHandler.deleteConversationMessageList(p),DA.messageHistory.completedHistoryConversations.delete(p),DA.messageHistory.clearHistoryMessageListFetchAnchors(p),this._updateConversationLastMessage(p)),{code:0,data:{conversationID:p},successLog:{message:`convID:${p}`}}}catch(Ee){const{errorCode:We}=Ee;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:We,moreMessage:`convID:${p}`})}})}_updateConversationLastMessage(p){const{appStore:B}=this._core;B.conversationStore.updateConversation(p,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:p,nextReqMessageID:B}){const{OuterConstant:{CONV_C2C:v,CONV_GROUP:N}}=this._core,O=this._core.message.messageDataHandler.getLocalMessageList(p),{length:z}=O;if(!B)return z;let X=-1;return p?.startsWith(v)?X=O.findIndex(rA=>rA.ID===B):p?.startsWith(N)&&(X=O.findIndex(rA=>B.includes("-")?rA.ID===B:String(rA.sequence)===B)),X===-1?0:X}_needFetchHistoryMessageList({conversationID:p,availableLocalMessagesCount:B,targetCount:v}){const{message:N}=this._core;return BB.startsWith(O)?Ee.ID===v:String(Ee.sequence)===v),VA=ee>N?ee-N:0,DA=ee):VA=rA>N?rA-N:0,GA.messageList=X.slice(VA,ee),GA.isCompleted=DA<=N&&z.messageHistory.completedHistoryConversations.has(B),GA.isCompleted?GA.nextReqMessageID="":GA.nextReqMessageID=this._generateNextReqMessageID({conversationID:B,targetIndex:VA}),B.startsWith(O)&&(yield Fu(B),yield Qd({messageList:GA.messageList,conversationID:B})),GA})}_generateNextReqMessageID({conversationID:p,targetIndex:B}){const v=this._core.message.messageDataHandler.getLocalMessageList(p);return p.startsWith("C2C")?v[B].ID:String(v[B].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},Oa=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(p){this._core=p;const{common:{workflowManager:B},constants:{WORKFLOW_NAME:v,WORKFLOW_STEP:N,InnerEvent:O}}=p;B.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,N.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),B.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,N.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),p.notificationCenter.subscribeInnerEvent(O.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(p){const{conversationList:B}=p?.result||{},{OuterConstant:v,utils:{isArray:N}}=this._core;if(N(B)){const O=B.filter(z=>z.type===v.CONV_GROUP&&z.groupProfile.type!==v.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(O)}}_recoverGroupHistoryMessage(p){return pA(this,void 0,void 0,function*(){const{OuterConstant:B}=this._core,v=[],N=[];return yield Promise.all(p?.map(O=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:z}={},lastMessage:{lastSequence:X}={}}=O,rA=`${B.CONV_GROUP}${z}`;let DA=this._getLocalLastMessageSequence(rA);this._shouldRecoverHistory({localLastMessageSequence:DA,serverLastMessageSequence:X})&&(yield this._recoverGroupHistoryForConversation({conversationID:rA,localLastMessageSequence:DA,serverLastMessageSequence:X,groupTipList:N})),v.push(rA.replace(B.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:v,groupTipList:N}})}_recoverGroupHistoryForConversation(p){return pA(this,arguments,void 0,function*({conversationID:B,localLastMessageSequence:v,serverLastMessageSequence:N,groupTipList:O}){try{const{utils:{isArray:z,isObject:X,isEmpty:rA},OuterEvent:DA,OuterConstant:GA,notificationCenter:VA,message:ee,appStore:Ee,common:{getMessagePreviewText:We,buildLastMessage:ot}}=this._core,at=N-v,Ut=Math.min(20,at),Jt={},Ui=yield ee.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:B,sequence:v+Ut,direction:GA.Direction.FORWARD,count:Ut}),{nextReqMessageIDFromServer:go,hasNoMoreHistoryMessage:Xi,messageList:Ei,serverGroupTipList:Po}=Ui;z(Po)&&O.push(...Po);const es=Xi&&go<0,pi=[];if(z(Ei)&&(Ei.forEach(ji=>{ee.messageReceiver.groupMessageReceiver.updateMessageProfile(ji),ji.from===GA.CONV_SYSTEM&&(ji.isSystemMessage=!1),ee.messageDataHandler.storeConversationMessage(ji)&&!rA(ji.payload)&&(pi.push(ji),ji._isExcludedFromLastMessage||(Jt.lastMessage=ot(ji)))}),pi.length>0&&VA.emitOuterEvent(DA.MESSAGE_RECEIVED,{name:DA.MESSAGE_RECEIVED,data:pi})),!es&&Ei.length>0){const ji=Ei[Ei.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:B,localLastMessageSequence:ji,serverLastMessageSequence:N,groupTipList:O})}X(Jt.lastMessage)&&(Jt.lastMessage.messageForShow=We(Jt.lastMessage.type,Jt.lastMessage.payload),Ee.conversationStore.updateConversation(B,Jt))}catch(z){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${B}`,{error:z})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:p}=this._core,B=p.messageDataHandler.getContinuousMessagesByConversation();for(const[v,N]of B){const O=Array.from(N.values());if(O?.length>0){const z=O[O.length-1];v.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(v,z.time):v.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(v,z.sequence)}}}_getLocalLastMessageSequence(p){const{message:B}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(p))return this._lastMessageSequenceMapOnDisconnect.get(p);const v=B.messageDataHandler.getLocalMessageList(p),N=v[v.length-1];return N?.sequence}_shouldRecoverHistory(p){const{localLastMessageSequence:B,serverLastMessageSequence:v}=p;if(typeof B!="number"||typeof v!="number")return!1;const N=v-B;return v!==0&&B>0&&N>=dC&&N{z.type===v.CONV_C2C&&O.push(z)}),this._recoverC2CHistoryMessage(O)}}_recoverC2CHistoryMessage(p){return pA(this,void 0,void 0,function*(){yield Promise.all(p?.map(B=>pA(this,void 0,void 0,function*(){const{conversationID:v,lastMessage:{lastTime:N}={}}=B,O=this._getLocalLastMessageTime(v);this._shouldRecoverC2CHistory({localLastMessageTime:O,serverLastMessageTime:N})&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:O,serverLastMessageTime:N}))})))})}_shouldRecoverC2CHistory(p){const{localLastMessageTime:B,serverLastMessageTime:v}=p,N=v-B;return B>0&&N>=1&&N<=600}_recoverHistoryForC2CConversation(p){return pA(this,void 0,void 0,function*(){var B;const{conversationID:v,localLastMessageTime:N,serverLastMessageTime:O}=p,{utils:{isArray:z,isObject:X,isEmpty:rA,safeStringify:DA},OuterEvent:GA,OuterConstant:VA,notificationCenter:ee,message:Ee,appStore:We,common:{getMessagePreviewText:ot,buildLastMessage:at}}=this._core;try{const Ut={},Jt=yield Ee.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,direction:VA.Direction.BACKWARD,time:N,count:20});if(rA(Jt))return;const{hasNoMoreHistoryMessage:Ui,messageList:go}=Jt,Xi=[];z(go)&&(go.forEach(Po=>{Ee.messageDataHandler.storeConversationMessage(Po)&&!rA(Po.payload)&&(Xi.push(Po),Po._isExcludedFromLastMessage||(Ut.lastMessage=at(Po)))}),Xi.length>0&&ee.emitOuterEvent(GA.MESSAGE_RECEIVED,{name:GA.MESSAGE_RECEIVED,data:Xi}));const Ei=(B=go[go.length-1])===null||B===void 0?void 0:B.time;!Ui&&Ei>O&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:Ei,serverLastMessageTime:O})),X(Ut.lastMessage)&&(Ut.lastMessage.messageForShow=ot(Ut.lastMessage.type,Ut.lastMessage.payload),We.conversationStore.updateConversation(v,Ut))}catch(Ut){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${v} error: ${DA(Ut)}`)}})}_getLocalLastMessageTime(p){const{message:B}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(p))return this._lastMessageTimeMapOnDisconnect.get(p);const v=B.messageDataHandler.getLocalMessageList(p),N=v[v.length-1];return N?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},CC=new class{constructor(){this.name="HistoryMessage"}install(p){this._core=p,Rc.init(p),hI.init(p),Oa.init(p),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this.dispose,this),Oa.dispose()}_reset(){Oa.reset()}},Pa=new class{init(p){this.core=p}},ur=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(p){const{helper:{registerExperimentalAPI:B}}=p;this._core=p,B("reportModalView",this),B("reportTUIFeatureUsage",this),B("reportRoomEngineEvent",this)}reportModalView(p){const{ssoLog:B,utils:{safeStringify:v,isString:N}}=this._core;try{if(!N(p))throw new Error("reportModalView data is not a string");B.createSSOLogData({method:"reportModalView",message:p,eventType:30}).end(!0)}catch(O){B.debug(`reportModalView Report failed: ${v(O)}`)}}reportTUIFeatureUsage(p){const{ssoLog:B,utils:{safeStringify:v,isEmpty:N}}=this._core,{atomicStoreID:O}=p;try{N(O)||this._reportedAtomicStoreIDs.has(O)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${p.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:O}),this._reportedAtomicStoreIDs.add(O))}catch(z){B.debug(`reportTUIFeatureUsage Report failed: ${v(z)}`)}}reportRoomEngineEvent(p){const{utils:{safeStringify:B},ssoLog:v}=this._core;try{v.debug(`reportRoomEngineEvent Report: ${B(p)}`);const{eventId:N,eventCode:O,eventResult:z,eventMessage:X,moreMessage:rA,extensionMessage:DA}=p;v.createSSOLogData({method:DA,code:N,message:X,eventType:30,costTime:O,uiPlatform:z,moreMessage:rA}).end(!0)}catch(N){v.debug(`reportRoomEngineEvent Report failed: ${B(N)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},pd=new class{constructor(){this.name="DataReport"}install(p){this._core=p;const{notificationCenter:B,InnerEvent:{LOGOUT:v,DESTROY:N}}=p;Pa.init(p),ur.init(p),B.subscribeInnerEvent(v,this._reset,this),B.subscribeInnerEvent(N,this._dispose,this)}_reset(){ur.reset()}_dispose(){const{notificationCenter:p,InnerEvent:{LOGOUT:B,DESTROY:v}}=this._core;p.unSubscribeInnerEvent(B,this._reset,this),p.unSubscribeInnerEvent(v,this._dispose,this),ur.dispose()}};let Ou=da.STANDARD,Er=[];Ou=da.BASIC,Er=[IC,rh,ro,Uu,cg,CC,pd];function wc(p,B){const{operationType:v,memberInfoList:N,operatorInfo:O}=p||{};let z={};if(Rs(N)?Rs(O)||(z=O):v!==sa.JOINED&&v!==sa.KICKED&&v!==sa.ADMIN_SET&&v!==sa.ADMIN_CANCELED||(z=Object.assign({},N[0])),!Rs(z)){const{nick:X="",avatar:rA=""}=z;B.nick=X,B.avatar=rA}}const ol=p=>({lastTime:p?.time||p?.lastTime||0,lastSequence:p?.sequence||p?.lastSequence||0,fromAccount:p?.from||p?.fromAccount||"",messageForShow:jI(p?.type,p?.payload),payload:p?.payload||null,type:p?.type||"",isRevoked:p?.isRevoked||!1,cloudCustomData:p?.cloudCustomData||"",onlineOnlyFlag:p?._onlineOnlyFlag||!1,nick:p?.nick||"",nameCard:p?.nameCard||"",version:p?.version||0,isPeerRead:p?.isPeerRead||!1,revoker:p?.revoker||null});var Lg=Object.freeze({__proto__:null,ChatError:rs,WorkflowManager:tn,buildAndSendPacket:Zg,buildLastMessage:ol,get builtInPlugins(){return Er},checkBusinessCapabilityBits:Wc,deepMerge:Fa,getCurrentUserID:qn,getErrorMessage:wl,getMessagePreviewText:jI,isC2CConv:p=>l(p)&&p.slice(0,3)===_g.CONV_C2C,isCommunity:Ca,isGroupConv:p=>l(p)&&p.slice(0,5)===_g.CONV_GROUP,isInternational:bu,isTopic:Xr,isUnlimitedAVChatRoom:function(){var p;return!!(!((p=ye.store.get("instance"))===null||p===void 0)&&p.unlimitedAVChatRoom)},liteChatInstanceMap:ws,registerInterceptor:Sr,registerValidateConfig:Mc,requireAuth:gs,get sdkEdition(){return Ou},setGroupTipsUserInfo:wc,t:lC,updateGroupAtInfo:(p,B)=>{const{CONV_AT_ME:v,CONV_AT_ALL:N,CONV_AT_ALL_AT_ME:O}=hs;if(function(rA,DA){const{CONV_AT_ME:GA,CONV_AT_ALL:VA,CONV_AT_ALL_AT_ME:ee}=hs,{groupID:Ee,sequence:We}=rA;let ot=!1;return Ca({groupID:Ee})&&DA.forEach(at=>{at.messageSequence===We&&(at.atTypeArray.includes(GA)&&rA.groupAtType.includes(VA)&&(at.atTypeArray=[ee]),at.atTypeArray.includes(VA)&&rA.groupAtType.includes(GA)&&(at.atTypeArray=[ee],at.__random=rA.__random,at.__sequence=rA.__sequence),ot=!0)}),ot}(p,B))return;let z=[...p.groupAtType];z.includes(v)&&z.includes(N)&&(z=[O]);const X={from:p.from,groupID:p.groupID,topicID:p.topicID,messageSequence:p.sequence,atTypeArray:z,__random:p.__random,__sequence:p.__sequence};B.push(X)},validateAndExecute:_l,validateParameters:ud});class Oo{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Oo._instance||(Oo._instance=new Oo),Oo._instance}static setInstance(B){Oo._instance=B}installBuiltInPlugin(B){B&&this._installPlugin(B,this._builtInPlugins)}installExternalPlugin(B){B&&this._installPlugin(B,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(B,v){let N=[];N=h(B)?B:[B];const O=N.findIndex(X=>X?.name==="AVChatRoom"),z=O>-1?N.splice(O,1):[];N.forEach(X=>{this._isPluginInstalled(X.name)||(X&&fe(X.install)?(v.add(X.name),fe(X.getInstalledSubPlugins)?(z?.forEach(rA=>v.add(rA?.name)),X.install(js.getInstance().exposeApiForPlugin(),z)):X.install(js.getInstance().exposeApiForPlugin()),fe(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):fe(X)?(v.add(X.name),X(js.getInstance().exposeApiForPlugin()),fe(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(B){return this._builtInPlugins.has(B)||this._externalPlugins.has(B)}_isLoggedIn(){var B;return((B=ye.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}}var $g=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(p){return this._conversationMap.get(p)}updateConversation(p,B,v){const{emit:N=!0,needSort:O=!1}=v||{},z=this._conversationMap.get(p);z&&!Rs(B)&&(Object.keys(B).forEach(X=>{z[X]=B[X]}),N&&ye.notificationCenter.emitInnerEvent(ui.CONVERSATION_UPDATED,{needSort:O}))}deleteConversation(p){this._conversationMap.has(p)&&(this._conversationMap.delete(p),ye.notificationCenter.emitInnerEvent(ui.CONVERSATION_UPDATED))}},Za=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(p){return this._groupMap.get(p)}updateGroup(p,B){const v=this._groupMap.get(p);v&&!Rs(B)&&Object.keys(B).forEach(N=>{v[N]=B[N]})}},Nl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(p,B,v){var N;const{operation:O,updateUnreadCount:z=!0}=v,X=Do(v,["operation","updateUnreadCount"]),rA=[];for(const DA of B){const GA=(N=this._messagesByConversation.get(p))===null||N===void 0?void 0:N.get(DA);if(!GA)return!1;Object.keys(X).forEach(VA=>{GA[VA]=X[VA]}),rA.push(GA)}return this._emitMessageStoreOperationEvent(O,{conversationID:p,messageList:rA,updateUnreadCount:z}),rA}getMessagesByConversation(p){var B;return[...((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(p,B){const{conversationID:v}=B;Xr(v)?ye.notificationCenter.emitInnerEvent(ag[p],B):ye.notificationCenter.emitInnerEvent(p,B)}},Aa=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(p){return this.userProfileMap.get(p)}getFriend(p){return this.friendMap.get(p)}},gh=Object.freeze({__proto__:null,conversationStore:$g,groupStore:Za,messageStore:Nl,userStore:Aa});class js{static getInstance(){return js._instance||(js._instance=new js),js._instance}static setInstance(B){js._instance=B}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:ye.notificationCenter.subscribeOuterEvent.bind(ye.notificationCenter),off:ye.notificationCenter.unSubscribeOuterEvent.bind(ye.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Oo.getInstance().installExternalPlugin.bind(Oo.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(B){ye.ssoLog.debug("registerPlugin",B)}statKeyFeatureUsage(B){ye.ssoLog.debug("statTUIKeyFeatures",B)}setLogLevel(B){ye.ssoLog.debug("setLogLevel",B),ye.ssoLog.setLogLevel(B)}setApplicationID(B){ye.store.set("instance",{applicationID:B})}getApiMap(){return this._apiMap}setApiMap(B){this._apiMap=B}registerApi(B){const{common:{timeManager:v},utils:{safeStringify:N}}=ye,{apiName:O,context:z,methodName:X=O,matcher:rA}=B;this._apiHandlersMap[O]||(this._apiHandlersMap[O]=[]),this._apiHandlersMap[O].push({context:z,methodName:X,matcher:rA}),this._apiMap[O]&&this._apiHandlersMap[O].length!==1||(this._apiMap[O]=(...DA)=>{const GA=v.getServerTimeMs();let VA=0;O==="login"&&(VA=4),rr.includes(O)&&ye.ssoLog.debug(O,`${O} start params: ${N(DA)}`),_l(X,DA);const ee=this._apiHandlersMap[O];for(const Ee of ee)if(!Ee.matcher||Ee.matcher(DA))try{const We=Ee.context[Ee.methodName].bind(Ee.context)(...DA);return this._isPromiseLike(We)?this._handleAsyncResult(We,O,VA,GA):(this._reportApiSuccessLog({result:We,apiName:O,eventType:VA,startTime:GA}),We)}catch(We){throw ye.ssoLog.error(O,`${O} fail ${We?.message||We?.errorMessage})`,{error:We,costTime:v.getServerTimeMs()-GA,eventType:VA,method:O}),We}})}registerExperimentalAPI(B,v,N){const O=N||B;this._experimentalApiMap[B]=v[O].bind(v)}destroy(){return pA(this,void 0,void 0,function*(){var B,v;try{!((B=ye.store.get("login"))===null||B===void 0)&&B.isLogin&&(yield this._apiMap.logout()),ye.notificationCenter.emitInnerEvent(ui.DESTROY)}catch(N){console.debug("destroy error: ",N)}finally{ye.notificationCenter.emitOuterEvent(Dn.SDK_DESTROY,{SDKAppID:(v=ye.store.get("instance"))===null||v===void 0?void 0:v.sdkAppId}),ws.clear(),Oo.getInstance().clear(),tn.getInstance().destroy(),ye.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:ui,InnerEventSubType:ye.notificationCenter.InnerEventSubType,OuterEvent:Dn,OuterConstant:hs,SignalingEvent:no,helper:Object.assign(Object.assign(Object.assign({},ye.utils),ye.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Sr,registerValidateConfig:Mc,checkBusinessCapabilityBits:Wc,registerWorkflowStep:tn.getInstance().registerWorkflowStep.bind(tn.getInstance()),ChatError:rs}),apiMap:this._apiMap},ye),{constants:Object.assign(Object.assign({},qI),ye.constants),common:Object.assign(Object.assign(Object.assign({},Lg),ye.common),{workflowManager:tn.getInstance()}),utils:ye.utils,appStore:gh})}callExperimentalAPI(B,v){return ye.ssoLog.debug(`callExperimentalAPI.${B} start params: ${ye.utils.safeStringify(v)}`),this._experimentalApiMap[B]?this._experimentalApiMap[B](v):(ye.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${B} not found, params: ${ye.utils.safeStringify(v)}`),Promise.reject(new rs({code:Lo.INVALID_OPERATION})))}_isPromiseLike(B){return B!==null&&typeof B=="object"&&typeof B.then=="function"}_handleAsyncResult(B,v,N,O){return B.then(z=>(this._reportApiSuccessLog({result:z,apiName:v,eventType:N,startTime:O}),z)).catch(z=>{throw ye.ssoLog.error(v,`${v} fail ${z?.message||z?.errorMessage})`,{error:z,costTime:ye.common.timeManager.getServerTimeMs()-O,eventType:N,method:v,startTime:O}),z})}_reportApiSuccessLog(B){let{result:v,apiName:N,startTime:O,eventType:z}=B;const{timeManager:X}=ye.common,{successLog:{message:rA,moreMessage:DA}={message:"",moreMessage:""}}=v||{},GA=X.getServerTimeMs();N==="login"&&(O+=X.getTimeOffsetWithServer()),rr.includes(N)&&ye.ssoLog.info(N,`${N} success ${rA} ${DA}`,{costTime:GA-O,eventType:z,message:rA,moreMessage:DA,startTime:O}),v?.successLog&&delete v.successLog}}class XI{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:B,store:v}=ye;v.set("login",{isReady:!1}),js.getInstance().registerApi({apiName:"login",context:this}),js.getInstance().registerApi({apiName:"logout",context:this}),js.getInstance().registerApi({apiName:"getLoginUser",context:this}),js.getInstance().registerApi({apiName:"isReady",context:this}),js.getInstance().registerApi({apiName:"getServerTime",context:this}),js.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),B.subscribeInnerEvent(ui.RECONNECTED,this._reLogin,this),ye.notificationCenter.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}login(B){return pA(this,void 0,void 0,function*(){var v;const{sdkEdition:N}=ye.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new rs({functionName:"login",code:Lo.REPEAT_LOGIN});const O=yield this._performLogin(B);this._validateAfterLogin(O),this._handleLoginSuccess(O),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const z=(v=ye.channel.getSocketAdapter())===null||v===void 0?void 0:v.getId(),{appId:X,href:rA}=ye.store.get("instance")||{},{instanceID:DA,customStatus:GA}=O||{};return{code:0,data:O,successLog:{message:N,moreMessage:`socketID:${z} instanceID:${DA} customStatus:${GA} href: ${rA} appId: ${X}`}}}catch(O){const{errorCode:z}=O;z!==Lo.REPEAT_LOGIN&&(this._latestLoginAt=0);const X=new rs({functionName:"login",code:z});throw console.error(X),X}})}_reLogin(){return pA(this,void 0,void 0,function*(){var B;try{if(!this._isLoginIn())return;const v=yield Gu(this._customLoginInfo);if(v){const{instanceID:N,customStatus:O}=v;ye.store.set("login",{statusInstanceId:N}),tn.getInstance().executeWorkflow(nr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:O,statusType:_u.USER_STATUS_ONLINE});const z=(B=ye.channel.getSocketAdapter())===null||B===void 0?void 0:B.getId();ye.ssoLog.info("reLogin",`socketId:${z} instanceId:${N}`)}}catch(v){console.warn(v)}})}logout(){return pA(this,arguments,void 0,function*(B=za.USER_INITIATED){const{ssoLog:v}=ye;v.debug("logout",`logout start logoutReason: ${B}`);try{yield this._performLogout(B),v.info("logout","logout success"),ye.ssoLog.uploadSSOLogData()}catch(N){const{errorCode:O}=N;throw new rs({functionName:"logout",code:O})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?qn():""}isReady(){var B;return(B=ye.store.get("login"))===null||B===void 0?void 0:B.isReady}setCustomLoginInfo(B=""){this._customLoginInfo=B}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),tn.getInstance().reset(),ye.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:B}=ye.common;return B.getServerTimeMs()}_updateAndEmitSDKReady(){ye.store.set("login",{isReady:!0}),setTimeout(()=>{ye.notificationCenter.emitOuterEvent(Dn.SDK_READY,{name:Dn.SDK_READY})},1)}_updateAndEmitSDKNotReady(){ye.store.set("login",{isReady:!1}),ye.notificationCenter.emitOuterEvent(Dn.SDK_NOT_READY,{name:Dn.SDK_NOT_READY})}_validateAfterLogin(B){const v="login";if(!B)throw new rs({functionName:v,message:"login response is empty"});const{tinyID:N,a2Key:O}=B||{};if(!N)throw new rs({functionName:v,code:Lo.NO_TINYID});if(!O)throw new rs({functionName:v,code:Lo.NO_A2KEY})}_createRepeatLoginResponse(){var B;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:wl({code:"RepeatLogin",replacement1:(B=ye.store.get("login"))===null||B===void 0?void 0:B.userId}),repeatLogin:!0}}}_performLogin(B){return pA(this,void 0,void 0,function*(){const{userID:v,userSig:N}=B;return ye.store.set("login",{userId:v,userSig:N}),this._latestLoginAt=Date.now(),Gu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(B=>{setTimeout(()=>B(null),1)})})}_handleLoginSuccess(B){const{timeManager:v}=ye.common,{helloInterval:N,timeStamp:O,customStatus:z,purchaseBits:X}=B,rA=1e3*O;v.calculateTimeOffsetWithServer(this._latestLoginAt,rA),this._helloInterval=N||120,this._updateLoginStore(B),ye.user.userStatus.setCustomStatus(z),tn.getInstance().executeWorkflow(nr.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:X}),ye.common.taskScheduler.addTask({id:Tu,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(B){return function(v){return pA(this,void 0,void 0,function*(){const{logoutReason:N}=v,O="im_open_status.wslogout",z=ye.common.generateProtocolData({servcmd:O,data:{wslogout_type:N,isWebUniapp:0}}),X=`${z.head.seq}${O}`;return yield ye.channel.sendPacket(z,{requestId:X})})}({logoutReason:B})}_updateLoginStore(B){const{a2Key:v,tinyID:N,instanceID:O,authKey:z}=B;ye.store.set("login",{a2Key:v,tinyID:N,statusInstanceId:O,authKey:z,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return pA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const B="im_open_status.wshello",v=ye.common.generateProtocolData({servcmd:B,data:{isWebUniapp:0}}),N=`${v.head.seq}${B}`;return ye.channel.sendPacket(v,{requestId:N})}()}catch(B){ye.ssoLog.warn("_sendOnlinePresenceRequest",` error:${B.message}`)}})}_isLoginIn(){var B;return((B=ye.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){ye.common.taskScheduler.removeTask(Tu),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",ye.store.clear("login"),ye.store.set("login",{isReady:!1}),ye.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:B}=ye;B.unSubscribeInnerEvent(ui.RECONNECTED,this._reLogin,this),B.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this)}}const Us={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},_c={logout:!0};class Ac{constructor(){this.loginAction=new XI,this.kickedOutHandler=new Sc,this.loginAction.init(),this.kickedOutHandler.init(),Mc({auth:_c,params:Us})}}var dr,Vr,Xa;(function(p){p.CONV_C2C="C2C",p.CONV_GROUP="GROUP",p.CONV_TOPIC="TOPIC",p.CONV_SYSTEM="@TIM#SYSTEM"})(dr||(dr={})),function(p){p.MSG_PRIORITY_HIGH="High",p.MSG_PRIORITY_NORMAL="Normal",p.MSG_PRIORITY_LOW="Low",p.MSG_PRIORITY_LOWEST="Lowest"}(Vr||(Vr={})),function(p){p.MSG_TEXT="TIMTextElem",p.MSG_CUSTOM="TIMCustomElem",p.MSG_LOCATION="TIMLocationElem",p.MSG_FACE="TIMFaceElem",p.MSG_IMAGE="TIMImageElem",p.MSG_AUDIO="TIMSoundElem",p.MSG_FILE="TIMFileElem",p.MSG_VIDEO="TIMVideoFileElem",p.MSG_GRP_TIP="TIMGroupTipElem",p.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",p.MSG_MERGER="TIMRelayElem"}(Xa||(Xa={}));const bE={1:Vr.MSG_PRIORITY_HIGH,2:Vr.MSG_PRIORITY_NORMAL,3:Vr.MSG_PRIORITY_LOW,4:Vr.MSG_PRIORITY_LOWEST},hC=0,ch=1;var ao;(function(p){p.IN="in",p.OUT="out"})(ao||(ao={}));const Tc=2,Gl={};function BC(p){if(!p)return 0;if(Gl[p]===void 0){const B=new Date,v=`3${B.getHours()}`.slice(-2),N=`0${B.getMinutes()}`.slice(-2),O=`0${B.getSeconds()}`.slice(-2);Gl[p]=parseInt([v,N,O,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${Gl[p]}`)}else Gl[p]+=1;return Gl[p]}class QC{constructor(B){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=Vr.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:v=ye.common.timeManager.getServerTimeSeconds()||0,senderTinyID:N,currentUser:O,needReadReceipt:z,isSupportExtension:X,customModerationConfigurationId:rA,to:DA,from:GA,nick:VA="",avatar:ee="",time:Ee,messageControlInfo:We,tinyID:ot,cloudCustomData:at="",messageLifeTime:Ut,messageVersion:Jt=0,conversationType:Ui,sequence:go,checkResult:Xi=0,isPlaceMessage:Ei=0,messageFlagBits:Po,receiverList:es,isSystemMessage:pi=!1,status:ji=wg.SUCCESS,revokeReason:Ws="",conversationSubType:_e,clientSequence:_t,protocol:FA="JSON",revokerInfo:Xt={userID:"",nick:"",avatar:""},readReceiptInfo:En={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Ai,groupProfile:us,atUserList:vi,flow:ho,isRead:ht=!1,priority:Qt=Vr.MSG_PRIORITY_NORMAL,onlineOnlyFlag:ug=!1,nameCard:ks="",quoteInfo:Wi}=B;var Hr;this.clientTime=v,this.senderTinyID=N||ot,this.needReadReceipt=z===!0||z===1,this.isSupportExtension=X===!0||X===1,this._cmConfigID=rA,this.to=DA,this.nick=VA,this.avatar=ee,this.protocol=FA,this.random=Ai===void 0?(Hr=Hr||99999999,Math.round(Math.random()*Hr)):Ai,this.time=Ee||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!We?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!We?.excludedFromUnreadCount,this.isModified=!!Jt,this.cloudCustomData=at,this.messageLifeTime=Ut,this.from=GA||null,this.sequence=go||0,this.conversationType=Ui||dr.CONV_C2C,this.hasRiskContent=Xi>1,this.version=Jt,this.isPlaceMessage=Ei,this.isRevoked=Ei===2||Po===8,this.isSystemMessage=pi,this.readReceiptInfo=En,this.revokeReason=Ws,this.revokerInfo=Xt,this._receiverList=es,this.conversationSubType=_e,this.revoker=Xt?.revoker||"",this.clientSequence=_t||go||0,this.status=ji,this.atUserList=vi||[],this.flow=ho,this.isRead=ht,this.priority=Qt,this._onlineOnlyFlag=ug,this.nameCard=ks,this.quoteInfo=Wi,this.reInitialize(O),this._initC2CReadReceiptInfo(B),this._extractGroupInfo(us)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(B){Array.isArray(B)?this._elements=B:this._elements=[B],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(B=>B.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(B){this._relayFlag=B}validateBeforeSend(){var B,v,N;return this._relayFlag?{isValid:!0}:((B=this._elements)===null||B===void 0?void 0:B.length)>0?(N=(v=this._elements[0])===null||v===void 0?void 0:v.validateBeforeSend)===null||N===void 0?void 0:N.call(v):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(B){const{readReceiptSentByPeer:v,timestamp:N=0}=B;this.conversationType===dr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=v===1,this.readReceiptInfo.timestamp=N)}_extractGroupInfo(B){if(!B)return;const{From_AccountNick:v,From_AccountHeadurl:N,MsgFrom_AccountExtraInfo:O,GroupType:z}=B,{NameCard:X}=O||{};typeof v=="string"&&(this.nick=v),typeof N=="string"&&(this.avatar=N),typeof X=="string"&&(this.nameCard=X),this.conversationSubType=z}reInitialize(B){B===this.from&&(this.isRead=!0),this._initSequence(B),this._concatConversationID(B),this.generateMessageID()}_concatConversationID(B){let v="";const N=this.conversationType;N!==dr.CONV_SYSTEM?(v=N===dr.CONV_C2C?B===this.from?this.to:this.from:this.to,this.conversationID=v?`${N}${v}`:null):this.conversationID=dr.CONV_SYSTEM}_initSequence(B){this.clientSequence===0&&B&&(this.clientSequence=BC(B)),this.sequence===0&&this.conversationType===dr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===dr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(B){this.isRead=B}}class bl{static parseServerPushElement(B){const{MsgContent:v={}}=B,{Data:N,Ext:O,Desc:z}=v;return new bl({data:N,description:z,extension:O})}constructor(B){this.type=Xa.MSG_CUSTOM;const{data:v="",description:N="",extension:O=""}=B;this.content={data:v,description:N,extension:O}}transformToServerFormat(B){const{isMergerMessage:v=!1}=B||{},N=v?this.payload:this.content,{data:O,description:z,extension:X}=N;return{MsgType:this.type,MsgContent:{Data:O,Ext:X,Desc:z}}}validateBeforeSend(){const{isEmpty:B}=ye.utils,v=[this.content.data,this.content.description,this.content.extension].some(N=>!B(N));return{isValid:v,error:v?null:{message:"content can not be empty"}}}}class $I{static parseServerPushElement(B){const{MsgContent:v={Text:""}}=B,{Text:N}=v;return new $I({text:N})}constructor(B){this.type=zg.MSG_TEXT,this.content={text:B.text||""}}validateBeforeSend(){var B,v;return((v=(B=this.content)===null||B===void 0?void 0:B.text)===null||v===void 0?void 0:v.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(B){const{isMergerMessage:v=!1}=B||{},N=v?this.payload:this.content,{text:O}=N;return{MsgType:this.type,MsgContent:{Text:O}}}}var BI=new class{constructor(){this._elementClassMap={[Xa.MSG_CUSTOM]:bl,[Xa.MSG_TEXT]:$I}}init(){js.getInstance().registerApi({apiName:"createCustomMessage",context:this}),js.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(p,B){var v;(v=B).prototype!==void 0&&"constructor"in v.prototype&&(this._elementClassMap[p]=B)}getElementClass(p){return this._elementClassMap[p]}createMessage(p){const{from:B,flow:v=ao.OUT}=p,{userId:N}=ye.store.get("login")||{};this._isSendByCurrentInstance({from:B,flow:v,currentUser:N})?this._updateWithSenderInfo(p):this._isMultiEndpointSyncMessage({from:B,flow:v,currentUser:N})&&(p.flow=ao.OUT);const O=Object.assign(Object.assign({},p),{currentUser:N});return new QC(O)}createCustomMessage(p){const B=qn(),v=this.createMessage(Object.assign(Object.assign({},p),{from:B})),N=this._elementClassMap[Xa.MSG_CUSTOM];if(!v)return null;if(N){const O=new N(p.payload);v.setElement(O)}return v}createTextMessage(p){var B;if(!p)return null;const v=typeof p.payload=="string"?p.payload:((B=p?.payload)===null||B===void 0?void 0:B.text)||"",N=new $I({text:v}),O=qn(),z=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},p),{from:O}));return z.setElement(N),z}_updateWithSenderInfo(p){var B,v;const{nick:N,avatar:O,conversationType:z,to:X}=p,{userId:rA,tinyID:DA}=ye.store.get("login")||{},GA=Aa.getUserProfile(rA);return p.nick=N||GA?.nick||"",p.avatar=O||GA?.avatar||"",p.tinyID=p.tinyID||DA||"",p.from=rA,p.status=wg.UNSENT,p.flow=ao.OUT,z===_g.CONV_GROUP&&(p.nameCard=(v=(B=Za.getGroup(X))===null||B===void 0?void 0:B.selfInfo)===null||v===void 0?void 0:v.nameCard),p}_isMultiEndpointSyncMessage(p){const{from:B,flow:v,currentUser:N}=p;return B===N&&v===ao.IN}_isSendByCurrentInstance(p){const{from:B,flow:v,currentUser:N}=p;return B===N&&v===ao.OUT}};const QI={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},kE={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},kl={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Ll(p,B){return Object.keys(B).forEach(v=>{const{range:N,defaultValue:O}=B[v];p[v]=N.includes(p[v])?p[v]:O}),p}function Ug(p){const B=p.lastIndexOf(".");return B===-1?p:p.slice(0,B)}function ec(p){const{androidInfo:B={},androidOPPOChannelID:v=""}=p,N=B.OPPOChannelID||v,O=Ll(B,kE),{sound:z="",FCMChannelID:X=""}=O,rA=Do(O,["sound","FCMChannelID"]);return Object.assign(Object.assign({},rA),{Sound:Ug(z),OPPOChannelID:N,GoogleChannelID:X})}function md(p){const{apnsInfo:B={},ignoreIOSBadge:v=!1,disableVoipPush:N}=p,O=Ll(B,kl),{ignoreIOSBadge:z,disableVoipPush:X,enableIOSBackgroundNotification:rA}=O,DA=Do(O,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),GA=z===!0||v===!0?1:0;let VA;return r(N)||(VA=N===!1?1:0),r(X)||(VA=X===!1?1:0),Object.assign(Object.assign({},DA),{BadgeMode:GA,IsVoipPush:VA,ContentAvailable:rA?1:0})}function LE(p){return ye.utils.isPlainObject(p)?{PushFlag:p.disablePush===!0?1:0,Title:p.title||"",Desc:p.description||"",Ext:p.extension||"",ApnsInfo:md(p),AndroidInfo:ec(p)}:QI}function Nc(p){const{From_AccountHeadurl:B,From_AccountNick:v,IsNeedReadReceipt:N,IsPeerRead:O,IsSyncMsg:z,MsgBody:X,MsgClientTime:rA,MsgLifeTime:DA,MsgRandom:GA,MsgSeq:VA,MsgTimeStamp:ee,SendMsgControl:Ee,SupportMessageExtension:We,TinyId:ot,MsgCheckResult:at,CloudCustomData:Ut,MsgVersion:Jt,MsgFlagBits:Ui,RevokerInfo:go,InnerSdkCustomData:Xi}=p;let Ei,{From_Account:Po,To_Account:es}=p;if(z===1){const pi=es;es=Po,Po=pi}if(go){const{Reason:pi,Revoker_Account:ji,Revoker_FromUin:Ws}=go;Ei={reason:pi,revoker:ji,revokerFromUin:Ws,userID:ji}}return{from:Po,avatar:B,nick:v,needReadReceipt:N===1,isSyncMessage:z,clientTime:rA,messageLifeTime:DA,random:GA,sequence:VA,time:ee,messageControlInfo:{excludedFromLastMessage:Ee?.NoLastMsg===1,excludedFromUnreadCount:Ee?.NoUnread===1},isSupportExtension:We,to:es,tinyID:ot,checkResult:at,cloudCustomData:Ut,revokerInfo:Ei,messageVersion:Jt,messageFlagBits:Ui,readReceiptSentByPeer:O,elements:$a(X),onlineOnlyFlag:DA===0,quoteInfo:Pu(Xi)}}function Au(p){const{From_Account:B,MsgBody:v,MsgClientTime:N,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,To_Account:rA,MsgVersion:DA,CloudCustomData:GA,MsgCheckResult:VA}=p;return{from:B,clientTime:N,random:O,sequence:z,time:X,to:rA,elements:$a(v),messageVersion:DA,cloudCustomData:GA,checkResult:VA}}function lo(p){const{ClientSeq:B,From_Account:v,GroupInfo:N,MsgBody:O,MsgClientTime:z,MsgRandom:X,MsgSeq:rA,MsgTimeStamp:DA,SendMsgControl:GA,SupportMessageExtension:VA,TinyId:ee,CloudCustomData:Ee,MsgVersion:We,MsgCheckResult:ot,NeedReadReceipt:at,IsPlaceMsg:Ut,RevokerInfo:Jt,GroupAtInfo:Ui,OnlineOnlyFlag:go,InnerSdkCustomData:Xi}=p;let Ei,Po=Vr.MSG_PRIORITY_NORMAL;if(Object.keys(bE).includes(String(p.MsgPriority))&&(Po=bE[p.MsgPriority]),Jt){const{Reason:pi,Revoker_Account:ji,Revoker_FromUin:Ws}=Jt;Ei={reason:pi,revoker:ji,revokerFromUin:Ws,userID:ji}}const es=function(pi){const ji=[];return Array.isArray(pi)&&pi.forEach(Ws=>{Ws.GroupAtAllFlag===hC?ji.push(Ws.GroupAt_Account):Ws.GroupAtAllFlag===ch&&ji.push(hs.MSG_AT_ALL)}),ji}(Ui);return{clientSequence:B,from:v,groupProfile:N,clientTime:z,priority:Po,random:X,sequence:rA,time:DA,messageControlInfo:{excludedFromLastMessage:GA?.NoLastMsg===1,excludedFromUnreadCount:GA?.NoUnread===1},isSupportExtension:VA,tinyID:ee,cloudCustomData:Ee,messageVersion:We,checkResult:ot,needReadReceipt:at,isPlaceMessage:Ut,revokerInfo:Ei,atUserList:es,elements:$a(O),to:UE(p),onlineOnlyFlag:go===1,quoteInfo:Pu(Xi)}}function UE(p){const{utils:{isEmpty:B},constants:{IS_TOPIC_MESSAGE:v}}=ye,{ToGroupId:N,GroupInfo:{MillionGroupFlag:O=0,TopicId:z}={}}=p;return O!==v||B(z)?N:z}function $a(p){if(!p)return null;if(Array.isArray(p))return p.map(v=>{const N=ye.message.messageFactory.getElementClass(v.MsgType);return N?.parseServerPushElement(v)});const B=ye.message.messageFactory.getElementClass(p.MsgType);return B?.parseServerPushElement(p)}function eu(p){const{From_Account:B,MsgBody:v,MsgClientTime:N,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,GroupId:rA,TopicId:DA,MsgVersion:GA,CloudCustomData:VA,MsgCheckResult:ee}=p;return{from:B,clientTime:N,random:O,sequence:z,time:X,groupID:rA,topicID:DA,elements:$a(v),messageVersion:GA,cloudCustomData:VA,checkResult:ee}}function Pu(p){const{utils:{isString:B,safeStringify:v},ssoLog:N}=ye;if(!B(p))return null;try{const{messageID:O,messageTime:z,messageSequence:X}=JSON.parse(p).businessQuote;return{msgID:O,messageTime:z,messageSequence:X}}catch(O){return N.debug("_parseServerQuoteInfo",v(O)),null}}function Gc({conversationUpdateFields:p,message:B}){const{conversationID:v,conversationType:N,conversationSubType:O,flow:z,_isExcludedFromUnreadCount:X,_isExcludedFromLastMessage:rA}=B,DA=rA?"":ol(B),GA=!X&&z===ao.IN;p.has(v)?(p.get(v).lastMessage=DA,GA&&p.get(v).unreadCount++):p.set(v,{conversationID:v,type:N,subType:O,unreadCount:GA?1:0,lastMessage:DA})}function pI(p){return p.filter(B=>{const v=!Rs(B?._elements),N=B?.isPlaceMessage===1;return v||ye.ssoLog.error("emptyMessageBody",`from:${B.from} to:${B.to} sequence:${B.sequence}`),v&&!N})}function sl(p){const{messageDataHandler:B}=ye.message;return!B.isInMessageList(p)&&!B.isMessageSentByCurrentInstance(p)}var nl=Object.freeze({__proto__:null,autoIncrementIndex:BC,createAndroidPushInfo:ec,createApnsPushInfo:md,createOfflinePushInfo:LE,filterValidMessages:pI,getAndroidSoundName:Ug,parseServerGroupMessage:lo,parseServerPushC2CModifyMessage:Au,parseServerPushGroupModifyMessage:eu,parseServerPushMessage:Nc,parseServerPushMessageElement:$a,shouldStoreMessage:sl,updateConversationFields:Gc});const{isPlainObject:xa}=ye.utils;function FE(p,B={}){const{onlineUserOnly:v,messageControlInfo:N}=B;let{offlinePushInfo:O}=B;p.conversationType===dr.CONV_C2C&&v===!0&&(O?O.disablePush=!0:O={disablePush:!0});let z="";typeof p.cloudCustomData=="string"&&p.cloudCustomData.length>0&&(z=p.cloudCustomData);const X=[];if(N&&xa(N)){const{excludedFromUnreadCount:rA,excludedFromLastMessage:DA,excludedFromContentModeration:GA}=N;rA===!0&&X.push("NoUnread"),DA===!0&&X.push("NoLastMsg"),GA===!0&&X.push("NoMsgCheck")}return{onlineUserOnly:v,cloudCustomData:z,messageControlInfo:X,offlinePushInfo:O}}function ra(p){const{webhookInfo:{disableCloudMessagePreHook:B=!1,disableCloudMessagePostHook:v=!1}={}}=p||{};if(!B&&!v)return;const N=[];return B&&N.push("ForbidBeforeSendMsgCallback"),v&&N.push("ForbidAfterSendMsgCallback"),N}function Mn(p,B){return pA(this,void 0,void 0,function*(){const v=p.conversationType===dr.CONV_GROUP?function(O,z){var X;const rA=FE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:VA,offlinePushInfo:ee}=rA,Ee=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));let We;return h(O._receiverList)&&O._receiverList.length>0&&(We=O._receiverList,O._receiverList.length>50&&(We=O._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(X=ye.store.get("login"))===null||X===void 0?void 0:X.userId,GroupId:O.to,MsgBody:Ee,CloudCustomData:GA,Random:O.random,MsgPriority:O.priority,ClientSeq:O.clientSequence,GroupAtInfo:O._groupAtInfoList,OnlineOnlyFlag:DA?1:0,MsgClientTime:O.clientTime,OfflinePushInfo:LE(ee),SendMsgControl:DA?void 0:VA,NeedReadReceipt:O.needReadReceipt===!0?1:0,To_Account:We,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,ForbidCallbackControl:ra(z),InnerSdkCustomData:OE(O)}}}(p,B):function(O,z){var X;const rA=FE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:VA,offlinePushInfo:ee}=rA,Ee=DA===!0?0:void 0,We=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(X=ye.store.get("login"))===null||X===void 0?void 0:X.userId,To_Account:O.to,MsgBody:We,CloudCustomData:GA,MsgSeq:O.sequence,MsgRandom:O.random,MsgLifeTime:Ee,From_AccountNick:O.nick,From_AccountHeadurl:O.avatar,SendMsgControl:Ee!==0?VA:void 0,MsgClientTime:O.clientTime,IsNeedReadReceipt:O.needReadReceipt===!0?1:0,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,OfflinePushInfo:LE(ee),ForbidCallbackControl:ra(z),InnerSdkCustomData:OE(O)}}}(p,B),N=yield Zg(v);return N?{time:N.MsgTime,messageDropReason:N.MsgDropReason,sequence:N.MsgSeq}:null})}function kr(p){return pA(this,void 0,void 0,function*(){const{from:B,to:v,version:N=0,sequence:O,random:z,time:X,type:rA,cloudCustomData:DA}=p,GA={From_Account:B,To_Account:v,MsgVersion:N,MsgSeq:O,MsgRandom:z,MsgTime:X,MsgType:rA,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:DA},VA=yield Zg({servcmd:"openim.modify_c2c_msg",data:GA});if(VA){const{MsgBody:ee,MsgVersion:Ee,CloudCustomData:We}=VA;return{elements:$a(ee),messageVersion:Ee,cloudCustomData:We}}})}function rl(p){return pA(this,void 0,void 0,function*(){const{to:B,version:v=0,sequence:N,cloudCustomData:O}=p,z={GroupId:B,MsgVersion:v,MsgSeq:N,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:O},X=yield Zg({servcmd:"openim.modify_group_msg",data:z});if(X){const{MsgBody:rA,MsgVersion:DA,CloudCustomData:GA}=X;return{elements:$a(rA),messageVersion:DA,cloudCustomData:GA}}})}function Ul(p){return pA(this,void 0,void 0,function*(){const{groupID:B,count:v,messageSequence:N,messageSequenceList:O,getType:z}=p,X={GroupId:B,ReqMsgNumber:v,WithRecalledMsg:1,Version:1,GetType:z};return N&&(X.ReqMsgSeq=N),h(O)&&O.length>0&&(X.ReqMsgSeqList=O),yield Zg({servcmd:"group_open_http_svc.group_msg_get",data:X})})}function bc(p){return pA(this,void 0,void 0,function*(){const{peerAccount:B,count:v,lastMessageTime:N,messageKey:O,direction:z}=p;return Zg({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:v,WithRecalledMsg:1,LastMsgTime:N,MsgKey:O,GetDirection:z}})})}function OE(p){if(ye.utils.isObject(p.quoteInfo)){const{msgID:B,messageSequence:v,messageTime:N}=p.quoteInfo;return JSON.stringify({businessQuote:{messageID:B,messageSequence:v,messageTime:N}})}}var kc=Object.freeze({__proto__:null,createMessagePackOptions:FE,generateForbidCallbackControl:ra,getC2CRoamingMessagesByAnchor:bc,getGroupRoamingMessagesByAnchor:Ul,getRoamingMessages:function(p){return pA(this,void 0,void 0,function*(){const{peerAccount:B,count:v,lastMessageTime:N,messageKey:O}=p;return(yield Zg({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:v||15,LastMsgTime:N||0,MsgKey:O,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:kr,modifyGroupMessage:rl,sendMessage:Mn});const{isPlainObject:xu}=ye.utils,{MSG_AUDIO:pC,MSG_FILE:tu,MSG_IMAGE:lh,MSG_VIDEO:Yu,MSG_MERGER:mI}=hs;class al{constructor(){this._sendProtocolMap=new Map}init(){js.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:B=>![pC,tu,lh,Yu,mI].includes(B[0].type)})}registerSendProtocol(B,v,N){this._sendProtocolMap.set(B,v.bind(N))}sendMessage(B,v){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:N,SEND_COST:O,SUCCESS_COUNT:z,FAILED_COUNT:X}=cI;if(!(B instanceof QC))throw new rs({code:Lo.MSG_INSTANCE_REQUIRED});const rA=B.validateBeforeSend();if(!rA.isValid){const{code:VA,message:ee=""}=rA.error||{};throw new rs({code:VA,message:ee})}this._reportMessageSendQuality({name:N,message:B});let DA=!1;const{messageDataHandler:GA}=ye.message||{};try{const{messageControlInfo:VA}=v||{};let ee=null;GA.addRandomOfSentMessage(B.random);const Ee=Date.now(),We=this._getSendProtocol(B);if(B.conversationType===dr.CONV_C2C?(DA=v?.onlineUserOnly===!0,ee=yield We(B,v)):B.conversationType===dr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(B),ee=yield We(B,v)),ee){const{messageDropReason:ot,sequence:at,time:Ut}=ee;if(this._updateNickAndAvatarOfSentMessageByMe(B),ot&&this._logRateLimitInfo(B,at,ot),this._reportMessageSendQuality({name:z,message:B}),this._reportMessageSendQuality({name:O,message:B,startTs:Ee}),B.isResend===!0){const Jt=GA.findMessage(B.ID);Jt&&(ye.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${Jt.ID}`),GA.deleteConversationMessage(Jt))}return B.status=wg.SUCCESS,B.time=Ut,B.conversationType===dr.CONV_GROUP&&(B.sequence=at),DA?B._onlineOnlyFlag=!0:(GA.storeConversationMessage(B),this._applySentMessageControlInfo(B,VA),this._emitOnlineMessageSent(B)),B.type===zg.MSG_STREAM?{code:0,data:{message:B,streamMessageID:ee.streamMessageID}}:{code:0,data:{message:B}}}}catch(VA){B.status=wg.FAIL,GA.removeRandomOfSentMessage(B.random);let{errorCode:ee}=VA||{},Ee=VA?.errorInfo||VA?.message||"";throw this._hasRiskContent(ee)&&(B.hasRiskContent=!0),DA||this._isRejectedByRestApi(ee)||GA.storeConversationMessage(B),this._reportMessageSendQuality({name:X,message:B,error:VA}),new rs({code:ee,message:Ee,data:{message:B},moreMessage:`type:${B.type} from:${B.from} to:${B.to}`})}})}_hasRiskContent(B){return B===80001||B===80004}_isRejectedByRestApi(B){return B>=10100&&B<=10200||B>=120001&&B<=13e4}_emitOnlineMessageSent(B){const v=B._isExcludedFromLastMessage?"":B,{conversationID:N,conversationType:O}=B,z=Xr(N)?ui.TOPIC_NEW_MESSAGE:ui.NEW_MESSAGE;ye.notificationCenter.emitInnerEvent(z,{result:{conversationUpdateFieldList:[{conversationID:N,type:O,message:B,lastMessage:v,unreadCount:0}]}})}_applySentMessageControlInfo(B,v){v&&xu(v)&&(v.excludedFromLastMessage===!0&&(B._isExcludedFromLastMessage=!0),v.excludedFromUnreadCount===!0&&(B._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(B,v,N){const O=`from:${B.from} to:${B.to} sequence:${v} messageDropReason:${N}`;ye.ssoLog.warn("messageDropReason",O)}_updateNickAndAvatarOfSentMessageByMe(B){const{messageDataHandler:v}=ye.message||{};let N=!1;const{conversationID:O}=B,z=v.getLatestMsgSentByMe(O);if(z){const{nick:X,avatar:rA}=z;X===B.nick&&rA===B.avatar||(N=!0),N&&v.updateNickAndAvatarOfSentMessage({conversationID:O,latestNick:B.nick,latestAvatar:B.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(B){return pA(this,void 0,void 0,function*(){var v,N,O;const{to:z,from:X}=B;let rA=z,DA=Za.getGroup(rA);if(Ca({groupID:rA})&&DA?.isSupportTopic)throw new rs({code:Lo.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(Xr(z)&&([rA]=z.split(La.TOPIC),DA=Za.getGroup(rA)),!DA&&typeof((v=js.getInstance().getApiMap())===null||v===void 0?void 0:v.getGroupProfile)=="function"){const GA=yield js.getInstance().getApiMap().getGroupProfile({groupID:rA});if(((O=(N=GA?.data)===null||N===void 0?void 0:N.group)===null||O===void 0?void 0:O.type)===hs.GRP_AVCHATROOM){const VA=wl({code:Lo.MSG_SEND_FAIL_NOT_IN_AV,replacement1:X,replacement2:rA});throw new rs({code:Lo.MSG_SEND_FAIL_NOT_IN_AV,message:VA})}}return!0})}_reportMessageSendQuality(B){ye.notificationCenter.emitInnerEvent(ui.QUALITY_STAT,{label:Ng.MESSAGE_SEND_SUCCESS_RATE,data:B})}_getSendProtocol(B){return this._sendProtocolMap.get(B.type)||Mn}}var mC=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){ye.notificationCenter.subscribeInnerEvent(ui.LOGOUT,this._reset,this),ye.notificationCenter.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}get _messagesByConversation(){return Nl.getMessages()}storeConversationMessage(p,B=!1){if(an)return!0;const{conversationID:v}=p;if(!v||(this._messagesByConversation.has(v)||this._messagesByConversation.set(v,new Map),this._shouldSkipStoreMessage(p,B)))return!1;const N=this._getUniqueIdOfMessage(p);return this._messagesByConversation.get(v).set(N,p),this._updateLatestMessageMap(p),!0}_updateLatestMessageMap(p){const{conversationID:B}=p;p.flow==="out"?this._setLatestMsgSentByMe(B,p):B.startsWith("C2C")&&this._setLatestMsgSentByPeer(B,p)}_shouldSkipStoreMessage(p,B){const v=this._getUniqueIdOfMessage(p),N=this._messagesByConversation.get(p.conversationID);if(N?.has(v)){const O=N?.get(v);if(!B||O?.isModified===!0)return!0}return!1}deleteConversationMessage(p){var B;const{conversationID:v=""}=p,N=this._getUniqueIdOfMessage(p);this._messagesByConversation.has(v)&&((B=this._messagesByConversation.get(v))===null||B===void 0||B.delete(N))}modifyConversationMessage(p,B){var v;if(!this._messagesByConversation.has(p)&&!this._sparseMessagesByConversation.has(p))return{isUpdated:!1,message:null};const N=this._getUniqueIdOfMessage(B),O=this._getMessageFromLocalMessage(p,N);if(O){const{messageVersion:z,elements:X,cloudCustomData:rA,checkResult:DA=0}=B,GA=DA>1;if(ye.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${O.version} remoteVersion:${z}`),O.versionO.ID===p)||null,B)break;if(!B){const N=Array.from(this._sparseMessagesByConversation.values());for(const O of N)if(B=O.get(p)||null,B)break}return B}deleteConversationMessageList(p){this._messagesByConversation.has(p)&&(this._messagesByConversation.delete(p),this._latestMessageSentByMeMap.delete(p),this._latestMessageSentByPeerMap.delete(p)),this._sparseMessagesByConversation.has(p)&&this._sparseMessagesByConversation.delete(p)}revokeMessage({conversationID:p,sequence:B,random:v,revoker:N}){const O=this._messagesByConversation.get(p);let z=null;if(O){const X=Array.from(O.values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:B}),z){const rA=this._getUniqueIdOfMessage(z);return Nl.updateMessage(p,[rA],{isRevoked:!0,revoker:N,operation:Yr.revoke}),z}}if(this._sparseMessagesByConversation.has(p)){const X=Array.from(this._sparseMessagesByConversation.get(p).values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:B}),z)return z.isRevoked=!0,z.revoker=N,z}}_findMessageBySequenceAndRandom({messageList:p,sequence:B,random:v}){for(let N=0;N0){const X=new Map([...O,...z.entries()]);this._messagesByConversation.set(v,X),this._updateLatestMessageSentByMe(v),this._updateLatestMessageSentByPeer(v)}return N}storeSparseMessageList(p){if(p.length===0)return;const{conversationID:B}=p[0],v=p.length;this._sparseMessagesByConversation.has(B)||this._sparseMessagesByConversation.set(B,new Map);const N=this._sparseMessagesByConversation.get(B);for(let O=0;O=0;N--)if(v[N].flow==="out"){this._setLatestMsgSentByMe(p,v[N]);break}}}_updateLatestMessageSentByPeer(p){var B;const v=Array.from(((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]);if(v.length!==0&&p.startsWith("C2C")){for(let N=v.length-1;N>=0;N--)if(v[N].flow==="in"){this._setLatestMsgSentByPeer(p,v[N]);break}}}_getUniqueIdOfMessage(p){const{from:B,to:v,random:N,sequence:O,time:z}=p;return`${B}-${v}-${N}-${O}-${z}`}_setLatestMsgSentByPeer(p,B){this._latestMessageSentByPeerMap.set(p,B)}_setLatestMsgSentByMe(p,B){this._latestMessageSentByMeMap.set(p,B)}getLatestMsgSentByPeer(p){return this._latestMessageSentByPeerMap.get(p)}getLatestMsgSentByMe(p){return this._latestMessageSentByMeMap.get(p)}addRandomOfSentMessage(p){this._randomOfSentMessageList.add(p)}removeRandomOfSentMessage(p){this._randomOfSentMessageList.delete(p)}updateNickAndAvatarOfSentMessage(p){const{conversationID:B="",latestAvatar:v,latestNick:N,isSentByMe:O=!0}=p,z=this._messagesByConversation.get(B);if(!z)return;const X=Array.from(z.values()),rA=O?"out":"in";X.forEach(DA=>{const{nick:GA,avatar:VA,flow:ee}=DA;ee===rA&&(GA!==N&&(DA.nick=N),VA!==v&&(DA.avatar=v))})}isInMessageList(p){var B;const{conversationID:v}=p;if(!v||!this._messagesByConversation.has(v))return!1;const N=this._getUniqueIdOfMessage(p);return(B=this._messagesByConversation.get(v))===null||B===void 0?void 0:B.has(N)}isMessageSentByCurrentInstance(p){const{random:B}=p;return this._randomOfSentMessageList.has(B)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(p){const B=this._messagesByConversation.get(p);return B?[...B.values()]:[]}getSparseMessageList(p){const B=this._sparseMessagesByConversation.get(p);return B?[...B.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),ye.notificationCenter.unSubscribeInnerEvent(ui.LOGOUT,this._reset,this),ye.notificationCenter.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this)}};function aa(p,B){const v=$g.getConversation(p);if(v?.lastMessage){const{lastMessage:N}=v,{lastTime:O,lastSequence:z,version:X}=N,{time:rA,sequence:DA,messageVersion:GA,elements:VA,cloudCustomData:ee}=B;O===rA&&z===DA&&X!==GA&&(N.type=VA[0].type,N.payload=VA[0].content,N.messageForShow=jI(N.type,N.payload),N.cloudCustomData=ee,N.version=GA,$g.updateConversation(p,{lastMessage:N}))}}class tc{init(){js.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(B){return pA(this,void 0,void 0,function*(){const{to:v,payload:N,sequence:O,conversationType:z,random:X,time:rA,from:DA,type:GA}=B;if(this._canModifyMessageElement(GA)){const VA=B?._elements||[];VA.length>=1&&(VA[0].type=GA,VA[0].content=N)}try{let VA=null,ee=null;if(z===dr.CONV_C2C?VA=yield kr(B):z===dr.CONV_GROUP&&(VA=yield rl(B)),VA){let Ee=`${z}${v}`;return v===qn()&&z===dr.CONV_C2C&&(Ee=`${z}${DA}`),ee={conversationType:z,from:DA,to:v,time:rA,random:X,sequence:O,elements:VA?.elements,cloudCustomData:VA?.cloudCustomData,messageVersion:VA?.messageVersion,conversationID:Ee},this._handleModifyMessageSuccess(ee),{code:0,data:{message:B},successLog:{message:`to:${v}`}}}}catch(VA){const{errorCode:ee}=VA||{};throw new rs({functionName:"modifyMessage",code:ee,moreMessage:`to:${v}`})}})}_handleModifyMessageSuccess(B){const{conversationID:v}=B,{isUpdated:N,message:O}=ye.message.messageDataHandler.modifyConversationMessage(v,B);N===!0&&ye.notificationCenter.emitOuterEvent(Dn.MESSAGE_MODIFIED,{name:Dn.MESSAGE_MODIFIED,data:[O]}),ye.notificationCenter.emitInnerEvent(ui.MESSAGE_MODIFIED,{conversationID:v,message:O}),aa(v,B)}_canModifyMessageElement(B){return[Xa.MSG_TEXT,Xa.MSG_CUSTOM,Xa.MSG_LOCATION,Xa.MSG_FACE].includes(B)}}class lg{init(){const{notificationCenter:B}=ye,{InnerEventSubType:v}=B;tn.getInstance().registerWorkflowStep(nr.RECEIVE_C2C_NEW_MESSAGE,Vt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),tn.getInstance().registerWorkflowStep(nr.RECEIVE_C2C_NEW_MESSAGE,Vt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),tn.getInstance().registerWorkflowStep(nr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Vt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),B.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){tn.getInstance().executeWorkflow(nr.RECEIVE_C2C_NEW_MESSAGE,B)}_handleC2CMessagePush(B){const v=B.data||{},{messageDataHandler:N}=ye.message||{},O=[],z=new Map;return v.C2cMsgArray.forEach(X=>{const rA=this._generateC2CMessage(X);this._updateMessageProfile(rA);let DA=rA.isModified===1;N.isMessageSentByCurrentInstance(rA)?rA.isModified=DA:DA=!1,rA._onlineOnlyFlag?N.isMessageSentByCurrentInstance(rA)||O.push(rA):sl(rA)&&(N.storeConversationMessage(rA)&&Gc({conversationUpdateFields:z,message:rA}),N.isMessageSentByCurrentInstance(rA)&&!DA||O.push(rA))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEventsAfterReceiveNewMessage(B){var v;const{messages:N=[]}=((v=B.result)===null||v===void 0?void 0:v[Vt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(N)}_emitMessageEventsAfterSyncUnreadMessage(B){var v;const{messages:N=[]}=((v=B.result)===null||v===void 0?void 0:v[Vt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(N)}_emitMessageEvents(B){const v=B?.filter(O=>O?.isModified===!0)||[];v.length>0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:v});const N=B?.filter(O=>!O?.isModified);N.length>0&&ye.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:N})}_generateC2CMessage(B){const v=dr.CONV_C2C,N=Nc(B),O=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:ao.IN})),{elements:z}=N;return O.setElement(z),O}_updateMessageProfile(B){var v;const{messageDataHandler:N}=ye.message||{},O=(v=ye.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA=""}=B;if(z!==O){const GA=N.getLatestMsgSentByPeer(DA);if(GA){const{nick:VA,avatar:ee}=GA;r(X)||r(rA)?(B.nick=l(VA)?VA:B.nick,B.avatar=l(ee)?ee:B.avatar):X===VA&&rA===ee||(N.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:DA,nick:X,avatar:rA}))}}else{const GA=N.getLatestMsgSentByMe(DA);!GA||X===GA.nick&&rA===GA.avatar||N.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!0})}}_updateConversationUserProfile(B){const{conversationID:v,nick:N,avatar:O}=B,z=$g.getConversation(v),{userProfile:X={}}=z||{};X.avatar===O&&X.nick===N||$g.updateConversation(v,{userProfile:Object.assign(Object.assign({},X),{nick:N,avatar:O})})}_updateMessageListDueToModify(B){const{conversationID:v}=B,{isUpdated:N,message:O}=ye.message.messageDataHandler.modifyConversationMessage(v,B);N===!0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),ye.notificationCenter.emitInnerEvent("ModifyMessageSuccess",B),aa(v,B)}_handleC2CMessageModify(B){B.C2cMsgModNotifys.forEach(v=>{var N;const O=dr.CONV_C2C;let z=Au(v);const{to:X,from:rA}=z;let DA=`${O}${X}`;X===((N=ye.store.get("login"))===null||N===void 0?void 0:N.userId)&&(DA=`${O}${rA}`),z=Object.assign({conversationType:O,conversationID:DA},z),this._updateMessageListDueToModify(z)})}_dispose(){const{notificationCenter:B}=ye,{InnerEventSubType:v}=B;ye.notificationCenter.unSubscribeInnerEvent(ui.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),ye.notificationCenter.unSubscribeInnerEvent(ui.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),ye.notificationCenter.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this)}}class fI{init(){const{notificationCenter:B}=ye,{InnerEventSubType:v}=B;tn.getInstance().registerWorkflowStep(nr.RECEIVE_GROUP_NEW_MESSAGE,Vt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),tn.getInstance().registerWorkflowStep(nr.RECEIVE_GROUP_NEW_MESSAGE,Vt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,v.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,v.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),B.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){this._canExecuteReceiverNewMessageWorkFlow(B)&&tn.getInstance().executeWorkflow(nr.RECEIVE_GROUP_NEW_MESSAGE,B)}_handleGroupMessagePush(B){const v=B.data||{},{messageDataHandler:N}=ye.message,O=[],z=new Map,X=v?.GroupMsgArray;return X?.forEach(rA=>{if(rA.GroupInfo.NotVisible===1)return;const DA=this._generateGroupMessage(rA);this.updateMessageProfile(DA);let GA=DA.isModified===1;N.isMessageSentByCurrentInstance(DA)?DA.isModified=GA:GA=!1,DA._onlineOnlyFlag?N.isMessageSentByCurrentInstance(DA)||O.push(DA):sl(DA)&&N.storeConversationMessage(DA)&&(O.push(DA),Gc({conversationUpdateFields:z,message:DA}))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEvents(B){var v;const{messages:N}=((v=B.result)===null||v===void 0?void 0:v[Vt.HANDLE_GROUP_NEW_MESSAGE])||{},O=N?.filter(X=>X?.isModified===!0)||[];O.length>0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:O});const z=N?.filter(X=>!X?.isModified)||[];z.length>0&&ye.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:z})}_generateGroupMessage(B){const v=dr.CONV_GROUP,N=lo(B),O=ye.message.messageFactory.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:ao.IN})),{elements:z}=N;return O.setElement(z),O}updateMessageProfile(B){var v;const{messageDataHandler:N}=ye.message||{},O=(v=ye.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA="",_elements:GA}=B;if(z===O){const VA=N.getLatestMsgSentByMe(DA);!VA||X===VA.nick&&rA===VA.avatar||N.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!0})}else if(z===hs.CONV_SYSTEM){const{operationType:VA,memberInfoList:ee,operatorInfo:Ee}=GA;let We={};if(Rs(ee)?Rs(Ee)||(We=Ee):[sa.JOINED,sa.KICKED,sa.ADMIN_SET,sa.ADMIN_CANCELED].includes(VA)&&(We=Object.assign({},ee[0])),!Rs(We)){const{nick:ot="",avatar:at=""}=We;B.nick=ot,B.avatar=at}}}_updateMessageListDueToModify(B){const{conversationID:v}=B,{isUpdated:N,message:O}=ye.message.messageDataHandler.modifyConversationMessage(v,B);N===!0&&ye.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),aa(v,B)}_handleGroupMessageModify(B){B.GroupMsgModNotifys.forEach(v=>{const N=dr.CONV_GROUP;let O=eu(v);const{topicID:z,groupID:X}=O,rA=z||X,DA=`${N}${rA}`;O=Object.assign({conversationType:N,conversationID:DA,to:rA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:B}=ye,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:v,GROUP_MESSAGE_MODIFIED:N}}=B;B.unSubscribeInnerEvent(ui.MESSAGE_PUSH,v,this._handleGroupMessagePush,this),B.unSubscribeInnerEvent(ui.MESSAGE_PUSH,N,this._handleGroupMessageModify,this),B.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(B){var v,N;const{GroupId:O,GroupType:z}=((N=(v=B?.GroupMsgArray)===null||v===void 0?void 0:v[0])===null||N===void 0?void 0:N.GroupInfo)||{},X=z===ME.GRP_AVCHATROOM;return!(!Za.getGroup(O)&&X)}}var PE=new class{constructor(){this.c2cMessageReceiver=new lg,this.groupMessageReceiver=new fI}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Vu={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:p=>!(!p.startsWith("C2C")&&!p.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:p=>function(B){var v;return typeof B?.text!="string"||typeof B.text=="string"&&((v=B?.text)===null||v===void 0?void 0:v.length)===0?"payload.text must be a string":!0}(p)}}},Ju={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var yI=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(p){return pA(this,void 0,void 0,function*(){try{const{conversationID:B,count:v,direction:N,sequence:O,messageSequenceList:z,shouldMarkCompleted:X=!1,getType:rA}=p,DA=B.replace(_g.CONV_GROUP,""),GA=[];let VA=O;if(N===yc.BACKWARD){if(typeof O!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};VA=O+v-1}const ee=yield Ul({groupID:DA,count:v,messageSequence:VA,messageSequenceList:z,getType:rA});if(ee){const{RspMsgList:Ee=[],NextReqMsgSeq:We=0,IsFinished:ot,InvisibleMsgSeq:at}=ee,Ut=`groupID:${DA} sequence:${O} reqSeq:${VA} direction:${N} complete:${ot} nextSequence:${We} remoteMsgCount:${Ee.length} invisibleSequenceList:${at}`,Jt=[];for(let Xi=0;Xi=O),Ui&&X&&this.completedHistoryConversations.add(B);const go=pI(Jt);return ye.ssoLog.info("getGroupRoamingMessagesByAnchor",Ut),{messageList:go,invisibleSequenceList:at,nextReqMessageIDFromServer:We,hasNoMoreHistoryMessage:Ui,serverGroupTipList:GA}}}catch(B){const{errorCode:v,errorInfo:N}=B||{};throw new rs({code:v,message:N})}})}clearHistoryMessageListFetchAnchors(p){this._historyMessageListFetchAnchors.delete(p)}isHistoryMessageFetchCompleted(p){return this.completedHistoryConversations.has(p)}_parseMessage(p){var B;const v=_g.CONV_GROUP;p.Event===4&&(p.MsgBody.MsgType=hs.MSG_GRP_TIP);const N=lo(p),O=BI.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:"in"}));return wc(((B=N.elements)===null||B===void 0?void 0:B.content)||{},O),O.setElement(N.elements),O}getC2CRoamingMessagesByAnchor(p){return pA(this,void 0,void 0,function*(){var B;try{const{conversationID:v,count:N,messageID:O,time:z,direction:X,shouldMarkCompleted:rA=!1}=p;let DA=z,GA="";if(!z){const Ee=O?ye.message.messageDataHandler.findMessage(O):null;if(DA=Ee?.time||0,O&&this._historyMessageListFetchAnchors.has(v)){const We=this._historyMessageListFetchAnchors.get(v);DA=We.lastMessageTime,GA=We.messageKey}}const VA=v.replace(_g.CONV_C2C,""),ee=yield bc({count:N,lastMessageTime:DA,messageKey:GA,peerAccount:VA,direction:X});if(ee){const{MsgList:Ee=[],Complete:We,MsgKey:ot,LastMsgTime:at}=ee;this._historyMessageListFetchAnchors.set(v,{messageKey:ot,lastMessageTime:at});const Ut=[];for(let Xi=0;Xi{const{tag:O,value:z}=N;O&&O.indexOf(Ig)>-1?v.profileCustomField.push({key:O,value:z}):Fl.has(O)&&(v[Fl.get(O)]=z)}),Object.assign(Object.assign({},Ya),v)}parseProfileItem(p=[]){const B=[];return p.forEach(v=>{B.push({tag:v.Tag,value:v.Value})}),B}parseProfileList(p=[]){const B=[];return p.forEach(v=>{B.push({tag:v.Tag,value:v.ValueBytes})}),B}convertParamsToProfile(p){const B=[];return Object.keys(p).forEach(v=>{v!==ar&&B.push({tag:Ur[v.toUpperCase()],value:p[v]})}),p.profileCustomField&&h(p.profileCustomField)&&p.profileCustomField.forEach(v=>{B.push({tag:v.key,value:v.value})}),B}normalizeProfileFields(p){const B={},v=[];return p.forEach(N=>{const{tag:O,value:z}=N;if(O&&O.indexOf(Ig)>-1&&v.push({key:O,value:z}),Fl.has(O)&&z!==void 0){const X=Fl.get(O);B[X]=z}}),v.length>0&&(B.profileCustomField=v),B}};const{generateProtocolData:DI}=ye.common;function iu(p){return pA(this,void 0,void 0,function*(){const B="profile.portrait_get_all",v={From_Account:qn(),UserItem:[]};p.forEach(X=>{v.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:X})});const N=DI({servcmd:B,data:v}),O=`${N.head.seq}${B}`,z=yield ye.channel.sendPacket(N,{requestId:O});if(z)return function(X){const{ActionStatus:rA,ErrorCode:DA,ErrorDisplay:GA,ErrorInfo:VA,UserProfileItem:ee}=X,Ee=[];return ee.map(We=>{const{To_Account:ot,CustomSequence:at,ResultCode:Ut,ResultInfo:Jt,StandardSequence:Ui,ProfileItem:go}=We,Xi=ha.parseProfileItem(go);Ee.push({userId:ot,customSequence:at,resultCode:Ut,resultInfo:Jt,standardSequence:Ui,profileItem:Xi})}),{actionStatus:rA,errorCode:DA,errorDisplay:GA,errorInfo:VA,userProfile:Ee}}(z)})}function Ba(p){return Aa.getFriendMap().has(p)}const{isEmpty:cl}=ye.utils;class xE{constructor(){this._strangerProfileMap=new Map}init(){js.getInstance().registerApi({apiName:"getMyProfile",context:this}),js.getInstance().registerApi({apiName:"getUserProfile",context:this}),js.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=ha.createProfile.bind(ha);const{notificationCenter:B}=ye;tn.getInstance().registerWorkflowStep(nr.SYNC_SERVER_INFO_AFTER_LOGIN,Vt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.subscribeInnerEvent(ui.LOGOUT,this._reset,this),B.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const B=qn(),v=yield iu([B]);if(v){const N=this._handleProfileFormResponse(v)[0];return Aa.getUserProfileMap().set(B,N),{code:0,data:N}}}catch(B){const{errorCode:v,errorInfo:N}=B;throw new rs({functionName:"getMyProfile",code:v,message:N})}})}getUserProfile(B){return pA(this,void 0,void 0,function*(){try{let{userIDList:v}=B;const{userIdListToRequest:N,profileFromCache:O}=this._filterRequestAndCacheUsers(v);if(N.length===0)return{code:0,data:O,successLog:{message:`userIDList.length:${v.length}`}};N.length>Fg&&(ye.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),N.length=Fg);const{data:z,error:X}=yield this._batchFetchUserProfiles(N),rA=N.length,DA=z.length,GA=rA-DA;if(O.length===0&&rA===GA&&!cl(X))throw X;if(h(z))return z.forEach(ee=>{Ba(ee.userID)?Aa.getUserProfileMap().set(ee.userID,ee):this._strangerProfileMap.set(ee.userID,ee)}),{code:0,data:z.concat(O),successLog:{message:`getUserProfile query:${rA} success:${DA} fail:${GA} from cache:${O.length}`}}}catch(v){throw new rs(v)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const B=qn(),v=Aa.getUserProfileMap().has(B);return v?{code:0,data:v}:this.getMyProfile()})}updateMyProfile(B){return pA(this,void 0,void 0,function*(){const v=qn(),N={};for(const z in B)B[z]!==void 0&&(N[z]=B[z]);const O=ha.convertParamsToProfile(N);try{yield function(GA){return pA(this,void 0,void 0,function*(){const VA="profile.portrait_set",ee=DI({servcmd:VA,data:GA}),Ee=`${ee.head.seq}${VA}`,We=yield ye.channel.sendPacket(ee,{requestId:Ee});if(We){const{ActionStatus:ot,ErrorCode:at,ErrorDisplay:Ut,ErrorInfo:Jt}=We;return{actionStatus:ot,errorCode:at,errorDisplay:Ut,errorInfo:Jt}}})}({From_Account:v,ProfileItem:O});const X=Aa.getUserProfile(v);let rA;rA=X?Object.assign(Object.assign({},X),N):ha.createProfile(v,O);const DA=!vg(X,rA,["lastUpdatedTime"]);return rA.lastUpdatedTime=Date.now(),Aa.getUserProfileMap().set(v,rA),DA&&this._emitProfileUpdated(rA),{code:0,data:rA,successLog:{message:`profileArray: ${ye.utils.safeStringify(O)}`}}}catch(z){const{errorCode:X,errorInfo:rA}=z;throw new rs({functionName:"updateMyProfile",code:X,message:rA,moreMessage:`params: ${ye.utils.safeStringify(B)}`})}})}updateMyNickAndAvatar(B){return pA(this,void 0,void 0,function*(){const v=qn(),N=Date.now(),O=Aa.getUserProfile(v);let z={};z=O?Object.assign(O,B):ha.createProfile(v,B),z.lastUpdatedTime=N,Aa.getUserProfileMap().set(v,z)})}_onProfileDataModify(B){const v=function(z){const{Profile_Account:X,PushType:rA,ProfileList:DA}=z;return{userId:X,pushType:rA,profileList:ha.parseProfileList(DA)}}(B.ProfileDataMod[0]);if(cl(v))return;const{isProfileUpdated:N,profile:O}=this._handleProfileModified(v);N&&this._emitProfileUpdated(O)}_emitProfileUpdated(B){ye.notificationCenter.emitInnerEvent(ui.PROFILE_UPDATE,{name:ui.PROFILE_UPDATE,data:[B]}),ye.notificationCenter.emitOuterEvent(Dn.PROFILE_UPDATED,{name:Dn.PROFILE_UPDATED,data:[B]}),$g.updateConversation(`C2C${B?.userID}`,{userProfile:B})}_dispose(){const{notificationCenter:B}=ye;B.unSubscribeInnerEvent(ui.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(ui.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(B){const{userId:v,profileList:N}=B,O=Aa.getUserProfile(v);if(!(qn()===v||Ba(v)&&O))return{isProfileUpdated:!1,profile:null};const z=ha.normalizeProfileFields(N),X=Object.keys(z).some(VA=>VA===ar?this._isCustomFieldChanged(O.profileCustomField,z.profileCustomField):O[VA]!==z[VA]);if(!X)return{isProfileUpdated:!1,profile:O};const rA=Date.now(),DA=Object.prototype.hasOwnProperty.call(z,ar)?this._mergeProfileCustomField(O.profileCustomField,z.profileCustomField):O.profileCustomField,GA=Object.assign(Object.assign(Object.assign({},O),z),{profileCustomField:DA,lastUpdatedTime:rA});return Aa.getUserProfileMap().set(v,GA),{isProfileUpdated:X,profile:GA}}_filterRequestAndCacheUsers(B){const v=[],N=[];return B.forEach(O=>{const z=Aa.getUserProfileMap().has(O);Ba(O)&&z?N.push(Aa.getUserProfile(O)):this._isStrangerAndProfileValid(O)?N.push(this._strangerProfileMap.get(O)):v.push(O)}),{userIdListToRequest:v,profileFromCache:N}}_handleProfileFormResponse(B){const{userProfile:v}=B;if(!Array.isArray(v))return[];const N=v.filter(z=>z.userId!=="@TLS#NOT_FOUND"&&z.userId!==""&&!cl(z.profileItem)),O=Date.now();return N.map(z=>{const X=ha.createProfile(z.userId,z.profileItem);return X.lastUpdatedTime=O,X})}_isStrangerAndProfileValid(B){var v;if(!Ba(B)){const{lastUpdatedTime:N=0}=this._strangerProfileMap.get(B)||{},O=((v=ye.store.get("cloudConfig"))===null||v===void 0?void 0:v.stranger_profile_expiration_time)||6e5;return Date.now()-N<=O}return!1}_chunkUserIDList(B,v){return Array.from({length:Math.ceil(B.length/v)},(N,O)=>B.slice(O*v,(O+1)*v))}_batchFetchUserProfiles(B){return pA(this,void 0,void 0,function*(){const v=[],N=[];let O={};return this._chunkUserIDList(B,100).forEach(z=>{v.push(iu(z))}),(yield Promise.allSettled(v)).forEach(z=>{if(z.status==="fulfilled"){const X=z.value,rA=this._handleProfileFormResponse(X);h(rA)&&N.push(...rA)}else if(z.status==="rejected"){const{code:X,message:rA}=z.reason||{};O={errorCode:X,message:rA}}}),{data:N,error:O}})}_isCustomFieldChanged(B=[],v=[]){if(!h(v)||v.length===0)return!1;if(!h(B)||B.length===0)return!0;const N=new Map(B.map(O=>[O.key,O.value]));return v.some(O=>N.get(O.key)!==O.value)}_mergeProfileCustomField(B=[],v=[]){const N=h(B)?B.map(O=>Object.assign({},O)):[];return h(v)&&v.length!==0&&v.forEach(({key:O,value:z})=>{const X=N.find(rA=>rA.key===O);X?X.value=z:N.push({key:O,value:z})}),N}_reset(){Aa.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const ou=new Map,YE=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let p=0,B=YE.length;p>(-2*z&6)):0)O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(O);try{return decodeURIComponent(escape(v))}catch(N){return console.warn(N),""}}const{isEmpty:su}=ye.utils,{generateProtocolData:Pt}=ye.common;function Hu(p){return pA(this,void 0,void 0,function*(){const B="im_open_status.ws_get_user_status",v=Pt({servcmd:B,data:{To_Account:p}}),N=`${v.head.seq}${B}`,O=yield ye.channel.sendPacket(v,{requestId:N});if(O)return function(z){const{ErrorCode:X,ErrorInfo:rA,ErrorList:DA=[],UserStatusList:GA=[]}=z,VA=GA.map(Ee=>{const{To_Account:We,Status:ot,CustomStatus:at,Detail:Ut=[]}=Ee;return{userID:We,statusType:ot,customStatus:Jr(at),onlineDevices:qu(Ut)}}),ee=DA.map(Ee=>{const{To_Account:We,Invalid_Account:ot,ErrorCode:at,ErrorInfo:Ut}=Ee;return{userID:su(ot)?We:ot,code:at,message:Ut}});return{errorCode:X,errorInfo:rA,successUserList:VA,failureUserList:ee}}(O)})}function qu(p){const B=[];return p?.forEach(v=>{const{Platform:N,Status:O}=v;O==="Online"&&B.push(N)}),B}class fC{constructor(){this._customStatus=""}init(){const{notificationCenter:B}=ye;js.getInstance().registerApi({apiName:"getUserStatus",context:this}),js.getInstance().registerApi({apiName:"setSelfStatus",context:this}),js.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),js.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),tn.getInstance().registerWorkflowStep(nr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Vt.USER_STATUS_UPDATE,this._onReOnline,this),B.subscribeInnerEvent(ui.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.subscribeInnerEvent(ui.LOGOUT,this._reset,this),B.subscribeInnerEvent(ui.DESTROY,this._dispose,this)}setSelfStatus(B){return pA(this,void 0,void 0,function*(){const v=qn(),{customStatus:N}=B;try{return yield function(O){return pA(this,void 0,void 0,function*(){const z="im_open_status.ws_set_custom_status",X=Pt({servcmd:z,data:{CustomStatus:O}}),rA=`${X.head.seq}${z}`,DA=yield ye.channel.sendPacket(X,{requestId:rA});if(DA){const{ErrorCode:GA,ErrorInfo:VA}=DA;return{errorCode:GA,errorInfo:VA}}})}(N),this._customStatus=N,{code:0,data:{userID:v,statusType:ic,customStatus:N},successLog:{message:`customStatus: ${N}`}}}catch(O){const{errorCode:z,errorInfo:X}=O;throw new rs({functionName:"setSelfStatus",code:z,message:X})}})}getUserStatus(B){return pA(this,void 0,void 0,function*(){const{userIDList:v=[]}=B;if(this._isOnlyMeInArray(v))return this._getMyStatus();const N=yield this._getUserStatus(v);return Object.assign(Object.assign({},N),{successLog:{message:`userIDList length: ${v.length}`}})})}setCustomStatus(B){const v=Jr(B);this._customStatus=v}subscribeUserStatus(B){return pA(this,void 0,void 0,function*(){try{const{userIDList:v=[]}=B;this._checkBusinessCapabilityBits("subscribeUserStatus");const N=this._getMaxUserCount("subscribe"),O=this._sliceUserIDList(v,N),z=yield function(rA){return pA(this,void 0,void 0,function*(){const{channel:DA}=ye,GA="im_open_status.ws_status_subscribe",VA=Pt({servcmd:GA,data:{To_Account:rA}}),ee=`${VA.head.seq}${GA}`;return yield DA.sendPacket(VA,{requestId:ee})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${v.length} failCount: ${X.length}`}}}catch(v){const{errorCode:N}=v;throw new rs({functionName:"subscribeUserStatus",code:N})}})}unsubscribeUserStatus(B){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:v=[]}=B,N=this._getMaxUserCount("unsubscribe"),O=this._sliceUserIDList(v,N),z=yield function(rA){return pA(this,void 0,void 0,function*(){const{channel:DA}=ye,GA="im_open_status.ws_status_unsubscribe";let VA={};VA=rA.length===0?{UnsubscribeAll:1}:{To_Account:rA};const ee=Pt({servcmd:GA,data:VA}),Ee=`${ee.head.seq}${GA}`;return yield DA.sendPacket(ee,{requestId:Ee})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${v.length} failCount: ${X.length}`}}}catch(v){const{errorCode:N}=v;throw new rs({functionName:"unsubscribeUserStatus",code:N})}})}_onUserStatusUpdate(B){const{UserStatusList:v=[]}=B||{},N=v.map(O=>{const{To_Account:z,Status:X,CustomStatus:rA,Platform:DA}=O,GA={userID:z,statusType:X,customStatus:Jr(rA)};return DA&&(GA.onlineDevices=DA),GA});this._emitUserStatusUpdatedEvent(N)}_onReOnline(B){const v=Jr(B.data.customStatus);if(this._customStatus===v)return;this._customStatus=v;const N={userID:qn(),statusType:ic,customStatus:v};this._emitUserStatusUpdatedEvent(N)}_emitUserStatusUpdatedEvent(B){ye.notificationCenter.emitOuterEvent(Dn.USER_STATUS_UPDATED,{name:Dn.USER_STATUS_UPDATED,data:B})}_sliceUserIDList(B,v){return B.slice(0,v)}_parseResponse(B){const{ErrorList:v=[]}=B;return v.map(N=>{const{To_Account:O,Invalid_Account:z,ErrorCode:X,ErrorInfo:rA}=N;return{userID:ye.utils.isEmpty(z)?O:z,code:X,message:rA}})}_checkBusinessCapabilityBits(B){if(!ye.store.get("commercialConfig").get(_r))throw new rs({functionName:B,code:Lo.NO_USE,replacement1:B})}_getMaxUserCount(B){const v=ye.store.get("cloudConfig")||{},N={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:O,default:z}=N[B],X=v[O]||z;return parseInt(X,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:qn(),statusType:ic,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(B){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const v=this._getMaxUserCount("query"),N=this._sliceUserIDList(B,v),O=yield Hu(N),{successUserList:z,failureUserList:X}=O||{};return{code:0,data:{successUserList:z,failureUserList:X}}}catch(v){const{errorCode:N}=v;throw new rs({functionName:"getUserStatus",code:N})}})}_isOnlyMeInArray(B){const v=qn();return B.length===1&&B.indexOf(v)>-1}_dispose(){const{notificationCenter:B}=ye;B.unSubscribeInnerEvent(ui.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this),B.unSubscribeInnerEvent(ui.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const q={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(p){for(const B of p){if(typeof B!="object")return"Each item in profileCustomField must be an object";if(typeof B?.key!="string")return"Each item.key in profileCustomField must be a string";if(!B?.key.startsWith(Ig))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},L={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class oA{constructor(){this.userProfile=new xE,this.userStatus=new fC,this.userProfile.init(),this.userStatus.init(),Mc({auth:L,params:q})}}function b(p){const B=[];if(!l(p))return B;const v=p.length;if(v===0)return B;for(let N=v-1;N>=0;N--)p[N]==="1"&&B.push(2**(v-N-1));return B}var x,tA,uA;(function(p){p.NOT_START="notStart",p.PENDING="pending",p.RESOLVED="resolved",p.REJECTED="rejected"})(x||(x={})),function(p){p[p.C2C=1]="C2C",p[p.GROUP=2]="GROUP"}(tA||(tA={})),function(p){p[p.C2C=8]="C2C",p[p.GROUP=2]="GROUP"}(uA||(uA={}));class wA{constructor(){this._name="SyncConversationHandler",this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:B}=ye;tn.getInstance().registerWorkflowStep(nr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Vt.CONVERSATION_RECOVER,this._syncConversationList,this),tn.getInstance().registerWorkflowStep(nr.SYNC_SERVER_INFO_AFTER_LOGIN,Vt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),B.subscribeInnerEvent(ui.LOGOUT,this._reset,this),B.subscribeInnerEvent(ui.DESTROY,this._dispose,this),ye.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===x.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return pA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=ye;B.debug("_syncConversationList","start");try{const N=yield this._pagingGetConversationList(!0);this._pagingStatus=x.RESOLVED;const{conversationList:O=[]}=N||{};return B.info("_syncConversationList",`success count:${O.length}`),N}catch(N){const O=new rs(N);B.error("_syncConversationList",`fail ${v(N)}`,{error:O})}})}_pagingGetConversationList(B){return pA(this,void 0,void 0,function*(){try{const v=[];this._pagingStatus=x.PENDING;const N=yield function(ee){return pA(this,void 0,void 0,function*(){const{fromAccount:Ee,pagingTimeStamp:We,pagingStartIndex:ot,pagingPinnedTimeStamp:at,pagingPinnedStartIndex:Ut}=ee;return Zg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:Ee,StartIndex:ot,TimeStamp:We,TopStartIndex:Ut,TopTimeStamp:at}})})}({fromAccount:qn(),pagingTimeStamp:B?this._pagingTimeStamp:0,pagingStartIndex:B?this._pagingStartIndex:0,pagingPinnedTimeStamp:B?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:B?this._pagingPinnedStartIndex:0}),{CompleteFlag:O,SessionItem:z=[],TimeStamp:X,StartIndex:rA,TopTimeStamp:DA,TopStartIndex:GA}=N||{};let VA=[];if(O===1&&(this._pagingStatus=x.RESOLVED),z.length>0&&(VA=this._getConversationOptions(z),v.push(...VA)),ye.notificationCenter.emitInnerEvent(ui.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:VA}),this._pagingTimeStamp=X,this._pagingStartIndex=rA,this._pagingPinnedTimeStamp=DA,this._pagingPinnedStartIndex=GA,O!==1){const{conversationList:ee}=yield this._pagingGetConversationList(B);v.push(...ee)}return{conversationList:v}}catch(v){throw v}})}_getConversationOptions(B){const{utils:{isUndefined:v}}=ye,N=this._convertConversationKey(B);return this._filterValidConversations(N).map(O=>(v(O.lastMsg)&&(O.lastMsg={elements:[]}),O.type===tA.C2C?this._assembleC2COption(O):this._assembleGroupOption(O)))}_filterValidConversations(B){return B.filter(({type:v,userID:N})=>v===tA.C2C&&!function(O){let z;return O.startsWith(hs.CONV_C2C)&&(z=O.replace(hs.CONV_C2C,"")),z==="@TLS#ERROR"||z==="@TLS#NOT_FOUND"}(N)||v===2)}_assembleC2COption(B){var v,N,O,z,X,rA,DA,GA;const VA=this._createUserprofile(B);return{conversationID:`${hs.CONV_C2C}${B.userID}`,type:hs.CONV_C2C,lastMessage:{lastTime:B.time,lastSequence:B.sequence,fromAccount:B.lastC2CMsgFromAccount,type:!((v=B.lastMsg)===null||v===void 0)&&v.elements[0]?(N=B.lastMsg)===null||N===void 0?void 0:N.elements[0].type:null,payload:!((O=B.lastMsg)===null||O===void 0)&&O.elements[0]?this._amendLayersOverLimitProp(B.lastMsg.elements[0].content):null,cloudCustomData:((rA=(X=(z=B.lastMsg)===null||z===void 0?void 0:z.elements)===null||X===void 0?void 0:X[0])===null||rA===void 0?void 0:rA.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(B),revoker:((GA=(DA=B.lastMsg)===null||DA===void 0?void 0:DA.revokerInfo)===null||GA===void 0?void 0:GA.revoker)||null},unreadCount:0,userProfile:VA,peerReadTime:B.peerReadTime,isPinned:B.isPinned===1,customData:B.customMark||"",markList:b(B.standardMark),conversationGroupList:[],remark:B.friendRemark||"",messageRemindType:this._transMsgRemindType(B.messageRemindType)}}_createUserprofile(B){var v;const{userID:N,nick:O,peerAvatar:z}=B,X=[{tag:"Tag_Profile_IM_Nick",value:O},{tag:"Tag_Profile_IM_Image",value:z}];return(v=ye.user.userProfile)===null||v===void 0?void 0:v.createProfile(N,X)}_computeIsPeerRead(B){const v=qn(),{lastC2CMsgFromAccount:N,time:O,c2cPeerReadTime:z}=B;return N===v&&O<=z}_assembleGroupOption(B){var v,N,O,z,X;return{conversationID:`${hs.CONV_GROUP}${B.groupID}`,type:hs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:B.time,lastSequence:B.sequence,fromAccount:B.msgGroupFromAccount},this._patchTypeAndPayload(B)),{cloudCustomData:((O=(N=(v=B.lastMsg)===null||v===void 0?void 0:v.elements)===null||N===void 0?void 0:N[0])===null||O===void 0?void 0:O.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.GROUP,onlineOnlyFlag:!1,nick:B.msgGroupFromNickName||"",nameCard:B.msgGroupFromCardName||"",revoker:((X=(z=B.lastMsg)===null||z===void 0?void 0:z.revokerInfo)===null||X===void 0?void 0:X.revoker)||null}),groupProfile:{groupID:B.groupID,name:B.groupNick,avatar:B.groupImage,type:B.groupType,nextMessageSeq:B.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(B),peerReadTime:0,isPinned:B.isPinned===1,version:0,customData:B.customMark||"",markList:b(B.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(B.messageRemindType),subType:B.groupType}}_convertConversationKey(B){return B.map(v=>({type:v.Type,userID:v.To_Account,nick:v.C2cNick,peerAvatar:v.C2cImage,time:v.MsgTimeStamp,sequence:v.MsgSeq,lastC2CMsgFromAccount:v.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(v.LastMsg),lastMessageFlag:v.LastMsgFlags,c2cPeerReadTime:v.C2cPeerReadTime,peerReadTime:v.C2cPeerReadTime,friendRemark:v.C2cRemark,isPinned:v.TopFlags,standardMark:v.StandardMark,customMark:v.CustomMark,messageRemindType:v.MsgRecvOption,groupID:v.ToAccount,groupNick:v.GroupNick,groupImage:v.GroupImage,groupType:v.GroupType,nextMessageSeq:v.GroupNextMsgSeq,msgGroupFromAccount:v.MsgGroupFrom_Account,msgGroupFromNickName:v.MsgGroupFromNickName,msgGroupFromCardName:v.MsgGroupFromCardName,unreadCount:v.UnreadMsgCount,noUnreadCount:v.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(B){var v,N,O;const{utils:{isEmpty:z}}=ye;if(z(B))return null;let X="",rA=null;if(!z(B.GroupTips)){const{From_Account:DA,GroupName:GA}=((v=B.GroupTips)===null||v===void 0?void 0:v.GroupInfo)||{};X=hs.MSG_GRP_TIP,rA=Object.assign(Object.assign({},this._parseContent(X,B.GroupTips.MsgBody)),{groupProfile:{from:DA,groupName:GA}})}return B.MsgBody&&(X=(N=B.MsgBody[0])===null||N===void 0?void 0:N.MsgType,rA=this._parseContent(X,B.MsgBody[0])),{event:B.Event,elements:[{type:X,content:rA,cloudCustomData:B.CloudCustomData}],revokerInfo:{revoker:(O=B.RevokerInfo)===null||O===void 0?void 0:O.Revoker_Account}}}_parseContent(B,v){var N;if(!v)return v;const O=ye.message.messageFactory.getElementClass(B);return O?(N=O.parseServerPushElement(v))===null||N===void 0?void 0:N.content:v}_amendLayersOverLimitProp(B){const{LayersOverLimit:v}=B;return Do(B,["LayersOverLimit"]).layersOverLimit=v===1,B}_transMsgRemindType(B){let v="";return B===0?v=hs.MSG_REMIND_ACPT_AND_NOTE:B===1?v=hs.MSG_REMIND_DISCARD:B===2?v=hs.MSG_REMIND_ACPT_NOT_NOTE:B===3&&(v=hs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),v}_patchTypeAndPayload(B){var v;const{utils:{isUndefined:N}}=ye,{event:O,elements:z=[]}=B.lastMsg||{};return N(O)?{type:z[0]?z[0].type:null,payload:z[0]?this._amendLayersOverLimitProp(z[0].content):null}:{type:hs.MSG_GRP_TIP,payload:((v=z?.[0])===null||v===void 0?void 0:v.content)||{}}}_computeGroupUnreadCount(B){const{unreadCount:v=0,noUnreadCount:N=0}=B,O=v-N;return O>0?O:0}_reset(){this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:B}=ye;B.unSubscribeInnerEvent(ui.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(ui.DESTROY,this._dispose,this)}}class XA{constructor(){this.syncConversationHandler=new wA,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Zr}`);var pe={create:function(p){var B,v;const{SDKAppID:N,testEnv:O=!1,devMode:z=!1,unlimitedAVChatRoom:X=!1,scene:rA="",oversea:DA=!1,instance:GA,disableIndependentDomain:VA=!1,proxyServer:ee=""}=p;let Ee=N;if(!function(ot){if(typeof ot=="number")return!0;const at=Number(ot);return!Number.isNaN(at)}(Ee))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(Ee=Number(Ee),ws.has(Ee))return ws.get(Ee);let We=null;if(GA)We=GA,We._workflowManager&&tn.setInstance(We._workflowManager),We._pluginManager&&We._pluginManager.installBuiltInPlugin(Er),GA.isReady()&&((v=(B=tn.getInstance()).executeWorkflow)===null||v===void 0||v.call(B,nr.SYNC_SERVER_INFO_AFTER_LOGIN));else{const ot=function(){function Xi(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Xi()+Xi()}${Xi()}${Xi()}${Xi()}${Xi()}${Xi()}${Xi()}`}();ye.init({sdkAppId:Ee,instanceId:ot,testEnv:O,devMode:z,unlimitedAVChatRoom:X,disableIndependentDomain:VA,scene:rA,oversea:DA,sdkEdition:Ou,version:Zr,proxyServer:ee}),tn.getInstance().init(),ye.message=new gl,ye.user=new oA,ye.login=new Ac,ye.conversation=new XA,Oo.getInstance().installBuiltInPlugin(Er),We=js.getInstance().exposeApiForClient(),We._workflowManager=tn.getInstance(),We._pluginManager=Oo.getInstance();const{utils:{IS_WORKER_AVAILABLE:at,USER_AGENT:Ut,getPlatformType:Jt,isIOSWebView:Ui}}=ye,go=`instanceID:${ot} SDKAppID:${N} platform:${HA} host:${Jt()} isIOSWebView:${Ui} workerAvailable:${at} UserAgent:${Ut}`;ye.ssoLog.info("sdkConstruct",go)}return ws.set(Ee,We),We},TSignaling:no,EVENT:Dn,VERSION:Zr,TYPES:hs};return pe})}(tY)),tY.exports}var TL={exports:{}},iY={exports:{}},brA=iY.exports,W8;function krA(){return W8||(W8=1,function(t,i){(function(r,l){t.exports=l()})(brA,function(){function r(A,e){return e.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(a){if(a!=="default"&&!(a in A)){var c=Object.getOwnPropertyDescriptor(o,a);Object.defineProperty(A,a,c.get?c:{enumerable:!0,get:function(){return o[a]}})}})}),Object.freeze(A)}var l=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof mg<"u"?mg:typeof self<"u"?self:{};function I(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var h=function(A){return A&&A.Math===Math&&A},f=h(typeof globalThis=="object"&&globalThis)||h(typeof window=="object"&&window)||h(typeof self=="object"&&self)||h(typeof l=="object"&&l)||h(typeof l=="object"&&l)||function(){return this}()||Function("return this")(),w={},_=function(A){try{return!!A()}catch{return!0}},G=!_(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),U=!_(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),j=U,lA=Function.prototype.call,sA=j?lA.bind(lA):function(){return lA.apply(lA,arguments)},mA={},IA={}.propertyIsEnumerable,cA=Object.getOwnPropertyDescriptor,TA=cA&&!IA.call({1:2},1);mA.f=TA?function(A){var e=cA(this,A);return!!e&&e.enumerable}:IA;var WA,ue,Ce=function(A,e){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:e}},xe=U,Qe=Function.prototype,ut=Qe.call,ft=xe&&Qe.bind.bind(ut,ut),je=xe?ft:function(A){return function(){return ut.apply(A,arguments)}},Mt=je,jt=Mt({}.toString),Et=Mt("".slice),re=function(A){return Et(jt(A),8,-1)},qe=_,yt=re,Me=Object,Oe=je("".split),gt=qe(function(){return!Me("z").propertyIsEnumerable(0)})?function(A){return yt(A)==="String"?Oe(A,""):Me(A)}:Me,Fi=function(A){return A==null},To=Fi,io=TypeError,Eo=function(A){if(To(A))throw new io("Can't call method on "+A);return A},Vs=gt,ki=Eo,ns=function(A){return Vs(ki(A))},jo=typeof document=="object"&&document.all,Ao=jo===void 0&&jo!==void 0?function(A){return typeof A=="function"||A===jo}:function(A){return typeof A=="function"},Zt=Ao,oo=function(A){return typeof A=="object"?A!==null:Zt(A)},bi=f,vs=Ao,HA=function(A,e){return arguments.length<2?(o=bi[A],vs(o)?o:void 0):bi[A]&&bi[A][e];var o},ce=je({}.isPrototypeOf),Ve=f.navigator,Ot=Ve&&Ve.userAgent,nt=Ot?String(Ot):"",It=f,ei=nt,ti=It.process,be=It.Deno,Ze=ti&&ti.versions||be&&be.version,wt=Ze&&Ze.v8;wt&&(ue=(WA=wt.split("."))[0]>0&&WA[0]<4?1:+(WA[0]+WA[1])),!ue&&ei&&(!(WA=ei.match(/Edge\/(\d+)/))||WA[1]>=74)&&(WA=ei.match(/Chrome\/(\d+)/))&&(ue=+WA[1]);var Nt=ue,Oi=Nt,po=_,No=f.String,so=!!Object.getOwnPropertySymbols&&!po(function(){var A=Symbol("symbol detection");return!No(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&Oi&&Oi<41}),Go=so&&!Symbol.sham&&typeof Symbol.iterator=="symbol",An=HA,rn=Ao,Es=ce,an=Object,Do=Go?function(A){return typeof A=="symbol"}:function(A){var e=An("Symbol");return rn(e)&&Es(e.prototype,an(A))},pA=String,Jn=function(A){try{return pA(A)}catch{return"Object"}},Qr=Ao,ds=Jn,zr=TypeError,Pi=function(A){if(Qr(A))return A;throw new zr(ds(A)+" is not a function")},Rs=Pi,or=Fi,en=function(A,e){var o=A[e];return or(o)?void 0:Rs(o)},wn=sA,qt=Ao,yg=oo,On=TypeError,Gn={exports:{}},Js=f,pr=Object.defineProperty,Pn=function(A,e){try{pr(Js,A,{value:e,configurable:!0,writable:!0})}catch{Js[A]=e}return e},mr=f,mo=Pn,gn="__core-js_shared__",Sl=Gn.exports=mr[gn]||mo(gn,{});(Sl.versions||(Sl.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var cn=Gn.exports,fr=cn,Ls=function(A,e){return fr[A]||(fr[A]=e||{})},Jc=Eo,ms=Object,as=function(A){return ms(Jc(A))},Ru=as,Wa=je({}.hasOwnProperty),Cs=Object.hasOwn||function(A,e){return Wa(Ru(A),e)},sg=je,HI=0,As=Math.random(),$i=sg(1.1.toString),pc=function(A){return"Symbol("+(A===void 0?"":A)+")_"+$i(++HI+As,36)},ng=Ls,Dg=Cs,ua=pc,bo=so,Zr=Go,_o=f.Symbol,Hc=ng("wks"),Hn=Zr?_o.for||_o:_o&&_o.withoutSetter||ua,Hs=function(A){return Dg(Hc,A)||(Hc[A]=bo&&Dg(_o,A)?_o[A]:Hn("Symbol."+A)),Hc[A]},Sg=sA,mc=oo,fn=Do,Ga=en,In=function(A,e){var o,a;if(e==="string"&&qt(o=A.toString)&&!yg(a=wn(o,A))||qt(o=A.valueOf)&&!yg(a=wn(o,A))||e!=="string"&&qt(o=A.toString)&&!yg(a=wn(o,A)))return a;throw new On("Can't convert object to primitive value")},fs=TypeError,Ea=Hs("toPrimitive"),yn=function(A,e){if(!mc(A)||fn(A))return A;var o,a=Ga(A,Ea);if(a){if(e===void 0&&(e="default"),o=Sg(a,A,e),!mc(o)||fn(o))return o;throw new fs("Can't convert object to primitive value")}return e===void 0&&(e="number"),In(A,e)},ba=yn,Sa=Do,$=function(A){var e=ba(A,"string");return Sa(e)?e:e+""},K=oo,vA=f.document,qA=K(vA)&&K(vA.createElement),Ae=function(A){return qA?vA.createElement(A):{}},me=Ae,Pe=!G&&!_(function(){return Object.defineProperty(me("div"),"a",{get:function(){return 7}}).a!==7}),Fe=G,rt=sA,Ct=mA,Rt=Ce,Yt=ns,Ii=$,ct=Cs,xt=Pe,Ji=Object.getOwnPropertyDescriptor;w.f=Fe?Ji:function(A,e){if(A=Yt(A),e=Ii(e),xt)try{return Ji(A,e)}catch{}if(ct(A,e))return Rt(!rt(Ct.f,A,e),A[e])};var Ki={},qs=G&&_(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Mi=oo,zo=String,Mg=TypeError,sr=function(A){if(Mi(A))return A;throw new Mg(zo(A)+" is not an object")},yr=G,xn=Pe,Ml=qs,Ks=sr,aI=$,Wg=TypeError,fc=Object.defineProperty,wu=Object.getOwnPropertyDescriptor,Ma="enumerable",vl="configurable",ye="writable";Ki.f=yr?Ml?function(A,e,o){if(Ks(A),e=aI(e),Ks(o),typeof A=="function"&&e==="prototype"&&"value"in o&&ye in o&&!o[ye]){var a=wu(A,e);a&&a[ye]&&(A[e]=o.value,o={configurable:vl in o?o[vl]:a[vl],enumerable:Ma in o?o[Ma]:a[Ma],writable:!1})}return fc(A,e,o)}:fc:function(A,e,o){if(Ks(A),e=aI(e),Ks(o),xn)try{return fc(A,e,o)}catch{}if("get"in o||"set"in o)throw new Wg("Accessors not supported");return"value"in o&&(A[e]=o.value),A};var fe=Ki,vg=Ce,rg=G?function(A,e,o){return fe.f(A,e,vg(1,o))}:function(A,e,o){return A[e]=o,A},Rg={exports:{}},Dn=G,Dr=Cs,ui=Function.prototype,no=Dn&&Object.getOwnPropertyDescriptor,qc=Dr(ui,"name"),zg={PROPER:qc&&function(){}.name==="something",CONFIGURABLE:qc&&(!Dn||Dn&&no(ui,"name").configurable)},wg=Ao,Yr=cn,yc=je(Function.toString);wg(Yr.inspectSource)||(Yr.inspectSource=function(A){return yc(A)});var Kc,ag,_u,SE=Yr.inspectSource,_g=Ao,ka=f.WeakMap,Dc=_g(ka)&&/native code/.test(String(ka)),ME=pc,La=Ls("keys"),sa=function(A){return La[A]||(La[A]=ME(A))},Tg={},gI=Dc,hs=f,Lo=oo,da=rg,nr=Cs,Vt=cn,Kt=sa,Ng=Tg,cI="Object already initialized",rr=hs.TypeError,qI=hs.WeakMap;if(gI||Vt.state){var za=Vt.state||(Vt.state=new qI);za.get=za.get,za.has=za.has,za.set=za.set,Kc=function(A,e){if(za.has(A))throw new rr(cI);return e.facade=A,za.set(A,e),e},ag=function(A){return za.get(A)||{}},_u=function(A){return za.has(A)}}else{var na=Kt("state");Ng[na]=!0,Kc=function(A,e){if(nr(A,na))throw new rr(cI);return e.facade=A,da(A,na,e),e},ag=function(A){return nr(A,na)?A[na]:{}},_u=function(A){return nr(A,na)}}var un={set:Kc,get:ag,has:_u,enforce:function(A){return _u(A)?ag(A):Kc(A,{})},getterFor:function(A){return function(e){var o;if(!Lo(e)||(o=ag(e)).type!==A)throw new rr("Incompatible receiver, "+A+" required");return o}}},Sn=je,Tu=_,Gg=Ao,Ua=Cs,jc=G,KI=zg.CONFIGURABLE,vE=SE,lI=un.enforce,Nu=un.get,Rl=String,Sc=Object.defineProperty,Gu=Sn("".slice),bu=Sn("".replace),wl=Sn([].join),rs=jc&&!Tu(function(){return Sc(function(){},"length",{value:8}).length!==8}),gs=String(String).split("String"),ud=Rg.exports=function(A,e,o){Gu(Rl(e),0,7)==="Symbol("&&(e="["+bu(Rl(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(e="get "+e),o&&o.setter&&(e="set "+e),(!Ua(A,"name")||KI&&A.name!==e)&&(jc?Sc(A,"name",{value:e,configurable:!0}):A.name=e),rs&&o&&Ua(o,"arity")&&A.length!==o.arity&&Sc(A,"length",{value:o.arity});try{o&&Ua(o,"constructor")&&o.constructor?jc&&Sc(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var a=lI(A);return Ua(a,"source")||(a.source=wl(gs,typeof e=="string"?e:"")),A};Function.prototype.toString=ud(function(){return Gg(this)&&Nu(this).source||vE(this)},"toString");var II=Rg.exports,uI=Ao,RE=Ki,Ed=II,_l=Pn,Sr=function(A,e,o,a){a||(a={});var c=a.enumerable,d=a.name!==void 0?a.name:e;if(uI(o)&&Ed(o,d,a),a.global)c?A[e]=o:_l(e,o);else{try{a.unsafe?A[e]&&(c=!0):delete A[e]}catch{}c?A[e]=o:RE.f(A,e,{value:o,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return A},Mc={},Wc=Math.ceil,tn=Math.floor,ws=Math.trunc||function(A){var e=+A;return(e>0?tn:Wc)(e)},Ca=ws,Xr=function(A){var e=+A;return e!=e||e===0?0:Ca(e)},zc=Xr,dd=Math.max,Zg=Math.min,gg=function(A,e){var o=zc(A);return o<0?dd(o+e,0):Zg(o,e)},wE=Xr,Xg=Math.min,qn=function(A){var e=wE(A);return e>0?Xg(e,9007199254740991):0},Ar=qn,Fa=function(A){return Ar(A.length)},Cd=ns,lC=gg,ku=Fa,jI=function(A){return function(e,o,a){var c=Cd(e),d=ku(c);if(d===0)return!A&&-1;var C,y=lC(a,d);if(A&&o!=o){for(;d>y;)if((C=c[y++])!=C)return!0}else for(;d>y;y++)if((A||y in c)&&c[y]===o)return A||y||0;return!A&&-1}},Zc={includes:jI(!0),indexOf:jI(!1)},Xc=Cs,WI=ns,EI=Zc.indexOf,$c=Tg,Al=je([].push),va=function(A,e){var o,a=WI(A),c=0,d=[];for(o in a)!Xc($c,o)&&Xc(a,o)&&Al(d,o);for(;e.length>c;)Xc(a,o=e[c++])&&(~EI(d,o)||Al(d,o));return d},bg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ys=va,Kn=bg.concat("length","prototype");Mc.f=Object.getOwnPropertyNames||function(A){return ys(A,Kn)};var vc={};vc.f=Object.getOwnPropertySymbols;var zI=HA,ZI=Mc,_E=vc,rh=sr,IC=je([].concat),ah=zI("Reflect","ownKeys")||function(A){var e=ZI.f(rh(A)),o=_E.f;return o?IC(e,o(A)):e},el=Cs,kg=ah,ro=w,uC=Ki,TE=function(A,e,o){for(var a=kg(e),c=uC.f,d=ro.f,C=0;CC;)QI.f(A,o=c[C++],a[o]);return A};var Ug,ec=HA("document","documentElement"),md=sr,LE=Gl,Nc=bg,Au=Tg,lo=ec,UE=Ae,$a="prototype",eu="script",Pu=sa("IE_PROTO"),Gc=function(){},pI=function(A){return"<"+eu+">"+A+""},sl=function(A){A.write(pI("")),A.close();var e=A.parentWindow.Object;return A=null,e},nl=function(){try{Ug=new ActiveXObject("htmlfile")}catch{}nl=typeof document<"u"?document.domain&&Ug?sl(Ug):function(){var e,o=UE("iframe"),a="java"+eu+":";return o.style.display="none",lo.appendChild(o),o.src=String(a),(e=o.contentWindow.document).open(),e.write(pI("document.F=Object")),e.close(),e.F}():sl(Ug);for(var A=Nc.length;A--;)delete nl[$a][Nc[A]];return nl()};Au[Pu]=!0;var xa=Object.create||function(A,e){var o;return A!==null?(Gc[$a]=md(A),o=new Gc,Gc[$a]=null,o[Pu]=A):o=nl(),e===void 0?o:LE.f(o,e)},FE=Hs,ra=xa,Mn=Ki.f,kr=FE("unscopables"),rl=Array.prototype;rl[kr]===void 0&&Mn(rl,kr,{configurable:!0,value:ra(null)});var Ul=function(A){rl[kr][A]=!0},bc=Zc.includes,OE=Ul;_n({target:"Array",proto:!0,forced:_(function(){return!Array(1).includes()})},{includes:function(A){return bc(this,A,arguments.length>1?arguments[1]:void 0)}}),OE("includes");var kc,xu,pC,tu={},lh=!_(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),Yu=Cs,mI=Ao,al=as,mC=lh,aa=sa("IE_PROTO"),tc=Object,lg=tc.prototype,fI=mC?tc.getPrototypeOf:function(A){var e=al(A);if(Yu(e,aa))return e[aa];var o=e.constructor;return mI(o)&&e instanceof o?o.prototype:e instanceof tc?lg:null},PE=_,Vu=Ao,Ju=oo,yI=fI,gl=Sr,Lr=Hs("iterator"),Ur=!1;[].keys&&("next"in(pC=[].keys())?(xu=yI(yI(pC)))!==Object.prototype&&(kc=xu):Ur=!0);var Ig=!Ju(kc)||PE(function(){var A={};return kc[Lr].call(A)!==A});Ig&&(kc={}),Vu(kc[Lr])||gl(kc,Lr,function(){return this});var ar={IteratorPrototype:kc,BUGGY_SAFARI_ITERATORS:Ur},_r=Ki.f,ic=Cs,Fg=Hs("toStringTag"),Ya=function(A,e,o){A&&!o&&(A=A.prototype),A&&!ic(A,Fg)&&_r(A,Fg,{configurable:!0,value:e})},Fl=ar.IteratorPrototype,ha=xa,DI=Ce,iu=Ya,Ba=tu,cl=function(){return this},xE=function(A,e,o,a){var c=e+" Iterator";return A.prototype=ha(Fl,{next:DI(+!a,o)}),iu(A,c,!1),Ba[c]=cl,A},ou=je,YE=Pi,Jr=oo,su=function(A){return Jr(A)||A===null},Pt=String,Hu=TypeError,qu=function(A,e,o){try{return ou(YE(Object.getOwnPropertyDescriptor(A,e)[o]))}catch{}},fC=oo,q=Eo,L=function(A){if(su(A))return A;throw new Hu("Can't set "+Pt(A)+" as a prototype")},oA=Object.setPrototypeOf||("__proto__"in{}?function(){var A,e=!1,o={};try{(A=qu(Object.prototype,"__proto__","set"))(o,[]),e=o instanceof Array}catch{}return function(a,c){return q(a),L(c),fC(a)&&(e?A(a,c):a.__proto__=c),a}}():void 0),b=_n,x=sA,tA=Ao,uA=xE,wA=fI,XA=oA,pe=Ya,p=rg,B=Sr,v=tu,N=zg.PROPER,O=zg.CONFIGURABLE,z=ar.IteratorPrototype,X=ar.BUGGY_SAFARI_ITERATORS,rA=Hs("iterator"),DA="keys",GA="values",VA="entries",ee=function(){return this},Ee=function(A,e,o,a,c,d,C){uA(o,e,a);var y,S,k,V=function(Ye){if(Ye===c&&$A)return $A;if(!X&&Ye&&Ye in CA)return CA[Ye];switch(Ye){case DA:case GA:case VA:return function(){return new o(this,Ye)}}return function(){return new o(this)}},J=e+" Iterator",gA=!1,CA=A.prototype,MA=CA[rA]||CA["@@iterator"]||c&&CA[c],$A=!X&&MA||V(c),Be=e==="Array"&&CA.entries||MA;if(Be&&(y=wA(Be.call(new A)))!==Object.prototype&&y.next&&(wA(y)!==z&&(XA?XA(y,z):tA(y[rA])||B(y,rA,ee)),pe(y,J,!0)),N&&c===GA&&MA&&MA.name!==GA&&(O?p(CA,"name",GA):(gA=!0,$A=function(){return x(MA,this)})),c)if(S={values:V(GA),keys:d?$A:V(DA),entries:V(VA)},C)for(k in S)(X||gA||!(k in CA))&&B(CA,k,S[k]);else b({target:e,proto:!0,forced:X||gA},S);return CA[rA]!==$A&&B(CA,rA,$A,{name:c}),v[e]=$A,S},We=function(A,e){return{value:A,done:e}},ot=ns,at=Ul,Ut=tu,Jt=un,Ui=Ki.f,go=Ee,Xi=We,Ei=G,Po="Array Iterator",es=Jt.set,pi=Jt.getterFor(Po),ji=go(Array,"Array",function(A,e){es(this,{type:Po,target:ot(A),index:0,kind:e})},function(){var A=pi(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,Xi(void 0,!0);switch(A.kind){case"keys":return Xi(o,!1);case"values":return Xi(e[o],!1)}return Xi([o,e[o]],!1)},"values"),Ws=Ut.Arguments=Ut.Array;if(at("keys"),at("values"),at("entries"),Ei&&Ws.name!=="values")try{Ui(Ws,"name",{value:"values"})}catch{}var _e=Pi,_t=as,FA=gt,Xt=Fa,En=TypeError,Ai="Reduce of empty array with no initial value",us=function(A){return function(e,o,a,c){var d=_t(e),C=FA(d),y=Xt(d);if(_e(o),y===0&&a<2)throw new En(Ai);var S=A?y-1:0,k=A?-1:1;if(a<2)for(;;){if(S in C){c=C[S],S+=k;break}if(S+=k,A?S<0:y<=S)throw new En(Ai)}for(;A?S>=0:y>S;S+=k)S in C&&(c=o(c,C[S],S,d));return c}},vi={left:us(!1),right:us(!0)},ho=_,ht=function(A,e){var o=[][A];return!!o&&ho(function(){o.call(null,e||function(){return 1},1)})},Qt=f,ug=nt,ks=re,Wi=function(A){return ug.slice(0,A.length)===A},Hr=Wi("Bun/")?"BUN":Wi("Cloudflare-Workers")?"CLOUDFLARE":Wi("Deno/")?"DENO":Wi("Node.js/")?"NODE":Qt.Bun&&typeof Bun.version=="string"?"BUN":Qt.Deno&&typeof Deno.version=="object"?"DENO":ks(Qt.process)==="process"?"NODE":Qt.window&&Qt.document?"BROWSER":"REST",oc=Hr==="NODE",is=vi.left;_n({target:"Array",proto:!0,forced:!oc&&Nt>79&&Nt<83||!ht("reduce")},{reduce:function(A){var e=arguments.length;return is(this,A,e,e>1?arguments[1]:void 0)}});var ga=vi.right;_n({target:"Array",proto:!0,forced:!oc&&Nt>79&&Nt<83||!ht("reduceRight")},{reduceRight:function(A){return ga(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Qa=re,ea=Array.isArray||function(A){return Qa(A)==="Array"},H=_n,BA=ea,yA=je([].reverse),NA=[1,2];H({target:"Array",proto:!0,forced:String(NA)===String(NA.reverse())},{reverse:function(){return BA(this)&&(this.length=this.length),yA(this)}});var zA=Jn,we=TypeError,le=je([].slice),Ne=le,ge=Math.floor,Ue=function(A,e){var o=A.length;if(o<8)for(var a,c,d=1;d0;)A[c]=A[--c];c!==d++&&(A[c]=a)}else for(var C=ge(o/2),y=Ue(Ne(A,0,C),e),S=Ue(Ne(A,C),e),k=y.length,V=S.length,J=0,gA=0;J3)){if(mm)return!0;if(ni)return ni<603;var A,e,o,a,c="";for(A=65;A<76;A++){switch(e=String.fromCharCode(A),A){case 66:case 69:case 70:case 72:o=3;break;case 68:case 71:o=4;break;default:o=2}for(a=0;a<47;a++)yo.push({k:e+a,v:o})}for(yo.sort(function(d,C){return C.v-d.v}),a=0;aWn(S)?1:-1}}(A)),o=Zo(c),a=0;ao||S!=S?1/0*C:C*S},uD=Math.fround||function(A){return ID(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},Ov=Array,BT=Math.abs,yd=Math.pow,QT=Math.floor,ED=Math.log,pT=Math.LN2,dD={pack:function(A,e,o){var a,c,d,C=Ov(o),y=8*o-e-1,S=(1<>1,V=e===23?yd(2,-24)-yd(2,-77):0,J=A<0||A===0&&1/A<0?1:0,gA=0;for((A=BT(A))!=A||A===1/0?(c=A!=A?1:0,a=S):(a=QT(ED(A)/pT),A*(d=yd(2,-a))<1&&(a--,d*=2),(A+=a+k>=1?V/d:V*yd(2,1-k))*d>=2&&(a++,d/=2),a+k>=S?(c=0,a=S):a+k>=1?(c=(A*d-1)*yd(2,e),a+=k):(c=A*yd(2,k-1)*yd(2,e),a=0));e>=8;)C[gA++]=255&c,c/=256,e-=8;for(a=a<0;)C[gA++]=255&a,a/=256,y-=8;return C[gA-1]|=128*J,C},unpack:function(A,e){var o,a=A.length,c=8*a-e-1,d=(1<>1,y=c-7,S=a-1,k=A[S--],V=127&k;for(k>>=7;y>0;)V=256*V+A[S--],y-=8;for(o=V&(1<<-y)-1,V>>=-y,y+=e;y>0;)o=256*o+A[S--],y-=8;if(V===0)V=1-C;else{if(V===d)return o?NaN:k?-1/0:1/0;o+=yd(2,e),V-=C}return(k?-1:1)*o*yd(2,V-e)}},mT=as,Pv=gg,fT=Fa,xv=function(A){for(var e=mT(this),o=fT(e),a=arguments.length,c=Pv(a>1?arguments[1]:void 0,o),d=a>2?arguments[2]:void 0,C=d===void 0?o:Pv(d,o);C>c;)e[c++]=A;return e},yT=Ao,DT=oo,CD=oA,hD=function(A,e,o){var a,c;return CD&&yT(a=e.constructor)&&a!==o&&DT(c=a.prototype)&&c!==o.prototype&&CD(A,c),A},TQ=f,Mm=je,vm=G,Dd=Mr,ST=rg,MT=Lg,Rm=nu,BD=_,Ih=MI,vT=Xr,RT=qn,wm=ym,Yv=uD,QD=dD,_m=fI,Vv=oA,wT=xv,_T=le,Jv=hD,Sd=TE,Tm=Ya,Md=un,VE=zg.PROPER,Nm=zg.CONFIGURABLE,yC="ArrayBuffer",uh="DataView",Wu="prototype",Yi="Wrong index",Gm=Md.getterFor(yC),dn=Md.getterFor(uh),Hv=Md.set,zu=TQ[yC],zs=zu,Eh=zs&&zs[Wu],Pl=TQ[uh],nc=Pl&&Pl[Wu],JE=Object.prototype,NQ=TQ.Array,cB=TQ.RangeError,TT=Mm(wT),NT=Mm([].reverse),GQ=QD.pack,bQ=QD.unpack,qv=function(A){return[255&A]},Kv=function(A){return[255&A,A>>8&255]},pD=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},DC=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},lB=function(A){return GQ(Yv(A),23,4)},mD=function(A){return GQ(A,52,8)},kQ=function(A,e,o){MT(A[Wu],e,{configurable:!0,get:function(){return o(this)[e]}})},vd=function(A,e,o,a){var c=dn(A),d=wm(o),C=!!a;if(d+e>c.byteLength)throw new cB(Yi);var y=c.bytes,S=d+c.byteOffset,k=_T(y,S,S+e);return C?k:NT(k)},Rd=function(A,e,o,a,c,d){var C=dn(A),y=wm(o),S=a(+c),k=!!d;if(y+e>C.byteLength)throw new cB(Yi);for(var V=C.bytes,J=y+C.byteOffset,gA=0;gA>24)},setUint8:function(A,e){fD(this,A,e<<24>>24)}},{unsafe:!0})}else Eh=(zs=function(A){Ih(this,Eh);var e=wm(A);Hv(this,{type:yC,bytes:TT(NQ(e),0),byteLength:e}),vm||(this.byteLength=e,this.detached=!1)})[Wu],nc=(Pl=function(A,e,o){Ih(this,nc),Ih(A,Eh);var a=Gm(A),c=a.byteLength,d=vT(e);if(d<0||d>c)throw new cB("Wrong offset");if(d+(o=o===void 0?c-d:RT(o))>c)throw new cB("Wrong length");Hv(this,{type:uh,buffer:A,byteLength:o,byteOffset:d,bytes:a.bytes}),vm||(this.buffer=A,this.byteLength=o,this.byteOffset=d)})[Wu],vm&&(kQ(zs,"byteLength",Gm),kQ(Pl,"buffer",dn),kQ(Pl,"byteLength",dn),kQ(Pl,"byteOffset",dn)),Rm(nc,{getInt8:function(A){return vd(this,1,A)[0]<<24>>24},getUint8:function(A){return vd(this,1,A)[0]},getInt16:function(A){var e=vd(this,2,A,arguments.length>1&&arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(A){var e=vd(this,2,A,arguments.length>1&&arguments[1]);return e[1]<<8|e[0]},getInt32:function(A){return DC(vd(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return DC(vd(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return bQ(vd(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return bQ(vd(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,e){Rd(this,1,A,qv,e)},setUint8:function(A,e){Rd(this,1,A,qv,e)},setInt16:function(A,e){Rd(this,2,A,Kv,e,arguments.length>2&&arguments[2])},setUint16:function(A,e){Rd(this,2,A,Kv,e,arguments.length>2&&arguments[2])},setInt32:function(A,e){Rd(this,4,A,pD,e,arguments.length>2&&arguments[2])},setUint32:function(A,e){Rd(this,4,A,pD,e,arguments.length>2&&arguments[2])},setFloat32:function(A,e){Rd(this,4,A,lB,e,arguments.length>2&&arguments[2])},setFloat64:function(A,e){Rd(this,8,A,mD,e,arguments.length>2&&arguments[2])}});Tm(zs,yC),Tm(Pl,uh);var bm={ArrayBuffer:zs,DataView:Pl},Wv=HA,GT=Lg,km=G,IB=Hs("species"),Lm=function(A){var e=Wv(A);km&&e&&!e[IB]&>(e,IB,{configurable:!0,get:function(){return this}})},bT=Lm,yD="ArrayBuffer",DD=bm[yD];_n({global:!0,constructor:!0,forced:f[yD]!==DD},{ArrayBuffer:DD}),bT(yD);var UQ=re,HE=je,Zu=function(A){if(UQ(A)==="Function")return HE(A)},SD=_n,dh=Zu,Um=_,zv=sr,FQ=gg,Zv=qn,MD=bm.ArrayBuffer,vn=bm.DataView,OQ=vn.prototype,wd=dh(MD.prototype.slice),vD=dh(OQ.getUint8),kT=dh(OQ.setUint8);SD({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Um(function(){return!new MD(2).slice(1,void 0).byteLength})},{slice:function(A,e){if(wd&&e===void 0)return wd(zv(this),A);for(var o=zv(this).byteLength,a=FQ(A,o),c=FQ(e===void 0?o:e,o),d=new MD(Zv(c-a)),C=new vn(this),y=new vn(d),S=0;ad;d++)if((y=Ye(A[d]))&&tS(Ld,y))return y;return new wC(!1)}a=tN(A,c)}for(S=gA?A.next:a.next;!(k=$T(S,a)).done;){try{y=Ye(k.value)}catch(ve){iS(a,"throw",ve)}if(typeof y=="object"&&y&&tS(Ld,y))return y}return new wC(!1)},sS=Hs("iterator"),nS=!1;try{var s=0,n={next:function(){return{done:!!s++}},return:function(){nS=!0}};n[sS]=function(){return this},Array.from(n,function(){throw 2})}catch{}var g=function(A,e){try{if(!e&&!nS)return!1}catch{return!1}var o=!1;try{var a={};a[sS]=function(){return{next:function(){return{done:o=!0}}}},A(a)}catch{}return o},u=SB,E=Rh.CONSTRUCTOR||!g(function(A){u.all(A).then(void 0,function(){})}),m=sA,D=Pi,M=Kr,T=DB,P=oS;_n({target:"Promise",stat:!0,forced:E},{all:function(A){var e=this,o=M.f(e),a=o.resolve,c=o.reject,d=T(function(){var C=D(e.resolve),y=[],S=0,k=1;P(A,function(V){var J=S++,gA=!1;k++,m(C,e,V).then(function(CA){gA||(gA=!0,y[J]=CA,--k||a(y))},c)}),--k||a(y)});return d.error&&c(d.value),o.promise}});var W=_n,iA=Rh.CONSTRUCTOR,EA=SB,RA=HA,kA=Ao,xA=Sr,LA=EA&&EA.prototype;if(W({target:"Promise",proto:!0,forced:iA,real:!0},{catch:function(A){return this.then(void 0,A)}}),kA(EA)){var SA=RA("Promise").prototype.catch;LA.catch!==SA&&xA(LA,"catch",SA,{unsafe:!0})}var OA=sA,JA=Pi,ae=Kr,se=DB,_i=oS;_n({target:"Promise",stat:!0,forced:E},{race:function(A){var e=this,o=ae.f(e),a=o.reject,c=se(function(){var d=JA(e.resolve);_i(A,function(C){OA(d,e,C).then(o.resolve,a)})});return c.error&&a(c.value),o.promise}});var Ti=Kr;_n({target:"Promise",stat:!0,forced:Rh.CONSTRUCTOR},{reject:function(A){var e=Ti.f(this);return(0,e.reject)(A),e.promise}});var Ft=sr,Ni=oo,cs=Kr,Se=function(A,e){if(Ft(A),Ni(e)&&e.constructor===A)return e;var o=cs.f(A);return(0,o.resolve)(e),o.promise},mt=_n,UA=Rh.CONSTRUCTOR,ri=Se;HA("Promise"),mt({target:"Promise",stat:!0,forced:UA},{resolve:function(A){return ri(this,A)}});var _s=_n,Gi=SB,Or=_,xi=HA,gr=Ao,Gt=eR,bt=Se,tE=Sr,ln=Gi&&Gi.prototype;if(_s({target:"Promise",proto:!0,real:!0,forced:!!Gi&&Or(function(){ln.finally.call({then:function(){}},function(){})})},{finally:function(A){var e=Gt(this,xi("Promise")),o=gr(A);return this.then(o?function(a){return bt(e,A()).then(function(){return a})}:A,o?function(a){return bt(e,A()).then(function(){throw a})}:A)}}),gr(Gi)){var Bo=xi("Promise").prototype.finally;ln.finally!==Bo&&tE(ln,"finally",Bo,{unsafe:!0})}var Il=oo,_C=re,Tr=Hs("match"),xg=function(A){var e;return Il(A)&&((e=A[Tr])!==void 0?!!e:_C(A)==="RegExp")},wI=_,ac=f.RegExp,nf=!wI(function(){var A=!0;try{ac(".","d")}catch{A=!1}var e={},o="",a=A?"dgimsy":"gimsy",c=function(y,S){Object.defineProperty(e,y,{get:function(){return o+=S,!0}})},d={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var C in A&&(d.hasIndices="d"),d)c(C,d[C]);return Object.getOwnPropertyDescriptor(ac.prototype,"flags").get.call(e)!==a||o!==a}),ap=sr,Va=function(){var A=ap(this),e="";return A.hasIndices&&(e+="d"),A.global&&(e+="g"),A.ignoreCase&&(e+="i"),A.multiline&&(e+="m"),A.dotAll&&(e+="s"),A.unicode&&(e+="u"),A.unicodeSets&&(e+="v"),A.sticky&&(e+="y"),e},Yl=sA,_I=Cs,iE=ce,Yg={correct:nf},dg=Va,rS=RegExp.prototype,LR=Yg.correct?function(A){return A.flags}:function(A){return Yg.correct||!iE(rS,A)||_I(A,"flags")?A.flags:Yl(dg,A)},UR=_,FR=f.RegExp,oN=UR(function(){var A=FR("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),NV=oN||UR(function(){return!FR("a","y").sticky}),$U=oN||UR(function(){var A=FR("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),gp={BROKEN_CARET:$U,MISSED_STICKY:NV,UNSUPPORTED_Y:oN},sN=Ki.f,nN=_,rN=f.RegExp,aN=nN(function(){var A=rN(".","s");return!(A.dotAll&&A.test(` -`)&&A.flags==="s")}),AF=_,GV=f.RegExp,eF=AF(function(){var A=GV("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),rf=G,gN=f,af=je,cN=wr,bV=hD,kV=rg,LV=xa,UV=Mc.f,OR=ce,tF=xg,lN=Er,iF=LR,aS=gp,IN=function(A,e,o){o in A||sN(A,o,{configurable:!0,get:function(){return e[o]},set:function(a){e[o]=a}})},PR=Sr,xR=_,FV=Cs,uN=un.enforce,YR=Lm,oF=aN,gf=eF,OV=Hs("match"),TB=gN.RegExp,cf=TB.prototype,PV=gN.SyntaxError,sF=af(cf.exec),lf=af("".charAt),nF=af("".replace),EN=af("".indexOf),dN=af("".slice),xV=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,oE=/a/g,NB=/a/g,rF=new TB(oE)!==oE,aF=aS.MISSED_STICKY,YV=aS.UNSUPPORTED_Y,CN=rf&&(!rF||aF||oF||gf||xR(function(){return NB[OV]=!1,TB(oE)!==oE||TB(NB)===NB||String(TB(oE,"i"))!=="/a/i"}));if(cN("RegExp",CN)){for(var GB=function(A,e){var o,a,c,d,C,y,S=OR(cf,this),k=tF(A),V=e===void 0,J=[],gA=A;if(!S&&k&&V&&A.constructor===GB)return A;if((k||OR(cf,A))&&(A=A.source,V&&(e=iF(gA))),A=A===void 0?"":lN(A),e=e===void 0?"":lN(e),gA=A,oF&&"dotAll"in oE&&(a=!!e&&EN(e,"s")>-1)&&(e=nF(e,/s/g,"")),o=e,aF&&"sticky"in oE&&(c=!!e&&EN(e,"y")>-1)&&YV&&(e=nF(e,/y/g,"")),gf&&(d=function(CA){for(var MA,$A=CA.length,Be=0,Ye="",ve=[],yi=LV(null),Ge=!1,Bt=!1,hi=0,Di="";Be<=$A;Be++){if((MA=lf(CA,Be))==="\\")MA+=lf(CA,++Be);else if(MA==="]")Ge=!1;else if(!Ge)switch(!0){case MA==="[":Ge=!0;break;case MA==="(":if(Ye+=MA,dN(CA,Be+1,Be+3)==="?:")continue;sF(xV,dN(CA,Be+1))&&(Be+=2,Bt=!0),hi++;continue;case(MA===">"&&Bt):if(Di===""||FV(yi,Di))throw new PV("Invalid capture group name");yi[Di]=!0,ve[ve.length]=[Di,hi],Bt=!1,Di="";continue}Bt?Di+=MA:Ye+=MA}return[Ye,ve]}(A),A=d[0],J=d[1]),C=bV(TB(A,e),S?this:cf,GB),(a||c||J.length)&&(y=uN(C),a&&(y.dotAll=!0,y.raw=GB(function(CA){for(var MA,$A=CA.length,Be=0,Ye="",ve=!1;Be<=$A;Be++)(MA=lf(CA,Be))!=="\\"?ve||MA!=="."?(MA==="["?ve=!0:MA==="]"&&(ve=!1),Ye+=MA):Ye+="[\\s\\S]":Ye+=MA+lf(CA,++Be);return Ye}(A),o)),c&&(y.sticky=!0),J.length&&(y.groups=J)),A!==gA)try{kV(C,"source",gA===""?"(?:)":gA)}catch{}return C},hN=UV(TB),BN=0;hN.length>BN;)IN(GB,TB,hN[BN++]);cf.constructor=GB,GB.prototype=cf,PR(gN,"RegExp",GB,{constructor:!0})}YR("RegExp");var If=sA,cp=je,bB=Er,VV=Va,uf=gp,gF=xa,cF=un.get,JV=aN,HV=eF,qV=Ls("native-string-replace",String.prototype.replace),lp=RegExp.prototype.exec,QN=lp,KV=cp("".charAt),jV=cp("".indexOf),lF=cp("".replace),gS=cp("".slice),pN=function(){var A=/a/,e=/b*/g;return If(lp,A,"a"),If(lp,e,"a"),A.lastIndex!==0||e.lastIndex!==0}(),IF=uf.BROKEN_CARET,mN=/()??/.exec("")[1]!==void 0;(pN||mN||IF||JV||HV)&&(QN=function(A){var e,o,a,c,d,C,y,S=this,k=cF(S),V=bB(A),J=k.raw;if(J)return J.lastIndex=S.lastIndex,e=If(QN,J,V),S.lastIndex=J.lastIndex,e;var gA=k.groups,CA=IF&&S.sticky,MA=If(VV,S),$A=S.source,Be=0,Ye=V;if(CA&&(MA=lF(MA,"y",""),jV(MA,"g")===-1&&(MA+="g"),Ye=gS(V,S.lastIndex),S.lastIndex>0&&(!S.multiline||S.multiline&&KV(V,S.lastIndex-1)!==` -`)&&($A="(?: "+$A+")",Ye=" "+Ye,Be++),o=new RegExp("^(?:"+$A+")",MA)),mN&&(o=new RegExp("^"+$A+"$(?!\\s)",MA)),pN&&(a=S.lastIndex),c=If(lp,CA?o:S,Ye),CA?c?(c.input=gS(c.input,Be),c[0]=gS(c[0],Be),c.index=S.lastIndex,S.lastIndex+=c[0].length):S.lastIndex=0:pN&&c&&(S.lastIndex=S.global?c.index+c[0].length:a),mN&&c&&c.length>1&&If(qV,c[0],o,function(){for(d=1;d0;(a>>>=1)&&(e+=e))1&a&&(o+=e);return o},Ef=Eo,df=dF(zV),qR=dF("".slice),CF=Math.ceil,fN=function(A){return function(e,o,a){var c,d,C=HR(Ef(e)),y=WV(o),S=C.length,k=a===void 0?" ":HR(a);return y<=S||k===""?C:((d=df(k,CF((c=y-S)/k.length))).length>c&&(d=qR(d,0,c)),A?C+d:d+C)}},yN={start:fN(!1)},DN=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(nt),ZV=yN.start;_n({target:"String",proto:!0,forced:DN},{padStart:function(A){return ZV(this,A,arguments.length>1?arguments[1]:void 0)}});var hF=sA,SN=Sr,BF=cS,MN=_,vN=Hs,XV=vN("species"),QF=RegExp.prototype,KR=je,$V=Xr,Cf=Er,hf=Eo,RN=KR("".charAt),pF=KR("".charCodeAt),AJ=KR("".slice),mF=function(A){return function(e,o){var a,c,d=Cf(hf(e)),C=$V(o),y=d.length;return C<0||C>=y?A?"":void 0:(a=pF(d,C))<55296||a>56319||C+1===y||(c=pF(d,C+1))<56320||c>57343?A?RN(d,C):a:A?AJ(d,C,C+2):c-56320+(a-55296<<10)+65536}},jR={codeAt:mF(!1),charAt:mF(!0)},eJ=jR.charAt,WR=je,tJ=as,iJ=Math.floor,wN=WR("".charAt),_N=WR("".replace),TN=WR("".slice),oJ=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sJ=/\$([$&'`]|\d{1,2})/g,fF=function(A,e,o,a,c,d){var C=o+A.length,y=a.length,S=sJ;return c!==void 0&&(c=tJ(c),S=oJ),_N(d,S,function(k,V){var J;switch(wN(V,0)){case"$":return"$";case"&":return A;case"`":return TN(e,0,o);case"'":return TN(e,C);case"<":J=c[TN(V,1,-1)];break;default:var gA=+V;if(gA===0)return k;if(gA>y){var CA=iJ(gA/10);return CA===0?k:CA<=y?a[CA-1]===void 0?wN(V,1):a[CA-1]+wN(V,1):k}J=a[gA-1]}return J===void 0?"":J})},yF=sA,nJ=sr,DF=Ao,rJ=re,SF=cS,aJ=TypeError,gJ=_d,MF=sA,zR=je,cJ=function(A,e,o,a){var c=vN(A),d=!MN(function(){var k={};return k[c]=function(){return 7},""[A](k)!==7}),C=d&&!MN(function(){var k=!1,V=/a/,J;return V.exec=function(){return k=!0,null},V[c](""),!k});if(!d||!C||o){var y=/./[c],S=e(c,""[A],function(k,V,J,gA,CA){var MA=V.exec;return MA===BF||MA===QF.exec?d&&!CA?{done:!0,value:hF(y,V,J,gA)}:{done:!0,value:hF(k,J,V,gA)}:{done:!1}});SN(String.prototype,A,S[0]),SN(QF,c,S[1])}},lJ=_,IJ=sr,vF=Ao,uJ=oo,EJ=Xr,RF=qn,Ip=Er,ZR=Eo,wF=function(A,e,o){return e+(o?eJ(A,e).length:1)},XR=en,_F=fF,TF=LR,dJ=function(A,e){var o=A.exec;if(DF(o)){var a=yF(o,A,e);return a!==null&&nJ(a),a}if(rJ(A)==="RegExp")return yF(SF,A,e);throw new aJ("RegExp#exec called on incompatible receiver")},$R=Hs("replace"),NN=Math.max,CJ=Math.min,NF=zR([].concat),GN=zR([].push),Aw=zR("".indexOf),GF=zR("".slice),hJ=function(A){return A===void 0?A:String(A)},BJ="a".replace(/./,"$0")==="$0",bF=!!/./[$R]&&/./[$R]("a","$0")==="",QJ=!lJ(function(){var A=/./;return A.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(A,"$")!=="7"});cJ("replace",function(A,e,o){var a=bF?"$":"$0";return[function(c,d){var C=ZR(this),y=uJ(c)?XR(c,$R):void 0;return y?MF(y,c,C,d):MF(e,Ip(C),c,d)},function(c,d){var C=IJ(this),y=Ip(c);if(typeof d=="string"&&Aw(d,a)===-1&&Aw(d,"$<")===-1){var S=o(e,C,y,d);if(S.done)return S.value}var k=vF(d);k||(d=Ip(d));var V,J=Ip(TF(C)),gA=Aw(J,"g")!==-1;gA&&(V=Aw(J,"u")!==-1,C.lastIndex=0);for(var CA,MA=[];(CA=dJ(C,y))!==null&&(GN(MA,CA),gA);)Ip(CA[0])===""&&(C.lastIndex=wF(y,RF(C.lastIndex),V));for(var $A="",Be=0,Ye=0;Ye=Be&&($A+=GF(y,Be,Ge)+ve,Be=Ge+yi.length)}return $A+GF(y,Be)}]},!QJ||!BJ||bF);var ew=` -\v\f\r                 \u2028\u2029\uFEFF`,pJ=Eo,mJ=Er,bN=ew,kN=je("".replace),kF=RegExp("^["+bN+"]+"),fJ=RegExp("(^|[^"+bN+"])["+bN+"]+$"),yJ=function(A){return function(e){var o=mJ(pJ(e));return 1&A&&(o=kN(o,kF,"")),2&A&&(o=kN(o,fJ,"$1")),o}},DJ={trim:yJ(3)},SJ=zg.PROPER,MJ=_,LF=ew,vJ=DJ.trim;_n({target:"String",proto:!0,forced:function(A){return MJ(function(){return!!LF[A]()||"​…᠎"[A]()!=="​…᠎"||SJ&&LF[A].name!==A})}("trim")},{trim:function(){return vJ(this)}});var cu,Bf,tw,LN={exports:{}},RJ=Mr,UN=G,TI=f,UF=Ao,FF=oo,Qf=Cs,iw=ur,FN=Jn,ON=rg,PN=Sr,OF=Lg,wJ=ce,xN=fI,up=oA,_J=Hs,TJ=pc,YN=un.enforce,kh=TI.Int8Array,pf=kh&&kh.prototype,PF=TI.Uint8ClampedArray,xF=PF&&PF.prototype,TC=kh&&xN(kh),Ud=pf&&xN(pf),NJ=Object.prototype,VN=TI.TypeError,YF=_J("toStringTag"),JN=TJ("TYPED_ARRAY_TAG"),lS="TypedArrayConstructor",Fd=RJ&&!!up&&iw(TI.opera)!=="Opera",VF=!1,kB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},JF={BigInt64Array:8,BigUint64Array:8},ow=function(A){if(!FF(A))return!1;var e=iw(A);return Qf(kB,e)||Qf(JF,e)};for(cu in kB)(tw=(Bf=TI[cu])&&Bf.prototype)?YN(tw)[lS]=Bf:Fd=!1;for(cu in JF)(tw=(Bf=TI[cu])&&Bf.prototype)&&(YN(tw)[lS]=Bf);if((!Fd||!UF(TC)||TC===Function.prototype)&&(TC=function(){throw new VN("Incorrect invocation")},Fd))for(cu in kB)TI[cu]&&up(TI[cu],TC);if((!Fd||!Ud||Ud===NJ)&&(Ud=TC.prototype,Fd))for(cu in kB)TI[cu]&&up(TI[cu].prototype,Ud);if(Fd&&xN(xF)!==Ud&&up(xF,Ud),UN&&!Qf(Ud,YF))for(cu in VF=!0,OF(Ud,YF,{configurable:!0,get:function(){return FF(this)?this[JN]:void 0}}),kB)TI[cu]&&ON(TI[cu],JN,cu);var Od={NATIVE_ARRAY_BUFFER_VIEWS:Fd,TYPED_ARRAY_TAG:VF&&JN,aTypedArray:function(A){if(ow(A))return A;throw new VN("Target is not a typed array")},aTypedArrayConstructor:function(A){if(UF(A)&&(!up||wJ(TC,A)))return A;throw new VN(FN(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,e,o,a){if(UN){if(o)for(var c in kB){var d=TI[c];if(d&&Qf(d.prototype,A))try{delete d.prototype[A]}catch{try{d.prototype[A]=e}catch{}}}Ud[A]&&!o||PN(Ud,A,o?e:Fd&&pf[A]||e,a)}},exportTypedArrayStaticMethod:function(A,e,o){var a,c;if(UN){if(up){if(o){for(a in kB)if((c=TI[a])&&Qf(c,A))try{delete c[A]}catch{}}if(TC[A]&&!o)return;try{return PN(TC,A,o?e:Fd&&TC[A]||e)}catch{}}for(a in kB)!(c=TI[a])||c[A]&&!o||PN(c,A,e)}},isTypedArray:ow,TypedArray:TC,TypedArrayPrototype:Ud},HN=f,IS=_,sw=g,GJ=Od.NATIVE_ARRAY_BUFFER_VIEWS,HF=HN.ArrayBuffer,Ep=HN.Int8Array,qF=!GJ||!IS(function(){Ep(1)})||!IS(function(){new Ep(-1)})||!sw(function(A){new Ep,new Ep(null),new Ep(1.5),new Ep(A)},!0)||IS(function(){return new Ep(new HF(2),1,void 0).length!==1}),bJ=oo,kJ=Math.floor,KF=Number.isInteger||function(A){return!bJ(A)&&isFinite(A)&&kJ(A)===A},LJ=Xr,UJ=RangeError,nw=function(A){var e=LJ(A);if(e<0)throw new UJ("The argument can't be less than 0");return e},FJ=RangeError,jF=function(A,e){var o=nw(A);if(o%e)throw new FJ("Wrong offset");return o},OJ=Math.round,WF=ur,PJ=yn,xJ=TypeError,rw=function(A){var e=PJ(A,"number");if(typeof e=="number")throw new xJ("Can't convert number to bigint");return BigInt(e)},zF=Ag,ZF=sA,YJ=Qh,VJ=as,XF=Fa,$F=WE,JJ=bh,AO=ZD,eO=function(A){var e=WF(A);return e==="BigInt64Array"||e==="BigUint64Array"},HJ=Od.aTypedArrayConstructor,qJ=rw,aw=function(A){var e,o,a,c,d,C,y,S,k=YJ(this),V=VJ(A),J=arguments.length,gA=J>1?arguments[1]:void 0,CA=gA!==void 0,MA=JJ(V);if(MA&&!AO(MA))for(S=(y=$F(V,MA)).next,V=[];!(C=ZF(S,y)).done;)V.push(C.value);for(CA&&J>2&&(gA=zF(gA,arguments[2])),o=XF(V),a=new(HJ(k))(o),c=eO(a),e=0;o>e;e++)d=CA?gA(V[e],e):V[e],a[e]=c?qJ(d):+d;return a},qN=ea,KN=_D,KJ=oo,jJ=Hs("species"),tO=Array,WJ=function(A){var e;return qN(A)&&(e=A.constructor,(KN(e)&&(e===tO||qN(e.prototype))||KJ(e)&&(e=e[jJ])===null)&&(e=void 0)),e===void 0?tO:e},iO=Ag,zJ=gt,ZJ=as,oO=Fa,XJ=function(A,e){return new(WJ(A))(e===0?0:e)},jN=je([].push),sO=function(A){var e=A===1,o=A===2,a=A===3,c=A===4,d=A===6,C=A===7,y=A===5||d;return function(S,k,V,J){for(var gA,CA,MA=ZJ(S),$A=zJ(MA),Be=oO($A),Ye=iO(k,V),ve=0,yi=J||XJ,Ge=e?yi(S,Be):o||C?yi(S,0):void 0;Be>ve;ve++)if((y||ve in $A)&&(CA=Ye(gA=$A[ve],ve,MA),A))if(e)Ge[ve]=CA;else if(CA)switch(A){case 3:return!0;case 5:return gA;case 6:return ve;case 2:jN(Ge,gA)}else switch(A){case 4:return!1;case 7:jN(Ge,gA)}return d?-1:a||c?c:Ge}},nO={forEach:sO(0)},$J=Fa,rO=_n,aO=f,gO=sA,cO=G,AH=qF,uS=Od,lO=bm,IO=MI,eH=Ce,LB=rg,tH=KF,iH=qn,uO=ym,WN=jF,EO=function(A){var e=OJ(A);return e<0?0:e>255?255:255&e},zN=$,dp=Cs,oH=ur,ZN=oo,XN=Do,sH=xa,$N=ce,gw=oA,nH=Mc.f,dO=aw,CO=nO.forEach,cw=Lm,rH=Lg,hO=Ki,BO=w,QO=function(A,e,o){for(var a=0,c=arguments.length>2?o:$J(e),d=new A(c);c>a;)d[a]=e[a++];return d},aH=hD,AG=un.get,gH=un.set,Cp=un.enforce,pO=hO.f,cH=BO.f,eG=aO.RangeError,mO=lO.ArrayBuffer,lH=mO.prototype,IH=lO.DataView,mf=uS.NATIVE_ARRAY_BUFFER_VIEWS,fO=uS.TYPED_ARRAY_TAG,yO=uS.TypedArray,ES=uS.TypedArrayPrototype,dS=uS.isTypedArray,hp="BYTES_PER_ELEMENT",lw="Wrong length",Iw=function(A,e){rH(A,e,{configurable:!0,get:function(){return AG(this)[e]}})},DO=function(A){var e;return $N(lH,A)||(e=oH(A))==="ArrayBuffer"||e==="SharedArrayBuffer"},tG=function(A,e){return dS(A)&&!XN(e)&&e in A&&tH(+e)&&e>=0},uw=function(A,e){return e=zN(e),tG(A,e)?eH(2,A[e]):cH(A,e)},SO=function(A,e,o){return e=zN(e),!(tG(A,e)&&ZN(o)&&dp(o,"value"))||dp(o,"get")||dp(o,"set")||o.configurable||dp(o,"writable")&&!o.writable||dp(o,"enumerable")&&!o.enumerable?pO(A,e,o):(A[e]=o.value,A)};cO?(mf||(BO.f=uw,hO.f=SO,Iw(ES,"buffer"),Iw(ES,"byteOffset"),Iw(ES,"byteLength"),Iw(ES,"length")),rO({target:"Object",stat:!0,forced:!mf},{getOwnPropertyDescriptor:uw,defineProperty:SO}),LN.exports=function(A,e,o){var a=A.match(/\d+/)[0]/8,c=A+(o?"Clamped":"")+"Array",d="get"+A,C="set"+A,y=aO[c],S=y,k=S&&S.prototype,V={},J=function(CA,MA){pO(CA,MA,{get:function(){return function($A,Be){var Ye=AG($A);return Ye.view[d](Be*a+Ye.byteOffset,!0)}(this,MA)},set:function($A){return function(Be,Ye,ve){var yi=AG(Be);yi.view[C](Ye*a+yi.byteOffset,o?EO(ve):ve,!0)}(this,MA,$A)},enumerable:!0})};mf?AH&&(S=e(function(CA,MA,$A,Be){return IO(CA,k),aH(ZN(MA)?DO(MA)?Be!==void 0?new y(MA,WN($A,a),Be):$A!==void 0?new y(MA,WN($A,a)):new y(MA):dS(MA)?QO(S,MA):gO(dO,S,MA):new y(uO(MA)),CA,S)}),gw&&gw(S,yO),CO(nH(y),function(CA){CA in S||LB(S,CA,y[CA])}),S.prototype=k):(S=e(function(CA,MA,$A,Be){IO(CA,k);var Ye,ve,yi,Ge=0,Bt=0;if(ZN(MA)){if(!DO(MA))return dS(MA)?QO(S,MA):gO(dO,S,MA);Ye=MA,Bt=WN($A,a);var hi=MA.byteLength;if(Be===void 0){if(hi%a)throw new eG(lw);if((ve=hi-Bt)<0)throw new eG(lw)}else if((ve=iH(Be)*a)+Bt>hi)throw new eG(lw);yi=ve/a}else yi=uO(MA),Ye=new mO(ve=yi*a);for(gH(CA,{buffer:Ye,byteOffset:Bt,byteLength:ve,length:yi,view:new IH(Ye)});Ge1?arguments[1]:void 0,e>2?arguments[2]:void 0)},iG(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,Od.exportTypedArrayStaticMethod)("from",aw,qF);var RO=f,wO=sA,sG=Od,_O=Fa,BH=jF,QH=as,TO=_,pH=RO.RangeError,nG=RO.Int8Array,rG=nG&&nG.prototype,aG=rG&&rG.set,gG=sG.aTypedArray,NO=sG.exportTypedArrayMethod,Ew=!TO(function(){var A=new Uint8ClampedArray(2);return wO(aG,A,{length:1,0:3},1),A[1]!==3}),GO=Ew&&sG.NATIVE_ARRAY_BUFFER_VIEWS&&TO(function(){var A=new nG(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});NO("set",function(A){gG(this);var e=BH(arguments.length>1?arguments[1]:void 0,1),o=QH(A);if(Ew)return wO(aG,this,o,e);var a=this.length,c=_O(o),d=0;if(c+e>a)throw new pH("Wrong length");for(;d0&&1/a<0?1:-1:o>a}}(A))},!dw||CG);var kO=_n,hG=sA,hS=je,BG=Eo,QG=Ao,yH=oo,LO=xg,BS=Er,DH=en,QS=LR,UO=fF,SH=Hs("replace"),FO=TypeError,Pd=hS("".indexOf);hS("".replace);var pS=hS("".slice),MH=Math.max;kO({target:"String",proto:!0},{replaceAll:function(A,e){var o,a,c,d,C,y,S,k,V,J=BG(this),gA=0,CA="";if(yH(A)){if(LO(A)&&(o=BS(BG(QS(A))),!~Pd(o,"g")))throw new FO("`.replaceAll` does not allow non-global regexes");if(a=DH(A,SH))return hG(a,A,J,e)}for(c=BS(J),d=BS(A),(C=QG(e))||(e=BS(e)),y=d.length,S=MH(1,y),k=Pd(c,d);k!==-1;)V=C?BS(e(d,k,c)):UO(d,c,k,[],void 0,e),CA+=pS(c,gA,k)+V,gA=k+y,k=k+S>c.length?-1:Pd(c,d,k+S);return gA1?arguments[1]:void 0)},PO=f,xO=pG,wH=mG,hw=RH,_H=rg,YO=function(A){if(A&&A.forEach!==hw)try{_H(A,"forEach",hw)}catch{A.forEach=hw}};for(var fG in xO)xO[fG]&&YO(PO[fG]&&PO[fG].prototype);YO(wH);var Bw=f,VO=pG,TH=mG,mS=ji,fS=rg,NH=Ya,yG=Hs("iterator"),DG=mS.values,JO=function(A,e){if(A){if(A[yG]!==DG)try{fS(A,yG,DG)}catch{A[yG]=DG}if(NH(A,e,!0),VO[e]){for(var o in mS)if(A[o]!==mS[o])try{fS(A,o,mS[o])}catch{A[o]=mS[o]}}}};for(var SG in VO)JO(Bw[SG]&&Bw[SG].prototype,SG);JO(TH,"DOMTokenList");var MG=MC.clear;_n({global:!0,bind:!0,enumerable:!0,forced:f.clearImmediate!==MG},{clearImmediate:MG});var yS=f,GH=_d,bH=Ao,kH=Hr,LH=nt,UH=le,FH=CB,vG=yS.Function,OH=/MSIE .\./.test(LH)||kH==="BUN"&&function(){var A=yS.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),HO=_n,qO=f,Qw=MC.set,PH=function(A,e){var o=1;return OH?function(a,c){var d=FH(arguments.length,1)>o,C=bH(a)?a:vG(a),y=d?UH(arguments,o):[],S=d?function(){GH(C,this,y)}:C;return A(S)}:A},RG=qO.setImmediate?PH(Qw):Qw;HO({global:!0,bind:!0,enumerable:!0,forced:qO.setImmediate!==RG},{setImmediate:RG});var Lh=jR.charAt,xH=Er,pw=un,YH=Ee,KO=We,jO="String Iterator",VH=pw.set,WO=pw.getterFor(jO);YH(String,"String",function(A){VH(this,{type:jO,string:xH(A),index:0})},function(){var A,e=WO(this),o=e.string,a=e.index;return a>=o.length?KO(void 0,!0):(A=Lh(o,a),e.index+=A.length,KO(A,!1))});var JH=_,HH=G,qH=Hs("iterator"),zO=!JH(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),e=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),a="";return A.pathname="c%20d",e.forEach(function(c,d){e.delete("b"),a+=d+c}),o.delete("a",2),o.delete("b",void 0),!e.size&&!HH||!e.sort||A.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[qH]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||a!=="a1c3"||new URL("https://x",void 0).host!=="x"}),ZO=G,KH=je,wG=sA,_G=_,TG=bl,jH=vc,WH=mA,zH=as,XO=gt,Bp=Object.assign,$O=Object.defineProperty,AP=KH([].concat),ZH=!Bp||_G(function(){if(ZO&&Bp({b:1},Bp($O({},"a",{enumerable:!0,get:function(){$O(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},e={},o=Symbol("assign detection"),a="abcdefghijklmnopqrst";return A[o]=7,a.split("").forEach(function(c){e[c]=c}),Bp({},A)[o]!==7||TG(Bp({},e)).join("")!==a})?function(A,e){for(var o=zH(A),a=arguments.length,c=1,d=jH.f,C=WH.f;a>c;)for(var y,S=XO(arguments[c++]),k=d?AP(TG(S),d(S)):TG(S),V=k.length,J=0;V>J;)y=k[J++],ZO&&!wG(C,S,y)||(o[y]=S[y]);return o}:Bp,XH=sr,$H=eS,Aq=G,eq=Ki,eP=Ce,tq=Ag,DS=sA,tP=as,iP=function(A,e,o,a){try{return a?e(XH(o)[0],o[1]):e(o)}catch(c){$H(A,"throw",c)}},NG=ZD,iq=_D,oq=Fa,SS=function(A,e,o){Aq?eq.f(A,e,eP(0,o)):A[e]=o},GG=WE,sq=bh,oP=Array,UB=je,bG=2147483647,sP=/[^\0-\u007E]/,kG=/[.\u3002\uFF0E\uFF61]/g,nP="Overflow: input needs wider integers to process",rP=RangeError,nq=UB(kG.exec),FB=Math.floor,mw=String.fromCharCode,fw=UB("".charCodeAt),sE=UB([].join),OB=UB([].push),pa=UB("".replace),aP=UB("".split),rq=UB("".toLowerCase),gP=function(A){return A+22+75*(A<26)},LG=function(A,e,o){var a=0;for(A=o?FB(A/700):A>>1,A+=FB(A/e);A>455;)A=FB(A/35),a+=36;return FB(a+36*A/(A+38))},aq=function(A){var e=[];A=function(Ye){for(var ve=[],yi=0,Ge=Ye.length;yi=55296&&Bt<=56319&&yi=d&&aFB((bG-C)/J))throw new rP(nP);for(C+=(V-d)*J,d=V,o=0;obG)throw new rP(nP);if(a===d){for(var gA=C,CA=36;;){var MA=CA<=y?1:CA>=y+26?26:CA-y;if(gAc;){if(e=+arguments[c++],gq(e,1114111)!==e)throw new cq(e+" is not a valid code point");o[c]=e<65536?Uh(e):Uh(55296+((e-=65536)>>10),e%1024+56320)}return vS(o,"")}});var Qp=_n,Df=f,pp=cR,UG=HA,Fs=sA,nE=je,Sf=G,FG=zO,lP=Sr,lq=Lg,Iq=nu,uq=Ya,Eq=xE,RS=un,IP=MI,OG=Ao,dq=Cs,Cq=Ag,hq=ur,Bq=sr,uP=oo,Vl=Er,Qq=xa,EP=Ce,dP=WE,pq=bh,yw=We,Mf=CB,mq=vt,fq=Hs("iterator"),mp="URLSearchParams",PG=mp+"Iterator",CP=RS.set,ul=RS.getterFor(mp),Fh=RS.getterFor(PG),hP=pp("fetch"),vf=pp("Request"),wS=pp("Headers"),xG=vf&&vf.prototype,BP=wS&&wS.prototype,QP=Df.TypeError,yq=Df.encodeURIComponent,Dq=String.fromCharCode,Sq=UG("String","fromCodePoint"),Mq=parseInt,Dw=nE("".charAt),Sw=nE([].join),Oh=nE([].push),pP=nE("".replace),vq=nE([].shift),mP=nE([].splice),fP=nE("".split),yP=nE("".slice),YG=nE(/./.exec),DP=/\+/g,Rq=/^[0-9a-f]+$/i,SP=function(A,e){var o=yP(A,e,e+2);return YG(Rq,o)?Mq(o,16):NaN},wq=function(A){for(var e=0,o=128;o>0&&A&o;o>>=1)e++;return e},_q=function(A){var e=null;switch(A.length){case 1:e=A[0];break;case 2:e=(31&A[0])<<6|63&A[1];break;case 3:e=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:e=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return e>1114111?null:e},MP=function(A){for(var e=(A=pP(A,DP," ")).length,o="",a=0;ae){o+="%",a++;continue}var d=SP(A,a+1);if(d!=d){o+=c,a++;continue}a+=2;var C=wq(d);if(C===0)c=Dq(d);else{if(C===1||C>4){o+="�",a++;continue}for(var y=[d],S=1;Se||Dw(A,a)!=="%");){var k=SP(A,a+1);if(k!=k){a+=3;break}if(k>191||k<128)break;Oh(y,k),a+=2,S++}if(y.length!==C){o+="�";continue}var V=_q(y);V===null?o+="�":c=Sq(V)}}o+=c,a++}return o},Tq=/[!'()~]|%20/g,Nq={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Gq=function(A){return Nq[A]},vP=function(A){return pP(yq(A),Tq,Gq)},VG=Eq(function(A,e){CP(this,{type:PG,target:ul(A).entries,index:0,kind:e})},mp,function(){var A=Fh(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,yw(void 0,!0);var a=e[o];switch(A.kind){case"keys":return yw(a.key,!1);case"values":return yw(a.value,!1)}return yw([a.key,a.value],!1)},!0),RP=function(A){this.entries=[],this.url=null,A!==void 0&&(uP(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?Dw(A,0)==="?"?yP(A,1):A:Vl(A)))};RP.prototype={type:mp,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var e,o,a,c,d,C,y,S=this.entries,k=pq(A);if(k)for(o=(e=dP(A,k)).next;!(a=Fs(o,e)).done;){if(d=(c=dP(Bq(a.value))).next,(C=Fs(d,c)).done||(y=Fs(d,c)).done||!Fs(d,c).done)throw new QP("Expected sequence with length 2");Oh(S,{key:Vl(C.value),value:Vl(y.value)})}else for(var V in A)dq(A,V)&&Oh(S,{key:V,value:Vl(A[V])})},parseQuery:function(A){if(A)for(var e,o,a=this.entries,c=fP(A,"&"),d=0;d0?arguments[0]:void 0));Sf||(this.size=A.entries.length)},fp=Rf.prototype;if(Iq(fp,{append:function(A,e){var o=ul(this);Mf(arguments.length,2),Oh(o.entries,{key:Vl(A),value:Vl(e)}),Sf||this.size++,o.updateURL()},delete:function(A){for(var e=ul(this),o=Mf(arguments.length,1),a=e.entries,c=Vl(A),d=o<2?void 0:arguments[1],C=d===void 0?d:Vl(d),y=0;yo.key?1:-1}),A.updateURL()},forEach:function(A){for(var e,o=ul(this).entries,a=Cq(A,arguments.length>1?arguments[1]:void 0),c=0;c1?wP(arguments[1]):{})}}),OG(vf)){var HG=function(A){return IP(this,xG),new vf(A,arguments.length>1?wP(arguments[1]):{})};xG.constructor=HG,HG.prototype=xG,Qp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:HG})}}var rE,kq=_n,qG=G,_P=zO,KG=f,TP=Ag,zE=je,Mw=Sr,ZE=Lg,Lq=MI,jG=Cs,WG=ZH,PB=function(A){var e=tP(A),o=iq(this),a=arguments.length,c=a>1?arguments[1]:void 0,d=c!==void 0;d&&(c=tq(c,a>2?arguments[2]:void 0));var C,y,S,k,V,J,gA=sq(e),CA=0;if(!gA||this===oP&&NG(gA))for(C=oq(e),y=o?new this(C):oP(C);C>CA;CA++)J=d?c(e[CA],CA):e[CA],SS(y,CA,J);else for(y=o?new this:[],V=(k=GG(e,gA)).next;!(S=DS(V,k)).done;CA++)J=d?iP(k,c,[S.value,CA],!0):S.value,SS(y,CA,J);return y.length=CA,y},xd=le,zG=jR.codeAt,Uq=function(A){var e,o,a=[],c=aP(pa(rq(A),kG,"."),".");for(e=0;e?@[\\\]^|]/,Kq=/[\0\t\n\r #/:<>?@[\\\]^|]/,jq=/^[\u0000-\u0020]+/,Wq=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,zq=/[\t\n\r]/g,Tf=function(A){var e,o,a,c;if(typeof A=="number"){for(e=[],o=0;o<4;o++)Vq(e,A%256),A=xh(A/256);return _S(e,".")}if(typeof A=="object"){for(e="",a=function(d){for(var C=null,y=1,S=null,k=0,V=0;V<8;V++)d[V]!==0?(k>y&&(C=S,y=k),S=null,k=0):(S===null&&(S=V),++k);return k>y?S:C}(A),o=0;o<8;o++)c&&A[o]===0||(c&&(c=!1),a===o?(e+=o?":":"::",c=!0):(e+=Yq(A[o],16),o<7&&(e+=":")));return"["+e+"]"}return A},Nf={},OP=WG({},Nf,{" ":1,'"':1,"<":1,">":1,"`":1}),tb=WG({},OP,{"#":1,"?":1,"{":1,"}":1}),YB=WG({},tb,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Vd=function(A,e){var o=zG(A,0);return o>32&&o<127&&!jG(e,A)?A:encodeURIComponent(A)},Yh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Gf=function(A,e){var o;return A.length===2&&Yd(TS,XE(A,0))&&((o=XE(A,1))===":"||!e&&o==="|")},ib=function(A){var e;return A.length>1&&Gf(yp(A,0,2))&&(A.length===2||(e=XE(A,2))==="/"||e==="\\"||e==="?"||e==="#")},NS=function(A){return A==="."||Tw(A)==="%2e"},PP=function(A){return(A=Tw(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},aE={},lu={},VB={},NC={},JB={},bw={},xP={},GS={},kw={},Lw={},Uw={},Fw={},Ow={},Pw={},ob={},xw={},bf={},GC={},bS={},Iu={},Jl={},Yw=function(A,e,o){var a,c,d,C=Ph(A);if(e){if(c=this.parse(C))throw new XG(c);this.searchParams=null}else{if(o!==void 0&&(a=new Yw(o,!0)),c=this.parse(C,null,a))throw new XG(c);(d=xq(new Pq)).bindURL(this),this.searchParams=d}};Yw.prototype={type:"URL",parse:function(A,e,o){var a,c,d,C,y=this,S=e||aE,k=0,V="",J=!1,gA=!1,CA=!1;for(A=Ph(A),e||(y.scheme="",y.username="",y.password="",y.host=null,y.port=null,y.path=[],y.query=null,y.fragment=null,y.cannotBeABaseURL=!1,A=ww(A,jq,""),A=ww(A,Wq,"$1")),A=ww(A,zq,""),a=PB(A);k<=a.length;){switch(c=a[k],S){case aE:if(!c||!Yd(TS,c)){if(e)return Ab;S=VB;continue}V+=Tw(c),S=lu;break;case lu:if(c&&(Yd(Jq,c)||c==="+"||c==="-"||c==="."))V+=Tw(c);else{if(c!==":"){if(e)return Ab;V="",S=VB,k=0;continue}if(e&&(y.isSpecial()!==jG(Yh,V)||V==="file"&&(y.includesCredentials()||y.port!==null)||y.scheme==="file"&&!y.host))return;if(y.scheme=V,e)return void(y.isSpecial()&&Yh[y.scheme]===y.port&&(y.port=null));V="",y.scheme==="file"?S=Pw:y.isSpecial()&&o&&o.scheme===y.scheme?S=NC:y.isSpecial()?S=GS:a[k+1]==="/"?(S=JB,k++):(y.cannotBeABaseURL=!0,_f(y.path,""),S=bS)}break;case VB:if(!o||o.cannotBeABaseURL&&c!=="#")return Ab;if(o.cannotBeABaseURL&&c==="#"){y.scheme=o.scheme,y.path=xd(o.path),y.query=o.query,y.fragment="",y.cannotBeABaseURL=!0,S=Jl;break}S=o.scheme==="file"?Pw:bw;continue;case NC:if(c!=="/"||a[k+1]!=="/"){S=bw;continue}S=kw,k++;break;case JB:if(c==="/"){S=Lw;break}S=GC;continue;case bw:if(y.scheme=o.scheme,c===rE)y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query=o.query;else if(c==="/"||c==="\\"&&y.isSpecial())S=xP;else if(c==="?")y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query="",S=Iu;else{if(c!=="#"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.path.length--,S=GC;continue}y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query=o.query,y.fragment="",S=Jl}break;case xP:if(!y.isSpecial()||c!=="/"&&c!=="\\"){if(c!=="/"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,S=GC;continue}S=Lw}else S=kw;break;case GS:if(S=kw,c!=="/"||XE(V,k+1)!=="/")continue;k++;break;case kw:if(c!=="/"&&c!=="\\"){S=Lw;continue}break;case Lw:if(c==="@"){J&&(V="%40"+V),J=!0,d=PB(V);for(var MA=0;MA65535)return Nw;y.port=y.isSpecial()&&Ye===Yh[y.scheme]?null:Ye,V=""}if(e)return;S=bf;continue}return Nw}V+=c;break;case Pw:if(y.scheme="file",c==="/"||c==="\\")S=ob;else{if(!o||o.scheme!=="file"){S=GC;continue}switch(c){case rE:y.host=o.host,y.path=xd(o.path),y.query=o.query;break;case"?":y.host=o.host,y.path=xd(o.path),y.query="",S=Iu;break;case"#":y.host=o.host,y.path=xd(o.path),y.query=o.query,y.fragment="",S=Jl;break;default:ib(_S(xd(a,k),""))||(y.host=o.host,y.path=xd(o.path),y.shortenPath()),S=GC;continue}}break;case ob:if(c==="/"||c==="\\"){S=xw;break}o&&o.scheme==="file"&&!ib(_S(xd(a,k),""))&&(Gf(o.path[0],!0)?_f(y.path,o.path[0]):y.host=o.host),S=GC;continue;case xw:if(c===rE||c==="/"||c==="\\"||c==="?"||c==="#"){if(!e&&Gf(V))S=GC;else if(V===""){if(y.host="",e)return;S=bf}else{if(C=y.parseHost(V))return C;if(y.host==="localhost"&&(y.host=""),e)return;V="",S=bf}continue}V+=c;break;case bf:if(y.isSpecial()){if(S=GC,c!=="/"&&c!=="\\")continue}else if(e||c!=="?")if(e||c!=="#"){if(c!==rE&&(S=GC,c!=="/"))continue}else y.fragment="",S=Jl;else y.query="",S=Iu;break;case GC:if(c===rE||c==="/"||c==="\\"&&y.isSpecial()||!e&&(c==="?"||c==="#")){if(PP(V)?(y.shortenPath(),c==="/"||c==="\\"&&y.isSpecial()||_f(y.path,"")):NS(V)?c==="/"||c==="\\"&&y.isSpecial()||_f(y.path,""):(y.scheme==="file"&&!y.path.length&&Gf(V)&&(y.host&&(y.host=""),V=XE(V,0)+":"),_f(y.path,V)),V="",y.scheme==="file"&&(c===rE||c==="?"||c==="#"))for(;y.path.length>1&&y.path[0]==="";)_w(y.path);c==="?"?(y.query="",S=Iu):c==="#"&&(y.fragment="",S=Jl)}else V+=Vd(c,tb);break;case bS:c==="?"?(y.query="",S=Iu):c==="#"?(y.fragment="",S=Jl):c!==rE&&(y.path[0]+=Vd(c,Nf));break;case Iu:e||c!=="#"?c!==rE&&(c==="'"&&y.isSpecial()?y.query+="%27":y.query+=c==="#"?"%23":Vd(c,Nf)):(y.fragment="",S=Jl);break;case Jl:c!==rE&&(y.fragment+=Vd(c,OP))}k++}},parseHost:function(A){var e,o,a;if(XE(A,0)==="["){if(XE(A,A.length-1)!=="]"||(e=function(c){var d,C,y,S,k,V,J,gA=[0,0,0,0,0,0,0,0],CA=0,MA=null,$A=0,Be=function(){return XE(c,$A)};if(Be()===":"){if(XE(c,1)!==":")return;$A+=2,MA=++CA}for(;Be();){if(CA===8)return;if(Be()!==":"){for(d=C=0;C<4&&Yd(UP,Be());)d=16*d+Rw(Be(),16),$A++,C++;if(Be()==="."){if(C===0||($A-=C,CA>6))return;for(y=0;Be();){if(S=null,y>0){if(!(Be()==="."&&y<4))return;$A++}if(!Yd(eb,Be()))return;for(;Yd(eb,Be());){if(k=Rw(Be(),10),S===null)S=k;else{if(S===0)return;S=10*S+k}if(S>255)return;$A++}gA[CA]=256*gA[CA]+S,++y!==2&&y!==4||CA++}if(y!==4)return;break}if(Be()===":"){if($A++,!Be())return}else if(Be())return;gA[CA++]=d}else{if(MA!==null)return;$A++,MA=++CA}}if(MA!==null)for(V=CA-MA,CA=7;CA!==0&&V>0;)J=gA[CA],gA[CA--]=gA[MA+V-1],gA[MA+--V]=J;else if(CA!==8)return;return gA}(yp(A,1,-1)),!e))return xB;this.host=e}else if(this.isSpecial()){if(A=Uq(A),Yd(FP,A)||(e=function(c){var d,C,y,S,k,V,J,gA=$G(c,".");if(gA.length&&gA[gA.length-1]===""&&gA.length--,(d=gA.length)>4)return c;for(C=[],y=0;y1&&XE(S,0)==="0"&&(k=Yd(Gw,S)?16:8,S=yp(S,k===8?1:2)),S==="")V=0;else{if(!Yd(k===10?LP:k===8?Hq:UP,S))return c;V=Rw(S,k)}_f(C,V)}for(y=0;y=bP(256,5-d))return null}else if(V>255)return null;for(J=kP(C),y=0;y1?arguments[1]:void 0,a=Oq(e,new Yw(A,!1,o));qG||(e.href=a.serialize(),e.origin=a.getOrigin(),e.protocol=a.getProtocol(),e.username=a.getUsername(),e.password=a.getPassword(),e.host=a.getHost(),e.hostname=a.getHostname(),e.port=a.getPort(),e.pathname=a.getPathname(),e.search=a.getSearch(),e.searchParams=a.getSearchParams(),e.hash=a.getHash())},Hl=Vh.prototype,ql=function(A,e){return{get:function(){return vw(this)[A]()},set:e&&function(o){return vw(this)[e](o)},configurable:!0,enumerable:!0}};if(qG&&(ZE(Hl,"href",ql("serialize","setHref")),ZE(Hl,"origin",ql("getOrigin")),ZE(Hl,"protocol",ql("getProtocol","setProtocol")),ZE(Hl,"username",ql("getUsername","setUsername")),ZE(Hl,"password",ql("getPassword","setPassword")),ZE(Hl,"host",ql("getHost","setHost")),ZE(Hl,"hostname",ql("getHostname","setHostname")),ZE(Hl,"port",ql("getPort","setPort")),ZE(Hl,"pathname",ql("getPathname","setPathname")),ZE(Hl,"search",ql("getSearch","setSearch")),ZE(Hl,"searchParams",ql("getSearchParams")),ZE(Hl,"hash",ql("getHash","setHash"))),Mw(Hl,"toJSON",function(){return vw(this).serialize()},{enumerable:!0}),Mw(Hl,"toString",function(){return vw(this).serialize()},{enumerable:!0}),wf){var YP=wf.createObjectURL,Vw=wf.revokeObjectURL;YP&&Mw(Vh,"createObjectURL",TP(YP,wf)),Vw&&Mw(Vh,"revokeObjectURL",TP(Vw,wf))}Fq(Vh,"URL"),kq({global:!0,constructor:!0,forced:!_P,sham:!qG},{URL:Vh});var VP=sA;_n({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return VP(URL.prototype.toString,this)}});let JP=!0,Jw=!0;function kS(A,e,o){const a=A.match(e);return a&&a.length>=o&&parseFloat(a[o],10)}function HB(A,e,o){if(!A.RTCPeerConnection)return;const a=A.RTCPeerConnection.prototype,c=a.addEventListener;a.addEventListener=function(C,y){if(C!==e)return c.apply(this,arguments);const S=k=>{const V=o(k);V&&(y.handleEvent?y.handleEvent(V):y(V))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(y,S),c.apply(this,[C,S])};const d=a.removeEventListener;a.removeEventListener=function(C,y){if(C!==e||!this._eventMap||!this._eventMap[e])return d.apply(this,arguments);if(!this._eventMap[e].has(y))return d.apply(this,arguments);const S=this._eventMap[e].get(y);return this._eventMap[e].delete(y),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,d.apply(this,[C,S])},Object.defineProperty(a,"on"+e,{get(){return this["_on"+e]},set(C){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),C&&this.addEventListener(e,this["_on"+e]=C)},enumerable:!0,configurable:!0})}function HP(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(JP=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function Zq(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(Jw=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function Hw(){if(typeof window=="object"){if(JP)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function LS(A,e){Jw&&console.warn(A+" is deprecated, please use "+e+" instead.")}function sb(A){return Object.prototype.toString.call(A)==="[object Object]"}function nb(A){return sb(A)?Object.keys(A).reduce(function(e,o){const a=sb(A[o]),c=a?nb(A[o]):A[o],d=a&&!Object.keys(c).length;return c===void 0||d?e:Object.assign(e,{[o]:c})},{}):A}function rb(A,e,o){e&&!o.has(e.id)&&(o.set(e.id,e),Object.keys(e).forEach(a=>{a.endsWith("Id")?rb(A,A.get(e[a]),o):a.endsWith("Ids")&&e[a].forEach(c=>{rb(A,A.get(c),o)})}))}function qP(A,e,o){const a=o?"outbound-rtp":"inbound-rtp",c=new Map;if(e===null)return c;const d=[];return A.forEach(C=>{C.type==="track"&&C.trackIdentifier===e.id&&d.push(C)}),d.forEach(C=>{A.forEach(y=>{y.type===a&&y.trackId===C.id&&rb(A,y,c)})}),c}const ab=Hw;function KP(A,e){const o=A&&A.navigator;if(!o.mediaDevices)return;const a=function(C){if(typeof C!="object"||C.mandatory||C.optional)return C;const y={};return Object.keys(C).forEach(S=>{if(S==="require"||S==="advanced"||S==="mediaSource")return;const k=typeof C[S]=="object"?C[S]:{ideal:C[S]};k.exact!==void 0&&typeof k.exact=="number"&&(k.min=k.max=k.exact);const V=function(J,gA){return J?J+gA.charAt(0).toUpperCase()+gA.slice(1):gA==="deviceId"?"sourceId":gA};if(k.ideal!==void 0){y.optional=y.optional||[];let J={};typeof k.ideal=="number"?(J[V("min",S)]=k.ideal,y.optional.push(J),J={},J[V("max",S)]=k.ideal,y.optional.push(J)):(J[V("",S)]=k.ideal,y.optional.push(J))}k.exact!==void 0&&typeof k.exact!="number"?(y.mandatory=y.mandatory||{},y.mandatory[V("",S)]=k.exact):["min","max"].forEach(J=>{k[J]!==void 0&&(y.mandatory=y.mandatory||{},y.mandatory[V(J,S)]=k[J])})}),C.advanced&&(y.optional=(y.optional||[]).concat(C.advanced)),y},c=function(C,y){if(e.version>=61)return y(C);if((C=JSON.parse(JSON.stringify(C)))&&typeof C.audio=="object"){const S=function(k,V,J){V in k&&!(J in k)&&(k[J]=k[V],delete k[V])};S((C=JSON.parse(JSON.stringify(C))).audio,"autoGainControl","googAutoGainControl"),S(C.audio,"noiseSuppression","googNoiseSuppression"),C.audio=a(C.audio)}if(C&&typeof C.video=="object"){let S=C.video.facingMode;S=S&&(typeof S=="object"?S:{ideal:S});const k=e.version<66;if(S&&(S.exact==="user"||S.exact==="environment"||S.ideal==="user"||S.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||k)){let V;if(delete C.video.facingMode,S.exact==="environment"||S.ideal==="environment"?V=["back","rear"]:S.exact!=="user"&&S.ideal!=="user"||(V=["front"]),V)return o.mediaDevices.enumerateDevices().then(J=>{J=J.filter(CA=>CA.kind==="videoinput");let gA=J.find(CA=>V.some(MA=>CA.label.toLowerCase().includes(MA)));return!gA&&J.length&&V.includes("back")&&(gA=J[J.length-1]),gA&&(C.video.deviceId=S.exact?{exact:gA.deviceId}:{ideal:gA.deviceId}),C.video=a(C.video),ab("chrome: "+JSON.stringify(C)),y(C)})}C.video=a(C.video)}return ab("chrome: "+JSON.stringify(C)),y(C)},d=function(C){return e.version>=64?C:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[C.name]||C.name,message:C.message,constraint:C.constraint||C.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(C,y,S){c(C,k=>{o.webkitGetUserMedia(k,y,V=>{S&&S(d(V))})})}.bind(o),o.mediaDevices.getUserMedia){const C=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(y){return c(y,S=>C(S).then(k=>{if(S.audio&&!k.getAudioTracks().length||S.video&&!k.getVideoTracks().length)throw k.getTracks().forEach(V=>{V.stop()}),new DOMException("","NotFoundError");return k},k=>Promise.reject(d(k))))}}}function jP(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function WP(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("ontrack"in A.RTCPeerConnection.prototype)){Object.defineProperty(A.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(o){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=o)},enumerable:!0,configurable:!0});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",a=>{let c;c=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(C=>C.track&&C.track.id===a.track.id):{track:a.track};const d=new Event("track");d.track=a.track,d.receiver=c,d.transceiver={receiver:c},d.streams=[o.stream],this.dispatchEvent(d)}),o.stream.getTracks().forEach(a=>{let c;c=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(C=>C.track&&C.track.id===a.id):{track:a};const d=new Event("track");d.track=a,d.receiver=c,d.transceiver={receiver:c},d.streams=[o.stream],this.dispatchEvent(d)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else HB(A,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function gb(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const e=function(c,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=c.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:c}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const c=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(C,y){let S=c.apply(this,arguments);return S||(S=e(this,C),this._senders.push(S)),S};const d=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(C){d.apply(this,arguments);const y=this._senders.indexOf(C);y!==-1&&this._senders.splice(y,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(c){this._senders=this._senders||[],o.apply(this,[c]),c.getTracks().forEach(d=>{this._senders.push(e(this,d))})};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(c){this._senders=this._senders||[],a.apply(this,[c]),c.getTracks().forEach(d=>{const C=this._senders.find(y=>y.track===d);C&&this._senders.splice(this._senders.indexOf(C),1)})}}else if(typeof A=="object"&&A.RTCPeerConnection&&"getSenders"in A.RTCPeerConnection.prototype&&"createDTMFSender"in A.RTCPeerConnection.prototype&&A.RTCRtpSender&&!("dtmf"in A.RTCRtpSender.prototype)){const e=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=e.apply(this,[]);return o.forEach(a=>a._pc=this),o},Object.defineProperty(A.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function zP(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,a,c]=arguments;if(arguments.length>0&&typeof o=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof o!="function"))return e.apply(this,[]);const d=function(y){const S={};return y.result().forEach(k=>{const V={id:k.id,timestamp:k.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[k.type]||k.type};k.names().forEach(J=>{V[J]=k.stat(J)}),S[V.id]=V}),S},C=function(y){return new Map(Object.keys(y).map(S=>[S,y[S]]))};if(arguments.length>=2){const y=function(S){a(C(d(S)))};return e.apply(this,[y,o])}return new Promise((y,S)=>{e.apply(this,[function(k){y(C(d(k)))},S])}).then(a,c)}}function cb(A){if(!(typeof A=="object"&&A.RTCPeerConnection&&A.RTCRtpSender&&A.RTCRtpReceiver))return;if(!("getStats"in A.RTCRtpSender.prototype)){const o=A.RTCPeerConnection.prototype.getSenders;o&&(A.RTCPeerConnection.prototype.getSenders=function(){const c=o.apply(this,[]);return c.forEach(d=>d._pc=this),c});const a=A.RTCPeerConnection.prototype.addTrack;a&&(A.RTCPeerConnection.prototype.addTrack=function(){const c=a.apply(this,arguments);return c._pc=this,c}),A.RTCRtpSender.prototype.getStats=function(){const c=this;return this._pc.getStats().then(d=>qP(d,c.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const a=o.apply(this,[]);return a.forEach(c=>c._pc=this),a}),HB(A,"track",a=>(a.receiver._pc=a.srcElement,a)),A.RTCRtpReceiver.prototype.getStats=function(){const a=this;return this._pc.getStats().then(c=>qP(c,a.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let a,c,d;return this.getSenders().forEach(C=>{C.track===o&&(a?d=!0:a=C)}),this.getReceivers().forEach(C=>(C.track===o&&(c?d=!0:c=C),C.track===o)),d||a&&c?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():c?c.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function ZP(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])};const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(d,C){if(!C)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const y=e.apply(this,arguments);return this._shimmedLocalStreams[C.id]?this._shimmedLocalStreams[C.id].indexOf(y)===-1&&this._shimmedLocalStreams[C.id].push(y):this._shimmedLocalStreams[C.id]=[C,y],y};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(S=>{if(this.getSenders().find(k=>k.track===S))throw new DOMException("Track already exists.","InvalidAccessError")});const C=this.getSenders();o.apply(this,arguments);const y=this.getSenders().filter(S=>C.indexOf(S)===-1);this._shimmedLocalStreams[d.id]=[d].concat(y)};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[d.id],a.apply(this,arguments)};const c=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},d&&Object.keys(this._shimmedLocalStreams).forEach(C=>{const y=this._shimmedLocalStreams[C].indexOf(d);y!==-1&&this._shimmedLocalStreams[C].splice(y,1),this._shimmedLocalStreams[C].length===1&&delete this._shimmedLocalStreams[C]}),c.apply(this,arguments)}}function XP(A,e){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&e.version>=65)return ZP(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const S=o.apply(this);return this._reverseStreams=this._reverseStreams||{},S.map(k=>this._reverseStreams[k.id])};const a=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(S){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(k=>{if(this.getSenders().find(V=>V.track===k))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){const k=new A.MediaStream(S.getTracks());this._streams[S.id]=k,this._reverseStreams[k.id]=S,S=k}a.apply(this,[S])};const c=A.RTCPeerConnection.prototype.removeStream;function d(S,k){let V=k.sdp;return Object.keys(S._reverseStreams||[]).forEach(J=>{const gA=S._reverseStreams[J],CA=S._streams[gA.id];V=V.replace(new RegExp(CA.id,"g"),gA.id)}),new RTCSessionDescription({type:k.type,sdp:V})}A.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},c.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},A.RTCPeerConnection.prototype.addTrack=function(S,k){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const V=[].slice.call(arguments,1);if(V.length!==1||!V[0].getTracks().find(gA=>gA===S))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(gA=>gA.track===S))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const J=this._streams[k.id];if(J)J.addTrack(S),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const gA=new A.MediaStream([S]);this._streams[k.id]=gA,this._reverseStreams[gA.id]=k,this.addStream(gA)}return this.getSenders().find(gA=>gA.track===S)},["createOffer","createAnswer"].forEach(function(S){const k=A.RTCPeerConnection.prototype[S],V={[S](){const J=arguments;return arguments.length&&typeof arguments[0]=="function"?k.apply(this,[gA=>{const CA=d(this,gA);J[0].apply(null,[CA])},gA=>{J[1]&&J[1].apply(null,gA)},arguments[2]]):k.apply(this,arguments).then(gA=>d(this,gA))}};A.RTCPeerConnection.prototype[S]=V[S]});const C=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(S,k){let V=k.sdp;return Object.keys(S._reverseStreams||[]).forEach(J=>{const gA=S._reverseStreams[J],CA=S._streams[gA.id];V=V.replace(new RegExp(gA.id,"g"),CA.id)}),new RTCSessionDescription({type:k.type,sdp:V})}(this,arguments[0]),C.apply(this,arguments)):C.apply(this,arguments)};const y=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const S=y.get.apply(this);return S.type===""?S:d(this,S)}}),A.RTCPeerConnection.prototype.removeTrack=function(S){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let k;this._streams=this._streams||{},Object.keys(this._streams).forEach(V=>{this._streams[V].getTracks().find(J=>S.track===J)&&(k=this._streams[V])}),k&&(k.getTracks().length===1?this.removeStream(this._reverseStreams[k.id]):k.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function US(A,e){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const a=A.RTCPeerConnection.prototype[o],c={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),a.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=c[o]})}function $P(A,e){HB(A,"negotiationneeded",o=>{const a=o.target;if(!(e.version<72||a.getConfiguration&&a.getConfiguration().sdpSemantics==="plan-b")||a.signalingState==="stable")return o})}var lb=Object.freeze({__proto__:null,shimMediaStream:jP,shimOnTrack:WP,shimGetSendersWithDtmf:gb,shimGetStats:zP,shimSenderReceiverGetStats:cb,shimAddTrackRemoveTrackWithNative:ZP,shimAddTrackRemoveTrack:XP,shimPeerConnection:US,fixNegotiationNeeded:$P,shimGetUserMedia:KP,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof e=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return e(o).then(a=>{const c=o.video&&o.video.width,d=o.video&&o.video.height,C=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:C||3}},c&&(o.video.mandatory.maxWidth=c),d&&(o.video.mandatory.maxHeight=d),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function Ax(A,e){const o=A&&A.navigator,a=A&&A.MediaStreamTrack;if(o.getUserMedia=function(c,d,C){LS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(c).then(d,C)},!(e.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const c=function(C,y,S){y in C&&!(S in C)&&(C[S]=C[y],delete C[y])},d=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(C){return typeof C=="object"&&typeof C.audio=="object"&&(C=JSON.parse(JSON.stringify(C)),c(C.audio,"autoGainControl","mozAutoGainControl"),c(C.audio,"noiseSuppression","mozNoiseSuppression")),d(C)},a&&a.prototype.getSettings){const C=a.prototype.getSettings;a.prototype.getSettings=function(){const y=C.apply(this,arguments);return c(y,"mozAutoGainControl","autoGainControl"),c(y,"mozNoiseSuppression","noiseSuppression"),y}}if(a&&a.prototype.applyConstraints){const C=a.prototype.applyConstraints;a.prototype.applyConstraints=function(y){return this.kind==="audio"&&typeof y=="object"&&(y=JSON.parse(JSON.stringify(y)),c(y,"autoGainControl","mozAutoGainControl"),c(y,"noiseSuppression","mozNoiseSuppression")),C.apply(this,[y])}}}}function ex(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function qw(A,e){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(c){const d=A.RTCPeerConnection.prototype[c],C={[c](){return arguments[0]=new(c==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),d.apply(this,arguments)}};A.RTCPeerConnection.prototype[c]=C[c]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},a=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[c,d,C]=arguments;return a.apply(this,[c||null]).then(y=>{if(e.version<53&&!d)try{y.forEach(S=>{S.type=o[S.type]||S.type})}catch(S){if(S.name!=="TypeError")throw S;y.forEach((k,V)=>{y.set(V,Object.assign({},k,{type:o[k.type]||k.type}))})}return y}).then(d,C)}}function tx(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const e=A.RTCPeerConnection.prototype.getSenders;e&&(A.RTCPeerConnection.prototype.getSenders=function(){const a=e.apply(this,[]);return a.forEach(c=>c._pc=this),a});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=o.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Ib(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const e=A.RTCPeerConnection.prototype.getReceivers;e&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=e.apply(this,[]);return o.forEach(a=>a._pc=this),o}),HB(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ix(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(e){LS("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function ub(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function ox(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.addTransceiver;e&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const a=o.length>0;a&&o.forEach(d=>{if("rid"in d&&!/^[a-z0-9]{0,16}$/i.test(d.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in d&&!(parseFloat(d.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in d&&!(parseFloat(d.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const c=e.apply(this,arguments);if(a){const{sender:d}=c,C=d.getParameters();(!("encodings"in C)||C.encodings.length===1&&Object.keys(C.encodings[0]).length===0)&&(C.encodings=o,d.sendEncodings=o,this.setParametersPromises.push(d.setParameters(C).then(()=>{delete d.sendEncodings}).catch(()=>{delete d.sendEncodings})))}return c})}function sx(A){if(typeof A!="object"||!A.RTCRtpSender)return;const e=A.RTCRtpSender.prototype.getParameters;e&&(A.RTCRtpSender.prototype.getParameters=function(){const o=e.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function nx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function rx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var ax=Object.freeze({__proto__:null,shimOnTrack:ex,shimPeerConnection:qw,shimSenderGetStats:tx,shimReceiverGetStats:Ib,shimRemoveStream:ix,shimRTCDataChannel:ub,shimAddTransceiver:ox,shimGetParameters:sx,shimCreateOffer:nx,shimCreateAnswer:rx,shimGetUserMedia:Ax,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return o.video===!0?o.video={mediaSource:e}:o.video.mediaSource=e,A.navigator.mediaDevices.getUserMedia(o)})}});function gx(A){if(typeof A=="object"&&A.RTCPeerConnection){if("getLocalStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in A.RTCPeerConnection.prototype)){const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(a=>e.call(this,a,o)),o.getVideoTracks().forEach(a=>e.call(this,a,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...a){return a&&a.forEach(c=>{this._localStreams?this._localStreams.includes(c)||this._localStreams.push(c):this._localStreams=[c]}),e.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(e);if(o===-1)return;this._localStreams.splice(o,1);const a=e.getTracks();this.getSenders().forEach(c=>{a.includes(c.track)&&this.removeTrack(c)})})}}function cx(A){if(typeof A=="object"&&A.RTCPeerConnection&&("getRemoteStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in A.RTCPeerConnection.prototype))){Object.defineProperty(A.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(o){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=o),this.addEventListener("track",this._onaddstreampoly=a=>{a.streams.forEach(c=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(c))return;this._remoteStreams.push(c);const d=new Event("addstream");d.stream=c,this.dispatchEvent(d)})})}});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(a){a.streams.forEach(c=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(c)>=0)return;o._remoteStreams.push(c);const d=new Event("addstream");d.stream=c,o.dispatchEvent(d)})}),e.apply(o,arguments)}}}function Eb(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype,o=e.createOffer,a=e.createAnswer,c=e.setLocalDescription,d=e.setRemoteDescription,C=e.addIceCandidate;e.createOffer=function(S,k){const V=arguments.length>=2?arguments[2]:arguments[0],J=o.apply(this,[V]);return k?(J.then(S,k),Promise.resolve()):J},e.createAnswer=function(S,k){const V=arguments.length>=2?arguments[2]:arguments[0],J=a.apply(this,[V]);return k?(J.then(S,k),Promise.resolve()):J};let y=function(S,k,V){const J=c.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J};e.setLocalDescription=y,y=function(S,k,V){const J=d.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J},e.setRemoteDescription=y,y=function(S,k,V){const J=C.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J},e.addIceCandidate=y}function db(A){const e=A&&A.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const o=e.mediaDevices,a=o.getUserMedia.bind(o);e.mediaDevices.getUserMedia=c=>a(lx(c))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(o,a,c){e.mediaDevices.getUserMedia(o).then(a,c)}.bind(e))}function lx(A){return A&&A.video!==void 0?Object.assign({},A,{video:nb(A.video)}):A}function Ix(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection;A.RTCPeerConnection=function(o,a){if(o&&o.iceServers){const c=[];for(let d=0;de.generateCertificate})}function ux(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Kw(A){const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const a=this.getTransceivers().find(d=>d.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&a?a.direction==="sendrecv"?a.setDirection?a.setDirection("sendonly"):a.direction="sendonly":a.direction==="recvonly"&&(a.setDirection?a.setDirection("inactive"):a.direction="inactive"):o.offerToReceiveAudio!==!0||a||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const c=this.getTransceivers().find(d=>d.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&c?c.direction==="sendrecv"?c.setDirection?c.setDirection("sendonly"):c.direction="sendonly":c.direction==="recvonly"&&(c.setDirection?c.setDirection("inactive"):c.direction="inactive"):o.offerToReceiveVideo!==!0||c||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Ex(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var dx=Object.freeze({__proto__:null,shimLocalStreamsAPI:gx,shimRemoteStreamsAPI:cx,shimCallbacksAPI:Eb,shimGetUserMedia:db,shimConstraints:lx,shimRTCIceServerUrls:Ix,shimTrackEventTransceiver:ux,shimCreateOfferLegacy:Kw,shimAudioContext:Ex}),Cx={exports:{}};(function(A){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(o){return o.trim().split(` +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(v)),this._worker.postMessage({type:Dr,url:B})}send(B){var v,G;try{(v=this._worker)===null||v===void 0||v.postMessage({type:Us,data:B})}catch(O){(G=this._onSendFail)===null||G===void 0||G.call(this,O)}}bindSocketHandlers(B){const{onOpen:v,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;if(this._worker){const rA={[fs]:v,[as]:G,[wu]:O,[Wa]:z,[hs]:X};this._onSendFail=X,this._worker.onmessage=DA=>{var GA;const{type:JA}=DA?.data||{};typeof rA[JA]=="function"&&((GA=rA[JA])===null||GA===void 0||GA.call(rA,DA?.data))}}}unbindSocketHandlers(){this._worker&&(this._worker.onmessage=null)}disconnect(){this._worker&&(this._worker.postMessage({type:Jc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class qI{}var es,eo=new class{constructor(){this._store=new Map}get(p){return this._store.get(p)}getStorage(p){return Gi?oi?my.getStorageSync({key:p}).data:Ao.getStorageSync(p):this._canUseLocalStorage()?localStorage.getItem(p):{}}set(p,B){const v=this._store.get(p)||{};B instanceof Map?this._store.set(p,B):this._store.set(p,Object.assign(Object.assign({},v),B))}setStorage(p,B){Gi?oi?my.setStorageSync({key:p,data:JSON.stringify(B)}):Ao.setStorageSync(p,JSON.stringify(B)):this._canUseLocalStorage()&&localStorage.setItem(p,JSON.stringify(B))}clear(p){typeof p=="string"?this._store.set(p,{}):this._store.clear()}clearLocalStorage(p){this._canUseLocalStorage()&&(typeof p=="string"?localStorage.setItem(p,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class pc{connectSocket(B){return this._socket=Ao.connectSocket({url:B,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(B){var v;(v=this._socket)===null||v===void 0||v.send({data:B,fail:this._onSendFail})}bindSocketHandlers(B){const{onOpen:v,onMessage:G,onClose:O,onError:z,onSendFail:X}=B;this._socket&&(this._socket.onClose(O),this._socket.onOpen(v),this._socket.onMessage(rA=>G(rA?.data)),this._socket.onError(()=>z),this._onSendFail=X)}unbindSocketHandlers(){this._socket&&(this._socket.onClose(()=>{}),this._socket.onOpen(()=>{}),this._socket.onMessage(()=>{}),this._socket.onError(()=>{}))}disconnect(){this._socket&&(this._socket.close(),this._socket=null)}}(function(p){p[p.CONNECTED=0]="CONNECTED",p[p.CONNECTING=1]="CONNECTING",p[p.DISCONNECTED=2]="DISCONNECTED"})(es||(es={}));class ng{constructor(B){this._url="",this._readyState=es.DISCONNECTED,this._url=B,this._id=L(),this._emitter=new Pn,oi?this._socket=new pc:ct||Co||Dt||Ve||Ni||Pt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new qI:this._canUseWebWorker()?this._socket=new sg:this._socket=new Ml,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this._readyState=es.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(B){this._readyState!==es.CONNECTED?this.reconnect():this._socket.send(B)}reconnect(){[es.CONNECTED,es.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(B,v,G){this._emitter.on(B,v,G)}off(B,v,G){this._emitter.off(B,v,G)}isConnected(){return this._readyState===es.CONNECTED}disconnect(){this._readyState=es.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(B){this._readyState===es.CONNECTING&&(this._readyState=es.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:B}))}_onMessage(B){this._emitter.emit("message",B)}_onClose(B){this._readyState=es.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:B})}_onError(B){this._readyState=es.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:B})}_onSendFail(B){this._readyState=es.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:B})}_bindSocketHandlers(){this._socket.bindSocketHandlers({onOpen:this._onOpen.bind(this),onMessage:this._onMessage.bind(this),onClose:this._onClose.bind(this),onError:this._onError.bind(this),onSendFail:this._onSendFail.bind(this)})}_unbindSocketHandlers(){this._socket.unbindSocketHandlers()}_canUseWebWorker(){const B=eo.get("cloudConfig")||{};return(n(B.isWorkerEnabled)||B.isWorkerEnabled==="1")&&Go}}const Dg={[gt.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[gt.KOREA]:[[3e7,4e7],[173e7,174e7]],[gt.GERMANY]:[[4e7,5e7],[174e7,175e7]],[gt.IND]:[[5e7,6e7],[175e7,176e7]],[gt.JPN]:[[6e7,7e7],[176e7,177e7]],[gt.USA]:[[7e7,8e7],[177e7,178e7]],[gt.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[gt.KSA]:[[9e7,1e8],[179e7,18e8]]};function ua(p){var B;if(!((B=eo.get("instance"))===null||B===void 0)&&B.oversea)return gt.OVERSEA;for(const v of Object.keys(Dg))for(const[G,O]of Dg[v])if(p>=G&&p`${ne}=${JA[ne]}`).join("&"));var JA;return v?`${p}/binfo?${GA}&compress=gzip`:`${p}/info?${GA}`}function Hs(p){const B=eo.get("instance"),{sdkAppId:v,testEnv:G,proxyServer:O}=B,z=ua(v);if(G)return Kn(dt.TEST[z].DEFAULT,{isBinary:p});if(!Rs(O))return Kn(O,{isBinary:p});const X=dt.PRODUCTION[z],rA=zt&&X.ANYCAST,DA=zt,GA=!!X.BACKUP_CN;return Kn({[bo.INITIAL]:()=>(To=bo.DEFAULT,X.DEFAULT),[bo.DEFAULT]:()=>(To=bo.IPV6,X.IPV6),[bo.IPV6]:()=>(To=bo.BACKUP,X.BACKUP),[bo.BACKUP]:()=>DA?(To=bo.BACKUP_WEB_ONLY,function(JA){const ne=Math.floor(10001*Math.random())+1e4;return JA.replace("*",String(ne))}(X.BACKUP_WEB_ONLY)):GA?(To=bo.BACKUP_CN,X.BACKUP_CN):rA?(To=bo.ANYCAST,X.ANYCAST):X.DEFAULT,[bo.BACKUP_WEB_ONLY]:()=>GA?(To=bo.BACKUP_CN,X.BACKUP_CN):rA?(To=bo.ANYCAST,X.ANYCAST):X.DEFAULT,[bo.BACKUP_CN]:()=>(To=rA?bo.ANYCAST:bo.DEFAULT,X[To]),[bo.ANYCAST]:()=>(To=bo.DEFAULT,X.ANYCAST="",X.DEFAULT)}[To](),{isBinary:p})}var Sg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(p,B){const v=Date.now(),G=v-p;this._timeOffsetWithServer=B+G-v}};const mc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(p){const{id:B}=p;this.removeTask(B),this._tasks.push(p),this._taskMap.set(B,p),this._sort(),this._scheduleNextTask()}_createTask(p){const{id:B,callback:v,context:G,isOnce:O=!1,intervalMs:z=mc}=p,X=Math.max(z,mc);return{id:B,nextExecuteTime:Date.now()+X,intervalMs:z,callback:v,context:G,isOnce:O}}addTask(p){const B=this._createTask(p);this._addTaskToScheduler(B)}addOnceTask(p){const B=this._createTask(Object.assign(Object.assign({},p),{isOnce:!0}));this._addTaskToScheduler(B)}removeTask(p){const B=this._tasks.findIndex(v=>v.id===p);B>-1&&(this._tasks.splice(B,1),this._taskMap.delete(p),this._scheduleNextTask())}updateTaskInterval(p,B){const v=this._taskMap.get(p);v&&(v.intervalMs=B,v.nextExecuteTime=Date.now()+B,this._sort(),this._scheduleNextTask())}clearAllTasks(){this._tasks=[],this._taskMap.clear(),this._timer&&(clearTimeout(this._timer),this._timer=null)}dispose(){this.clearAllTasks()}_sort(){this._tasks.sort((p,B)=>p.nextExecuteTime-B.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const p=this._tasks[0];if(p){const B=Math.max(0,p.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),B)}}_execute(){const p=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=p;){const B=this._tasks[0];try{B.context?B.callback.call(B.context):B.callback(),B.isOnce?this.removeTask(B.id):(B.nextExecuteTime=p+B.intervalMs,this._sort())}catch(v){console.warn(`Task ${B.id} execution failed:`,v),B.isOnce&&this.removeTask(B.id)}}this._scheduleNextTask()}};function Ga(p){const B=[];for(let v=0;v=55296&&G<=56319){const O=p.charCodeAt(++v)-56320+(G-55296<<10)+65536;B.push(240|O>>18,128|O>>12&63,128|O>>6&63,128|63&O)}else G<=127?B.push(G):G<=2047?B.push(192|G>>6,128|63&G):B.push(224|G>>12,128|G>>6&63,128|63&G)}return new Uint8Array(B)}function In(p){const B=Array.isArray(p)?[]:Object.create(null);for(const v in p)Object.prototype.hasOwnProperty.call(p,v)&&_(v)&&p[v]!=null&&(p[v]===null||typeof p[v]!="object"?B[v]=p[v]:B[v]=In(p[v]));return B}function ys(p,B){if(BA.includes(p))return 0;const v=Ga(JSON.stringify(B));let G=4294967295;const{length:O}=v;for(let z=0;z>>=1:G=G>>>1^3988292384}return(4294967295^G)>>>0}function Ea(p){const{servcmd:B,data:v}=p,G=function(z){const X=eo.get("login")||{},rA=eo.get("instance")||{};return{servcmd:z,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",a2:X.a2Key||void 0,tinyid:X.tinyID||void 0,status_instid:X.statusInstanceId||0,sdkappid:rA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.a2Key?void 0:X.userId,usersig:X.a2Key?void 0:X.userSig,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,tjgID:"",seq:Sa(),cs:0}}(B),O=In(v);return G.cs=ys(B,O),{head:G,body:O}}function yn(p){const{servcmd:B,data:v}=p,G=function(z){const X=eo.get("login")||{},rA=eo.get("instance")||{};return{servcmd:z,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:rA.sdkAppId,contenttype:"",reqtime:Math.floor(Date.now()/1e3),identifier:"",usersig:"",status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,seq:Sa(),cs:0}}(B),O=In(v);return G.cs=ys(B,O),{head:G,body:O}}let ba=L();function Sa(){return ba=ba<2415919103?ba+1:L(),ba}function $(){var p;const B=eo.get("login")||{},v=eo.get("instance")||{};return{sdk_type:30,sdk_app_id:v.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(B.tinyID),user_id:B.userId||((p=eo.get("webPush"))===null||p===void 0?void 0:p.userId),platform:VA,instance_id:v.instanceId,trace_id:new Date().getTime()}}var j,vA=Object.freeze({__proto__:null,calcBodyCRC:ys,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(p){const{servcmd:B,data:v}=p,G=function(z){const X=eo.get("login")||{},rA=eo.get("instance")||{};return{servcmd:z,ver:"v4",platform:VA,websdkappid:537048168,websdkversion:"1.7.3",sdkappid:rA.sdkAppId,contenttype:"json",reqtime:Math.floor(Date.now()/1e3),identifier:X.userId,usersig:X.userSig,status_instid:X.statusInstanceId||0,sdkability:478343027,sdkability_ext:lA(""),cappid:rA.applicationID||0,seq:Sa(),cs:0}}(B),O=In(v);return G.cs=ys(B,O),{head:G,body:O}},generateProtocolData:Ea,generateSSOLogProtocolData:yn,generateSequence:Sa,getCommonHead:$,getHostSite:ua,taskScheduler:fn,timeManager:Sg});(function(p){p[p.info=4]="info",p[p.warning=5]="warning",p[p.error=6]="error"})(j||(j={}));const jA={method:"extension",networkType:"network_type",eventType:"event_type",code:"error_code",message:"error_message",moreMessage:"more_message",duplicate:"duplicate",costTime:"cost_time",level:"level",uiPlatform:"ui_platform",timestamp:"timestamp"};class oe{constructor(B){this.level=j.info,this._canSendLog=!0,this._logCreatedAt=Sg.getServerTimeMs(),this.timestamp=0,this.networkType=8,this.code=0,this.moreMessage="",this.method="",this.message="",this.costTime=0,this.duplicate=!1,this.eventType=0,this.uiPlatform=this._getUiPlatform(),this._sdkEdition=this._getSDKEdition();const{method:v,eventType:G=0,message:O="",costTime:z=0,error:X,uiPlatform:rA,moreMessage:DA="",code:GA=0,startTime:JA=0}=B||{};this.eventType=G,this.method=v,this.message=O,this.costTime=z,this.moreMessage=`${DA} startTime:${JA}`,this.code=GA,X&&this.setError(X),Rs(rA)||(this.uiPlatform=rA)}setMoreMessage(B){this.moreMessage=`${this.moreMessage} ${B}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Sg.getTimeOffsetWithServer()}end(B=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Sg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),B&&this._ssoLogModule.uploadSSOLogData())}setError(B){var v;return B instanceof Error?this._canSendLog?(!((v=eo.get("netWorkMonitor"))===null||v===void 0)&&v.isNetworkOnline&&(B.errorCode&&(this.code=B.errorCode),B.errorMessage&&this.setMoreMessage(B.errorMessage)),this.level=j.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(B){return Object.keys(B).forEach(v=>{Object.keys(jA).includes(v)&&(this[v]=B[v])}),this}setSSOLogModule(B){this._ssoLogModule=B}_convertSSOLogDataKeyToServe(){const B={};return Object.keys(this).forEach(v=>{const G=v;jA[G]&&(B[jA[G]]=this[G])}),B}_getUiPlatform(){var B;const v=(B=eo.get("instance"))===null||B===void 0?void 0:B.scene;if(typeof v=="string"){const G=Number(v);return isNaN(G)?void 0:G}}_getSDKEdition(){var B;return(B=eo.get("instance"))===null||B===void 0?void 0:B.sdkEdition}}var ye;(function(p){p.RECONNECTED="reconnected",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.SOCKET_DISCONNECTED="socket_disconnected"})(ye||(ye={}));var He=ye;const Pe=20,rt=6e4,ht=[4,5,6],_t="report-logger";var Vt=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:me,maxCount:ae},single:{throttleTime:ZA,maxCount:KA}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:_t,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(p){const{evt_rpt_threshold:B=Pe,evt_rpt_waiting:v=rt,evt_rpt_level:G=ht,evt_rpt_sdkappid_bl:O="",evt_rpt_tinyid_wl:z="",evt_rpt_global_throttle_time:X=me,evt_rpt_global_throttle_count:rA=ae,evt_rpt_single_throttle_time:DA=ZA,evt_rpt_single_throttle_count:GA=KA}=p||{};this._sdkAppIdBlackList=O.split(",").map(JA=>Number(JA)),this._waitingTime=Number(v),this._minThreshold=B,this._reportLevel=G,this._tinyIdWhiteList=z.split(","),this._throttleConfig={global:{throttleTime:X,maxCount:rA},single:{throttleTime:DA,maxCount:GA}}}createSSOLogData(p){const B=new oe(p);return B.setSSOLogModule(this),this._ssoLogMap.set(p.method,B),B}getSSOLogData(p){return this._ssoLogMap.get(p)||{}}pushToLogQueue(p){p&&(this._logQueue.push(p),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(p){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(p)&&(this._logLevel=p)}debug(p,B="",v){this._log(IA.DEBUG,p,B,v)}info(p,B="",v){this._log(IA.INFO,p,B,v)}warn(p,B="",v){this._log(IA.WARN,p,B,v)}error(p,B="",v){this._log(IA.ERROR,p,B,v)}_shouldUploadImmediately(){return this._logQueue.length>=this._minThreshold}_isReportDue(){return Date.now()>=this._lastReportAt+this._waitingTime}_checkAndReportIfDue(){this._isReportDue()&&this._logQueue.length>0&&this.uploadSSOLogData()}uploadSSOLogData(){return mA(this,void 0,void 0,function*(){if(this._logQueue.length===0)return;const p=this._logQueue.slice();this._logQueue=[];try{const B=this._filterLogs(p);if(B.length===0)return void(this._lastReportAt=Date.now());const v={Header:$(),Event:B};Rs(v.Header.user_id)||(yield function(G){const O="imopenstat.tim_web_report_v2",z=yn({servcmd:O,data:G}),X=`${z.head.seq}${O}`;return Rl.sendPacket(z,{requestId:X})}(v))}catch(B){this._requeueFailedLogs(p),this.debug("uploadSSOLogData",en(B))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(p){this._logQueue=p.concat(this._logQueue);const B=this._logQueue.length-200;B>0&&(this._logQueue.splice(0,B),this.debug("uploadSSOLogData",`log queue overflow, dropped ${B} oldest logs`))}_savePlatFormInfo(){var p,B;if(ct){const v=(B=(p=wx.getAccountInfoSync)===null||p===void 0?void 0:p.call(wx))===null||B===void 0?void 0:B.miniProgram;if(v){const{appId:G,envVersion:O}=v;eo.set("instance",{appId:G,envVersion:O})}}else zt&&eo.set("instance",{href:window.location.href})}_filterLogs(p){const{tinyID:B}=eo.get("login")||{},{sdkAppId:v}=eo.get("instance")||{};return this._sdkAppIdBlackList.includes(v)&&!this._tinyIdWhiteList.includes(B)?[]:p.filter(G=>this._reportLevel.includes(G.level))}_checkThrottle(p){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(p)}_checkGlobalThrottle(){const p=Date.now();if(p-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=p;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(p){const B=Date.now(),v=this._singleThrottleMap.get(p);return v?B-v.startTime>=this._throttleConfig.single.throttleTime?(v.count=1,v.startTime=B,!1):v.count>=this._throttleConfig.single.maxCount||(v.count++,!1):(this._singleThrottleMap.set(p,{count:1,startTime:B}),!1)}_shouldLog(p){return p>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(p){return this._reportLevel.includes(HA[p])}_formatLog(p,B,v,G){const O=new Date,z=`${O.getHours()}:${O.getMinutes()}:${O.getSeconds()}:${O.getMilliseconds()}`,X=`<${IA[p]}>`;return ve||Gi?[`${gA} [${z}] ${X} [${B}] ${v}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",gA,"",`[${z}] ${X} [${B}] ${v} params: ${en(G)}`]}_log(p,B,v,G){if(this._shouldLog(p)){const O=this._formatLog(p,B,v,G);RA[p].apply(console,O)}if(this._shouldReport(p)){const O=this._getThrottleKey(B,v,G);this._checkThrottle(O)||this.createSSOLogData(Object.assign(Object.assign({message:v},G),{method:B})).end()}}_getThrottleKey(p,B,v){const G=`${p}${B}${en(Object.assign(Object.assign({},v),{costTime:""}))}`,O=Ga(JSON.stringify(G));let z=4294967295;const{length:X}=O;for(let rA=0;rA>>=1:z=z>>>1^3988292384}return`${(4294967295^z)>>>0}`}reset(){console.log("SSO_LOG_MODULE.reset"),fn.removeTask(_t),gn.unSubscribeInnerEvent(He.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Pe,this._maxThreshold=100,this._waitingTime=rt,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const ui=15e3,It="Channel",Yt="channel_schedule_task",qi="channel_reconnect_task",Wi="connected",qs="connecting",vi="disconnected",zo=1e3,Mg="network_status_change",ar="activity_status_change",Sr="send_fail",Yn="reconnect_failed",vl="socket_error",Ks="socket_close";function gI(p){return gI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(B){return typeof B}:function(B){return B&&typeof Symbol=="function"&&B.constructor===Symbol&&B!==Symbol.prototype?"symbol":typeof B},gI(p)}function Wg(p){throw new Error('Could not dynamically require "'+p+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var fc,_u={exports:{}},Ma=(fc||(fc=1,function(p){p.exports=function B(v,G,O){function z(DA,GA){if(!G[DA]){if(!v[DA]){if(!GA&&Wg)return Wg(DA);if(X)return X(DA,!0);var JA=new Error("Cannot find module '"+DA+"'");throw JA.code="MODULE_NOT_FOUND",JA}var ne=G[DA]={exports:{}};v[DA][0].call(ne.exports,function(he){return z(v[DA][1][he]||he)},ne,ne.exports,B,v,G,O)}return G[DA].exports}for(var X=Wg,rA=0;rA>>6:(he<65536?ne[at++]=224|he>>>12:(ne[at++]=240|he>>>18,ne[at++]=128|he>>>12&63),ne[at++]=128|he>>>6&63),ne[at++]=128|63&he);return ne},G.buf2binstring=function(JA){return GA(JA,JA.length)},G.binstring2buf=function(JA){for(var ne=new O.Buf8(JA.length),he=0,Ze=ne.length;he>10&1023,Ht[Ze++]=56320|1023&st)}return GA(Ht,Ze)},G.utf8border=function(JA,ne){var he;for((ne=ne||JA.length)>JA.length&&(ne=JA.length),he=ne-1;0<=he&&(192&JA[he])==128;)he--;return he<0||he===0?ne:he+rA[JA[he]]>ne?he:ne}},{"./common":1}],3:[function(B,v,G){v.exports=function(O,z,X,rA){for(var DA=65535&O,GA=O>>>16&65535,JA=0;X!==0;){for(X-=JA=2e3>>1:z>>>1;X[rA]=z}return X}();v.exports=function(z,X,rA,DA){var GA=O,JA=DA+rA;z^=-1;for(var ne=DA;ne>>8^GA[255&(z^X[ne])];return-1^z}},{}],6:[function(B,v,G){v.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],7:[function(B,v,G){v.exports=function(O,z){var X,rA,DA,GA,JA,ne,he,Ze,st,at,Ft,Ht,Pi,co,Xi,di,xo,ts,mi,zi,Ws,Ne,Tt,FA,Ai;X=O.state,rA=O.next_in,FA=O.input,DA=rA+(O.avail_in-5),GA=O.next_out,Ai=O.output,JA=GA-(z-O.avail_out),ne=GA+(O.avail_out-257),he=X.dmax,Ze=X.wsize,st=X.whave,at=X.wnext,Ft=X.window,Ht=X.hold,Pi=X.bits,co=X.lencode,Xi=X.distcode,di=(1<>>=mi=ts>>>24,Pi-=mi,(mi=ts>>>16&255)==0)Ai[GA++]=65535&ts;else{if(!(16&mi)){if(!(64&mi)){ts=co[(65535&ts)+(Ht&(1<>>=mi,Pi-=mi),Pi<15&&(Ht+=FA[rA++]<>>=mi=ts>>>24,Pi-=mi,!(16&(mi=ts>>>16&255))){if(!(64&mi)){ts=Xi[(65535&ts)+(Ht&(1<>>=mi,Pi-=mi,(mi=GA-JA)>3,Ht&=(1<<(Pi-=zi<<3))-1,O.next_in=rA,O.next_out=GA,O.avail_in=rA>>24&255)+(Ne>>>8&65280)+((65280&Ne)<<8)+((255&Ne)<<24)}function Ht(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new O.Buf16(320),this.work=new O.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Pi(Ne){var Tt;return Ne&&Ne.state?(Tt=Ne.state,Ne.total_in=Ne.total_out=Tt.total=0,Ne.msg="",Tt.wrap&&(Ne.adler=1&Tt.wrap),Tt.mode=Ze,Tt.last=0,Tt.havedict=0,Tt.dmax=32768,Tt.head=null,Tt.hold=0,Tt.bits=0,Tt.lencode=Tt.lendyn=new O.Buf32(st),Tt.distcode=Tt.distdyn=new O.Buf32(at),Tt.sane=1,Tt.back=-1,ne):he}function co(Ne){var Tt;return Ne&&Ne.state?((Tt=Ne.state).wsize=0,Tt.whave=0,Tt.wnext=0,Pi(Ne)):he}function Xi(Ne,Tt){var FA,Ai;return Ne&&Ne.state?(Ai=Ne.state,Tt<0?(FA=0,Tt=-Tt):(FA=1+(Tt>>4),Tt<48&&(Tt&=15)),Tt&&(Tt<8||15=ii.wsize?(O.arraySet(ii.window,Tt,FA-ii.wsize,ii.wsize,0),ii.wnext=0,ii.whave=ii.wsize):(Ai<(En=ii.wsize-ii.wnext)&&(En=Ai),O.arraySet(ii.window,Tt,FA-Ai,En,ii.wnext),(Ai-=En)?(O.arraySet(ii.window,Tt,FA-Ai,Ai,0),ii.wnext=Ai,ii.whave=ii.wsize):(ii.wnext+=En,ii.wnext===ii.wsize&&(ii.wnext=0),ii.whave>>8&255,FA.check=X(FA.check,ke,2,0),mt=Bt=0,FA.mode=2;break}if(FA.flags=0,FA.head&&(FA.head.done=!1),!(1&FA.wrap)||(((255&Bt)<<8)+(Bt>>8))%31){Ne.msg="incorrect header check",FA.mode=30;break}if((15&Bt)!=8){Ne.msg="unknown compression method",FA.mode=30;break}if(mt-=4,yA=8+(15&(Bt>>>=4)),FA.wbits===0)FA.wbits=yA;else if(yA>FA.wbits){Ne.msg="invalid window size",FA.mode=30;break}FA.dmax=1<>8&1),512&FA.flags&&(ke[0]=255&Bt,ke[1]=Bt>>>8&255,FA.check=X(FA.check,ke,2,0)),mt=Bt=0,FA.mode=3;case 3:for(;mt<32;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>8&255,ke[2]=Bt>>>16&255,ke[3]=Bt>>>24&255,FA.check=X(FA.check,ke,4,0)),mt=Bt=0,FA.mode=4;case 4:for(;mt<16;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>8),512&FA.flags&&(ke[0]=255&Bt,ke[1]=Bt>>>8&255,FA.check=X(FA.check,ke,2,0)),mt=Bt=0,FA.mode=5;case 5:if(1024&FA.flags){for(;mt<16;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>8&255,FA.check=X(FA.check,ke,2,0)),mt=Bt=0}else FA.head&&(FA.head.extra=null);FA.mode=6;case 6:if(1024&FA.flags&&(wi<(Zi=FA.length)&&(Zi=wi),Zi&&(FA.head&&(yA=FA.head.extra_len-FA.length,FA.head.extra||(FA.head.extra=new Array(FA.head.extra_len)),O.arraySet(FA.head.extra,Ai,ii,Zi,yA)),512&FA.flags&&(FA.check=X(FA.check,Ai,Zi,ii)),wi-=Zi,ii+=Zi,FA.length-=Zi),FA.length))break A;FA.length=0,FA.mode=7;case 7:if(2048&FA.flags){if(wi===0)break A;for(Zi=0;yA=Ai[ii+Zi++],FA.head&&yA&&FA.length<65536&&(FA.head.name+=String.fromCharCode(yA)),yA&&Zi>9&1,FA.head.done=!0),Ne.adler=FA.check=0,FA.mode=12;break;case 10:for(;mt<32;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>=7&mt,mt-=7&mt,FA.mode=27;break}for(;mt<3;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>=1)){case 0:FA.mode=14;break;case 1:if(zi(FA),FA.mode=20,Tt!==6)break;Bt>>>=2,mt-=2;break A;case 2:FA.mode=17;break;case 3:Ne.msg="invalid block type",FA.mode=30}Bt>>>=2,mt-=2;break;case 14:for(Bt>>>=7&mt,mt-=7&mt;mt<32;){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>16^65535)){Ne.msg="invalid stored block lengths",FA.mode=30;break}if(FA.length=65535&Bt,mt=Bt=0,FA.mode=15,Tt===6)break A;case 15:FA.mode=16;case 16:if(Zi=FA.length){if(wi>>=5,mt-=5,FA.ndist=1+(31&Bt),Bt>>>=5,mt-=5,FA.ncode=4+(15&Bt),Bt>>>=4,mt-=4,286>>=3,mt-=3}for(;FA.have<19;)FA.lens[ue[FA.have++]]=0;if(FA.lencode=FA.lendyn,FA.lenbits=7,XA={bits:FA.lenbits},NA=DA(0,FA.lens,0,19,FA.lencode,0,FA.work,XA),FA.lenbits=XA.bits,NA){Ne.msg="invalid code lengths set",FA.mode=30;break}FA.have=0,FA.mode=19;case 19:for(;FA.have>>16&255,Qa=65535&de,!((os=de>>>24)<=mt);){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>=os,mt-=os,FA.lens[FA.have++]=Qa;else{if(Qa===16){for(Te=os+2;mt>>=os,mt-=os,FA.have===0){Ne.msg="invalid bit length repeat",FA.mode=30;break}yA=FA.lens[FA.have-1],Zi=3+(3&Bt),Bt>>>=2,mt-=2}else if(Qa===17){for(Te=os+3;mt>>=os)),Bt>>>=3,mt-=3}else{for(Te=os+7;mt>>=os)),Bt>>>=7,mt-=7}if(FA.have+Zi>FA.nlen+FA.ndist){Ne.msg="invalid bit length repeat",FA.mode=30;break}for(;Zi--;)FA.lens[FA.have++]=yA}}if(FA.mode===30)break;if(FA.lens[256]===0){Ne.msg="invalid code -- missing end-of-block",FA.mode=30;break}if(FA.lenbits=9,XA={bits:FA.lenbits},NA=DA(GA,FA.lens,0,FA.nlen,FA.lencode,0,FA.work,XA),FA.lenbits=XA.bits,NA){Ne.msg="invalid literal/lengths set",FA.mode=30;break}if(FA.distbits=6,FA.distcode=FA.distdyn,XA={bits:FA.distbits},NA=DA(JA,FA.lens,FA.nlen,FA.ndist,FA.distcode,0,FA.work,XA),FA.distbits=XA.bits,NA){Ne.msg="invalid distances set",FA.mode=30;break}if(FA.mode=20,Tt===6)break A;case 20:FA.mode=21;case 21:if(6<=wi&&258<=Bo){Ne.next_out=us,Ne.avail_out=Bo,Ne.next_in=ii,Ne.avail_in=wi,FA.hold=Bt,FA.bits=mt,rA(Ne,Ls),us=Ne.next_out,En=Ne.output,Bo=Ne.avail_out,ii=Ne.next_in,Ai=Ne.input,wi=Ne.avail_in,Bt=FA.hold,mt=FA.bits,FA.mode===12&&(FA.back=-1);break}for(FA.back=0;ca=(de=FA.lencode[Bt&(1<>>16&255,Qa=65535&de,!((os=de>>>24)<=mt);){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>ta)])>>>16&255,Qa=65535&de,!(ta+(os=de>>>24)<=mt);){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>=ta,mt-=ta,FA.back+=ta}if(Bt>>>=os,mt-=os,FA.back+=os,FA.length=Qa,ca===0){FA.mode=26;break}if(32&ca){FA.back=-1,FA.mode=12;break}if(64&ca){Ne.msg="invalid literal/length code",FA.mode=30;break}FA.extra=15&ca,FA.mode=22;case 22:if(FA.extra){for(Te=FA.extra;mt>>=FA.extra,mt-=FA.extra,FA.back+=FA.extra}FA.was=FA.length,FA.mode=23;case 23:for(;ca=(de=FA.distcode[Bt&(1<>>16&255,Qa=65535&de,!((os=de>>>24)<=mt);){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>ta)])>>>16&255,Qa=65535&de,!(ta+(os=de>>>24)<=mt);){if(wi===0)break A;wi--,Bt+=Ai[ii++]<>>=ta,mt-=ta,FA.back+=ta}if(Bt>>>=os,mt-=os,FA.back+=os,64&ca){Ne.msg="invalid distance code",FA.mode=30;break}FA.offset=Qa,FA.extra=15&ca,FA.mode=24;case 24:if(FA.extra){for(Te=FA.extra;mt>>=FA.extra,mt-=FA.extra,FA.back+=FA.extra}if(FA.offset>FA.dmax){Ne.msg="invalid distance too far back",FA.mode=30;break}FA.mode=25;case 25:if(Bo===0)break A;if(Zi=Ls-Bo,FA.offset>Zi){if((Zi=FA.offset-Zi)>FA.whave&&FA.sane){Ne.msg="invalid distance too far back",FA.mode=30;break}Zi>FA.wnext?(Zi-=FA.wnext,Hr=FA.wsize-Zi):Hr=FA.wnext-Zi,Zi>FA.length&&(Zi=FA.length),oc=FA.window}else oc=En,Hr=us-FA.offset,Zi=FA.length;for(Boxo?(mi=Hr[oc+at[Tt]],zi=mt[ug+at[Tt]]):(mi=96,zi=0),Ht=1<>us)+(Pi-=Ht)]=ts<<24|mi<<16|zi,Pi!==0;);for(Ht=1<>=1;if(Ht!==0?(Bt&=Ht-1,Bt+=Ht):Bt=0,Tt++,--Ls[Ne]==0){if(Ne===Ai)break;Ne=JA[ne+at[Tt]]}if(En{const rA=new Uint8Array(X).slice(4);let DA;try{DA=Ma.inflate(rA,{to:"string"})}catch(GA){console.error("inflate error",GA)}return DA})(p.data):function(X){const rA=new Uint8Array(X);let DA="",GA=0;const{length:JA}=rA;for(;GA0)for(let st=0;st{var G;const{uplinkData:O,canResend:z,resolve:X,reject:rA,timeout:DA}=B;if(z){this._pendingRequests.set(v,{resolve:X,reject:rA,timestamp:Date.now(),uplinkData:O,timeout:DA,canResend:z});const GA=this._isBinarySupported?Ga(O).buffer:O;(G=this._socketAdapter)===null||G===void 0||G.send(GA)}else this._pendingRequests.delete(v)})}_onConnect(p){const{socketId:B,event:v={}}=p||{};this._connectionId=B,this._connectionEstablishedTime=Date.now();const G=Date.now()-this._connectionStartTime,O=`${It}.onConnect cost:${G} ms. socketID:${B} res:${JSON.stringify(v)}`;if(this._ssoLog({method:"onConnect",message:O}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const z=`${It}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:z}),gn.emitInnerEvent(He.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:Wi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(p){const B=Ea({servcmd:"openim.ws_msg_push_ack",data:{SessionData:p}});this.sendPacket(B)}_executeScheduledTaskIfReady(){return mA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var p;return((p=this._socketAdapter)===null||p===void 0?void 0:p.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return mA(this,void 0,void 0,function*(){var p;const B=Ea({servcmd:"heartbeat.alive",data:{}});try{const v=`${B.head.seq}${B.head.servcmd}`;yield this.sendPacket(B,{requestId:v,timeout:3e3})}catch(v){const G=(p=eo.get("netWorkMonitor"))===null||p===void 0?void 0:p.isNetworkOnline,O=`${It}.sendHeartbeat failed. isNetWorkOnline:${G} error: ${en(v)}`;this._ssoLog({method:"sendHeartbeatError",message:O}),this._handleConnectStateChange({state:vi,shouldEmitEvent:!0,shouldAttemptReconnect:!0})}})}_sendHeartbeatIfReady(){return mA(this,void 0,void 0,function*(){this._canSendHeartbeat()&&(this._isHeartbeatInProgress=!0,yield this._sendHeartbeat(),this._isHeartbeatInProgress=!1)})}_updateHeartbeatTime(){this._nextHeartbeatAt=Co?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(p){const B=`${It}.networkStatusChange ${JSON.stringify(p)}`;this._ssoLog({method:"networkStatusChange",message:B});const{isNetworkOnline:v,networkType:G}=p;v&&G!=="none"?this._handleConnectStateChange({state:Wi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg}):this._handleConnectStateChange({state:vi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Mg})}isPrivateNetWork(){const p=eo.get("instance")||{};return p.proxyServer&&!p.fileDownloadProxy}_handleConnectStateChange(p){const{state:B,shouldAttemptReconnect:v,shouldEmitEvent:G,reason:O}=p,z=`${It}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${v} shouldEmitEvent: ${G} reason: ${O}`;this._currentConnectState!==B&&(this._ssoLog({method:"handleConnectStateChange",message:z}),G&&(Vt.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${B}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:B}}),this._currentConnectState=B,B===vi&&gn.emitInnerEvent(He.SOCKET_DISCONNECTED)),v&&(this._resetReconnectDelay(),fn.addTask({id:qi,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(p){var B,v;const G=(v=(B=this._socketAdapter)===null||B===void 0?void 0:B._ws)===null||v===void 0?void 0:v.readyState,O=`${It}.activityStatusChange ${JSON.stringify(p)} readyState: ${G}`;Vt.debug("activityStatusChange",O),G===3&&this._handleConnectStateChange({state:vi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:ar})}_resetReconnectDelay(){var p;Vt.debug(`${It}._resetReconnectDelay`),fn.removeTask(qi);const B=(p=eo.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?zo:1e3}_scheduleReconnectWithBackoff(){var p;const B=(p=eo.get("activityMonitor"))===null||p===void 0?void 0:p.isActive;this._intendedDelay=B?Math.min(5e3,Math.max(zo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const v=new Date().toTimeString().slice(0,8),G=`${It}.scheduleReconnectWithBackoff timeStr: ${v} intendedDelay: ${this._intendedDelay}`;Vt.debug(G),this.reconnect(),fn.updateTaskInterval(qi,this._intendedDelay)}_ssoLog(p){const{method:B,message:v}=p;Vt.info(B,v)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(p){mA(this,void 0,void 0,function*(){const B=p.split("/")[2];if(!B.startsWith("ws"))return;const v=`https://${B}/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:v,data:{}})}catch(G){Vt.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${G.message}`)}})}(this._url),function(p){mA(this,void 0,void 0,function*(){const B=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${p.slice(p.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Yi({method:"GET",url:B,data:{}})}catch(v){Vt.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${v.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[p,B]of this._pendingRequests.entries()){const{reject:v,timestamp:G,timeout:O}=B;Date.now()-G>=O&&(this._pendingRequests.delete(p),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),v({errorCode:mr,errorInfo:"NETWORK_TIMEOUT",data:{requestId:p}}))}}_updateIsBinarySupported(){var p;if(!((p=eo.get("instance"))===null||p===void 0)&&p.devMode)return void(this._isBinarySupported=!1);const B=ds();if((oi||ct&&B==="windows"||ks)&&(this._isBinarySupported=!1),Co){const{uniRuntimeVersion:v=""}=Ao.getSystemInfoSync();(function(G){const O=G.split(".").map(Number),[z=0,X=0,rA=0]=O;return z>2||!(z<2)&&(X>2||!(X<2)&&rA>=6)})(v)||(this._isBinarySupported=!1)}}_isCompressedData(p){const B=new Uint8Array(p);return B[0]===67&&B[1]===79&&B[2]===77&&B[3]===80}};const Se={init:function(p){eo.set("instance",p),Rl.init()},destroy:function(){Rl.dispose(),eo.clear(),fn.dispose()},notificationCenter:gn,channel:Rl,store:eo,ssoLog:Vt,utils:yg,common:vA,constants:lt},De=p=>typeof p=="function";function vg(p,B,v){const G=v||[];if(!p||!B)return!1;const O=Object.keys(p).filter(X=>!G.includes(X)),z=Object.keys(B).filter(X=>!G.includes(X));return O.length===z.length&&O.every(X=>!!B.hasOwnProperty(X)&&(typeof p[X]=="object"&&p[X]!==null?vg(p[X],B[X],v):p[X]===B[X]))}var rg;(function(p){p.SDK_READY="sdkStateReady",p.SDK_NOT_READY="sdkStateNotReady",p.SDK_DESTROY="sdkDestroy",p.MESSAGE_RECEIVED="onMessageReceived",p.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",p.MESSAGE_MODIFIED="onMessageModified",p.MESSAGE_REVOKED="onMessageRevoked",p.MESSAGE_READ_BY_PEER="onMessageReadByPeer",p.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",p.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",p.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",p.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",p.CONVERSATION_LIST_UPDATED="onConversationListUpdated",p.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",p.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",p.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",p.GROUP_LIST_UPDATED="onGroupListUpdated",p.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",p.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",p.TOPIC_CREATED="onTopicCreated",p.TOPIC_DELETED="onTopicDeleted",p.TOPIC_UPDATED="onTopicUpdated",p.PROFILE_UPDATED="onProfileUpdated",p.USER_STATUS_UPDATED="onUserStatusUpdated",p.BLACKLIST_UPDATED="blacklistUpdated",p.FRIEND_LIST_UPDATED="onFriendListUpdated",p.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",p.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",p.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",p.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",p.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",p.KICKED_OUT="kickedOut",p.ERROR="error",p.NET_STATE_CHANGE="netStateChange",p.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",p.SERVER_CONFIG_UPDATED="onServerConfigUpdated",p.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",p.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",p.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",p.RICH_STATUS_CHANGED="onRichStatusChanged"})(rg||(rg={}));var Rg,Dn=rg;(function(p){p.LOGOUT="logout",p.DESTROY="destroy",p.CLOUD_CONFIG_UPDATE="cloud_config_update",p.PROFILE_UPDATE="profile_updated",p.ERROR="error",p.RECONNECTED="reconnected",p.FORCE_OFFLINE="im_open_status.stat_forceoffline",p.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",p.OVERLOAD_PUSH="OverLoadPush.notify2",p.NEW_MESSAGE="new_message",p.MESSAGE_PUSH="im_open_push.msg_push",p.MESSAGE_DELETED="message_deleted",p.MESSAGE_REVOKED="message_revoked",p.MESSAGE_MODIFIED="message_modified",p.SOCKET_DISCONNECTED="socket_disconnected",p.CONVERSATION_UPDATED="conversation_updated",p.TOPIC_MESSAGE_DELETED="topic_message_deleted",p.TOPIC_MESSAGE_REVOKED="topic_message_revoked",p.TOPIC_MESSAGE_MODIFIED="topic_message_modified",p.TOPIC_NEW_MESSAGE="topic_new_message",p.QUALITY_STAT="quality_stat",p.SYNC_CONVERSATION_LIST="sync_conversation_list",p.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(Rg||(Rg={}));var Mr,Ei=Rg;(function(p){p.NEW_INVITATION_RECEIVED="newInvitationReceived",p.INVITEE_ACCEPTED="ts_invitee_accepted",p.INVITEE_REJECTED="ts_invitee_rejected",p.INVITATION_CANCELLED="ts_invitation_cancelled",p.INVITATION_TIMEOUT="ts_invitation_timeout",p.INVITATION_MODIFIED="ts_invitation_modified"})(Mr||(Mr={}));var ro=Mr;const qc=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),zg={MSG_TEXT:"TIMTextElem",MSG_IMAGE:"TIMImageElem",MSG_AUDIO:"TIMSoundElem",MSG_FILE:"TIMFileElem",MSG_FACE:"TIMFaceElem",MSG_VIDEO:"TIMVideoFileElem",MSG_LOCATION:"TIMLocationElem",MSG_GRP_TIP:"TIMGroupTipElem",MSG_GRP_SYS_NOTICE:"TIMGroupSystemNoticeElem",MSG_CUSTOM:"TIMCustomElem",MSG_MERGER:"TIMRelayElem",MSG_STREAM:"TIMStreamElem"};var wg;(function(p){p.UNSENT="unSend",p.SUCCESS="success",p.FAIL="fail"})(wg||(wg={}));const Yr={modify:Ei.MESSAGE_MODIFIED,delete:Ei.MESSAGE_DELETED,revoke:Ei.MESSAGE_REVOKED};var yc;(function(p){p[p.FORWARD=0]="FORWARD",p[p.BACKWARD=1]="BACKWARD"})(yc||(yc={}));const Kc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},zg),{MSG_PRIORITY_HIGH:"High",MSG_PRIORITY_NORMAL:"Normal",MSG_PRIORITY_LOW:"Low",MSG_PRIORITY_LOWEST:"Lowest"}),{RECEIVE_WITH_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT:"AcceptNotNotifyExceptAt",NOT_RECEIVE_MSG_EXCEPT_AT:"NotReceiveMsgExceptAt",MSG_AT_ALL:"__kImSDK_MesssageAtALL__"}),{MSG_REMIND_ACPT_AND_NOTE:"AcceptAndNotify",MSG_REMIND_ACPT_NOT_NOTE:"AcceptNotNotify",MSG_REMIND_DISCARD:"Discard"}),{MessageStatus:wg,Direction:yc}),ag={[Yr.modify]:Ei.TOPIC_MESSAGE_MODIFIED,[Yr.delete]:Ei.TOPIC_MESSAGE_DELETED,[Yr.revoke]:Ei.TOPIC_MESSAGE_REVOKED},Tu={GENDER_UNKNOWN:"Gender_Type_Unknown",GENDER_FEMALE:"Gender_Type_Female",GENDER_MALE:"Gender_Type_Male",USER_STATUS_UNKNOWN:0,USER_STATUS_ONLINE:1,USER_STATUS_OFFLINE:2,USER_STATUS_UNLOGINED:3,USER_NOT_FOUND:"@TLS#NOT_FOUND"},DE=Object.assign({},Tu),_g={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ka=Object.assign(Object.assign(Object.assign(Object.assign({},_g),{CONV_AT_ME:1,CONV_AT_ALL:2,CONV_AT_ALL_AT_ME:3}),{CONV_MARK_TYPE_STAR:1,CONV_MARK_TYPE_UNREAD:2,CONV_MARK_TYPE_FOLD:4,CONV_MARK_TYPE_HIDE:8}),{READ_ALL_C2C_MSG:"readAllC2CMessage",READ_ALL_GROUP_MSG:"readAllGroupMessage",READ_ALL_MSG:"readAllMessage"}),Dc=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},{SNS_TYPE_NO_RELATION:"CheckResult_Type_NoRelation",SNS_TYPE_A_WITH_B:"CheckResult_Type_AWithB",SNS_TYPE_B_WITH_A:"CheckResult_Type_BWithA",SNS_TYPE_BOTH_WAY:"CheckResult_Type_BothWay"}),{ALLOW_TYPE_ALLOW_ANY:"AllowType_Type_AllowAny",ALLOW_TYPE_NEED_CONFIRM:"AllowType_Type_NeedConfirm",ALLOW_TYPE_DENY_ANY:"AllowType_Type_DenyAny"}),{SNS_ADD_TYPE_SINGLE:"Add_Type_Single",SNS_ADD_TYPE_BOTH:"Add_Type_Both"}),{SNS_DELETE_TYPE_SINGLE:"Delete_Type_Single",SNS_DELETE_TYPE_BOTH:"Delete_Type_Both"}),{SNS_APPLICATION_TYPE_BOTH:"Pendency_Type_Both",SNS_APPLICATION_SENT_TO_ME:"Pendency_Type_ComeIn",SNS_APPLICATION_SENT_BY_ME:"Pendency_Type_SendOut",SNS_APPLICATION_AGREE:"Response_Action_Agree",SNS_APPLICATION_AGREE_AND_ADD:"Response_Action_AgreeAndAdd"}),{SNS_CHECK_TYPE_BOTH:"CheckResult_Type_Both",SNS_CHECK_TYPE_SINGLE:"CheckResult_Type_Single"}),{FORBID_TYPE_NONE:"AdminForbid_Type_None",FORBID_TYPE_SEND_OUT:"AdminForbid_Type_SendOut"}),SE={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},La={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},na={JOINED:1,QUITTED:2,KICKED:3,ADMIN_SET:4,ADMIN_CANCELED:5,GROUP_PROFILE_UPDATED:6,GROUP_MEMBER_PROFILE_UPDATED:7,TOPIC_PROFILE_UPDATED:8},Tg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},SE),{GRP_MBR_ROLE_OWNER:"Owner",GRP_MBR_ROLE_ADMIN:"Admin",GRP_MBR_ROLE_MEMBER:"Member",GRP_MBR_ROLE_CUSTOM:"Custom"}),{GRP_TIP_MBR_JOIN:1,GRP_TIP_MBR_QUIT:2,GRP_TIP_MBR_KICKED_OUT:3,GRP_TIP_MBR_SET_ADMIN:4,GRP_TIP_MBR_CANCELED_ADMIN:5,GRP_TIP_GRP_PROFILE_UPDATED:6,GRP_TIP_MBR_PROFILE_UPDATED:7,GRP_TIP_BAN_AVCHATROOM_MEMBER:10,GRP_TIP_UNBAN_AVCHATROOM_MEMBER:11}),{JOIN_OPTIONS_FREE_ACCESS:"FreeAccess",JOIN_OPTIONS_NEED_PERMISSION:"NeedPermission",JOIN_OPTIONS_DISABLE_APPLY:"DisableApply",JOIN_STATUS_SUCCESS:"JoinedSuccess",JOIN_STATUS_ALREADY_IN_GROUP:"AlreadyInGroup",JOIN_STATUS_WAIT_APPROVAL:"WaitAdminApproval"}),{INVITE_OPTIONS_DISABLE_INVITE:"DisableInvite",INVITE_OPTIONS_NEED_PERMISSION:"NeedPermission",INVITE_OPTIONS_FREE_ACCESS:"FreeAccess"}),{GRP_PROFILE_OWNER_ID:"ownerID",GRP_PROFILE_CREATE_TIME:"createTime",GRP_PROFILE_LAST_INFO_TIME:"lastInfoTime",GRP_PROFILE_MEMBER_NUM:"memberNum",GRP_PROFILE_MAX_MEMBER_NUM:"maxMemberNum",GRP_PROFILE_JOIN_OPTION:"joinOption",GRP_PROFILE_INVITE_OPTION:"inviteOption",GRP_PROFILE_INTRODUCTION:"introduction",GRP_PROFILE_NOTIFICATION:"notification",GRP_PROFILE_MUTE_ALL_MBRS:"muteAllMembers"}),{GROUP_ID_PREFIX:La,GROUP_TIPS_OPERATION_TYPE:na}),cI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Bs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},qc),Kc),DE),ka),Dc),Tg),cI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),Uo={NO_SDKAPPID:2e3,NO_TINYID:2022,NO_A2KEY:2023,USER_NOT_LOGGED_IN:2024,REPEAT_LOGIN:2025,MSG_SEND_FAIL:2100,MSG_SEND_FAIL_NOT_IN_AV:2101,MSG_SEND_GRP_WITH_TOPIC_FAIL:2115,MSG_INSTANCE_REQUIRED:2105,MSG_INVALID_CONV_TYPE:2106,MSG_REVOKE_FAIL:2110,MSG_DELETE_FAIL:2111,MSG_UNREAD_ALL_FAIL:2112,READ_RECEIPT_MSG_LIST_EMPTY:2114,CANNOT_DELETE_GRP_SYSTEM_NOTICE:2116,NOT_MY_FRIEND:2700,NETWORK_ERROR:2800,NETWORK_TIMEOUT:2801,NO_NETWORK:2805,UNCAUGHT_ERROR:2903,INVALID_OPERATION:2905,SDK_IS_NOT_READY:2999,LOGGING_IN:3e3,LOGIN_FAILED:3001,KICKED_OUT_MULT_DEVICE:3002,KICKED_OUT_MULT_ACCOUNT:3003,KICKED_OUT_USERSIG_EXPIRED:3004,LOGGED_OUT:3005,KICKED_OUT_REST_API:3006,NO_USE:3122,OPTIONS_IS_EMPTY:3153,MSG_A2KEY_EXPIRED:20002,ACCOUNT_A2KEY_EXPIRED:70001,HELLO_ANSWER_KICKED_OUT:1002,OPEN_SERVICE_OVERLOAD_ERROR:60022},da={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},gr={SYNC_SERVER_INFO_AFTER_RE_ONLINE:"sync-server-info-after-re-online",SYNC_SERVER_INFO_AFTER_LOGIN:"sync-server-info-after-login",RECEIVE_C2C_NEW_MESSAGE:"receive-c2c-new-message",RECEIVE_GROUP_NEW_MESSAGE:"receive-group-new-message",RECEIVE_GROUP_TIPS_NOTIFICATION:"receive-group-tips-notification"},Jt={USER_STATUS_UPDATE:"user-status-update",CONVERSATION_RECOVER:"conversation-recover",HISTORY_MESSAGE_RECOVER:"history-message-recover",BLACKLIST_RECOVER:"blacklist-recover",FRIEND_RECOVER:"friend-recover",GROUP_ATTRIBUTE_CACHE_CLEAR:"group-attribute-cache-clear",UNREAD_MESSAGE_RECOVER:"unread-message-recover",HANDLE_NEW_MESSAGE:"handle-new-message",HANDLE_CONVERSATION_PROFILE_UPDATED:"handle-conversation-profile-updated",COMMERCIAL_CONFIG_UPDATE:"commercial-config-update",UNREAD_MESSAGE_SYNC:"unread-message-sync",FRIEND_AND_BLACKLIST_SYNC:"friend-and-blacklist-sync",SIGNALING_MESSAGE_RECOVER:"signaling-message-recover",GROUP_LIST_SYNC:"group-list-sync",CONVERSATION_LIST_SYNC:"conversation-list-sync",USER_PROFILE_SYNC:"user-profile-sync",CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED:"conversation-update-after-unread-sync-finished",CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED:"conversation-update-after-group-list-sync-finished",HANDLE_C2C_NEW_MESSAGE:"handle-c2c-new-message",HANDLE_GROUP_NEW_MESSAGE:"handle-group-new-message",CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE:"create-or-update-conversation-by-receive-new-message",HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD:"handle-group-tips-from-sync-unread",HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD:"handle-c2c-revoked-message-from-sync-unread",GROUP_REVOKED_NOTICE_RECOVER:"group-revoked-notice-recover",CLOUD_CONFIG_SYNC:"cloud-config-sync",UPDATE_GROUP_NEXT_SEQUENCE:"update-group-next-sequence",EMIT_C2C_MESSAGE_EVENT:"emit-c2c-message-event",EMIT_GROUP_MESSAGE_EVENT:"emit-group-message-event",CONVERSATION_GROUP_LIST_SYNC:"conversation-group-list-sync",CONVERSATION_GROUP_UPDATE:"conversation-group-update",UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED:"update-topic-after-unread-sync-finished",UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE:"update-topic-by-received-new-message",TOPIC_REQUEST_INFO_RESET:"topic-request-info-reset",QUALITY_REPORT:"quality-report",GROUP_TIPS_RECOVER:"group-tips-recover",HANDLE_GROUP_TIPS_NOTIFICATION:"handle-group-tips-notification",C2C_HISTORY_MESSAGE_RECOVER:"c2c-history-message-recover",FRIEND_APPLICATION_LIST_RECOVER:"friend-application-list-recover",EMIT_GROUP_TIPS_EVENT:"emit-group-tips-event",STREAM_MESSAGE_RECOVER:"stream-message-recover"},Wt={[gr.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Jt.USER_STATUS_UPDATE},{stepId:Jt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Jt.UNREAD_MESSAGE_SYNC,dependency:Jt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Jt.CONVERSATION_RECOVER},{stepId:Jt.HISTORY_MESSAGE_RECOVER,dependency:Jt.CONVERSATION_RECOVER},{stepId:Jt.BLACKLIST_RECOVER},{stepId:Jt.FRIEND_RECOVER},{stepId:Jt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Jt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Jt.HISTORY_MESSAGE_RECOVER},{stepId:Jt.GROUP_TIPS_RECOVER,dependency:Jt.HISTORY_MESSAGE_RECOVER},{stepId:Jt.TOPIC_REQUEST_INFO_RESET},{stepId:Jt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Jt.UNREAD_MESSAGE_SYNC},{stepId:Jt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Jt.UNREAD_MESSAGE_SYNC},{stepId:Jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Jt.UNREAD_MESSAGE_SYNC,Jt.CONVERSATION_RECOVER]},{stepId:Jt.EMIT_C2C_MESSAGE_EVENT,dependency:[Jt.UNREAD_MESSAGE_SYNC,Jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Jt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Jt.CONVERSATION_RECOVER},{stepId:Jt.STREAM_MESSAGE_RECOVER}],[gr.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Jt.COMMERCIAL_CONFIG_UPDATE},{stepId:Jt.CLOUD_CONFIG_SYNC},{stepId:Jt.USER_PROFILE_SYNC},{stepId:Jt.UNREAD_MESSAGE_SYNC},{stepId:Jt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Jt.GROUP_LIST_SYNC},{stepId:Jt.CONVERSATION_LIST_SYNC},{stepId:Jt.SIGNALING_MESSAGE_RECOVER,dependency:Jt.UNREAD_MESSAGE_SYNC},{stepId:Jt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Jt.UNREAD_MESSAGE_SYNC]},{stepId:Jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Jt.UNREAD_MESSAGE_SYNC,Jt.CONVERSATION_LIST_SYNC]},{stepId:Jt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Jt.GROUP_LIST_SYNC,Jt.CONVERSATION_LIST_SYNC]},{stepId:Jt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Jt.CONVERSATION_GROUP_UPDATE,dependency:[Jt.CONVERSATION_LIST_SYNC,Jt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Jt.QUALITY_REPORT}],[gr.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Jt.HANDLE_C2C_NEW_MESSAGE},{stepId:Jt.UNREAD_MESSAGE_SYNC},{stepId:Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Jt.HANDLE_C2C_NEW_MESSAGE},{stepId:Jt.EMIT_C2C_MESSAGE_EVENT,dependency:[Jt.HANDLE_C2C_NEW_MESSAGE,Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Jt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Jt.UNREAD_MESSAGE_SYNC]}],[gr.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Jt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Jt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Jt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Jt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Jt.HANDLE_GROUP_NEW_MESSAGE,Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[gr.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Jt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Jt.EMIT_GROUP_TIPS_EVENT,dependency:[Jt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Jt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},Ng={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},lI={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},cr=["login","getMyProfile","getUserProfile","updateMyProfile","setSelfStatus","getUserStatus","subscribeUserStatus","unsubscribeUserStatus","modifyMessage","deleteGroupMember","dismissGroup","getGroupMemberList","getGroupOnlineMemberCount","joinGroup","markGroupMemberList","quitGroup","searchCloudMessages","searchCloudGroups","searchCloudGroupMembers","searchCloudUsers","getMyFollowingList","getMyFollowersList","getMutualFollowersList","followUser","unfollowUser","getUserFollowInfo","checkFollowType","getFriendProfile","addFriend","deleteFriend","updateFriend","checkFriend","setFriendApplicationRead","createFriendGroup","deleteFriendGroup","addToFriendGroup","removeFromFriendGroup","renameFriendGroup","changeGroupOwner","createGroup","dismissGroup","getGroupList","getGroupOnlineMemberCount","getGroupProfile","searchGroupByID","updateGroupProfile","handleGroupApplication","deleteGroupAttributes","getGroupAttributes","initGroupAttributes","setGroupAttributes","addGroupMember","deleteGroupMember","getGroupMemberList","getGroupMemberProfile","setGroupMemberMuteTime","setGroupMemberNameCard","setGroupMemberRole","deleteMessage","revokeMessage","setMessageExtensions","getMessageExtensions","deleteMessageExtensions","getMessageList","addMessageReaction","removeMessageReaction","clearHistoryMessage","sendMessageReadReceipt","getMessageReadReceiptList","getGroupMessageReadMemberList","createMergerMessage","invite","accept","cancel","reject","modifyInvitation","deleteConversation","pinConversation","setMessageRead","setAllMessageRead","getConversationList","getTotalUnreadMessageCount","renameConversationGroup","deleteConversationGroup","markConversation","setConversationCustomData","deleteConversationsFromGroup","addConversationsToGroup","createConversationGroup"];var KI=Object.freeze({__proto__:null,ERROR_CODE:Uo,InnerEvent:Ei,NEED_LOG_API:cr,OuterConstant:Bs,OuterEvent:Dn,PUSH:cI,QUALITY_METRICS:Ng,SDK_EDITION:da,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:lI,SignalingEvent:ro,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Wt,WORKFLOW_NAME:gr,WORKFLOW_STEP:Jt}),za,ra,un;(function(p){p[p.USER_INITIATED=0]="USER_INITIATED",p[p.KICKED_OUT=1]="KICKED_OUT"})(za||(za={})),function(p){p[p.multipleAccount=1]="multipleAccount",p[p.multipleDevice=2]="multipleDevice",p[p.restApi=3]="restApi"}(ra||(ra={})),function(p){p[p.multipleDevice=3002]="multipleDevice",p[p.multipleAccount=3003]="multipleAccount",p[p.usersigExpired=70001]="usersigExpired",p[p.restApi=20002]="restApi"}(un||(un={}));const Sn={[ra.multipleAccount]:"multipleAccount",[ra.multipleDevice]:"multipleDevice",[ra.restApi]:"REST_API_Kick",[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[un.usersigExpired]:"userSigExpired"},Nu="login_online_presence_task",{ERROR:Gg,DESTROY:Ua,FORCE_OFFLINE:jc}=Ei,{KICKED_OUT_MULT_ACCOUNT:jI,KICKED_OUT_MULT_DEVICE:ME,KICKED_OUT_REST_API:II,ACCOUNT_A2KEY_EXPIRED:Gu,MSG_A2KEY_EXPIRED:wl}=Uo;class Sc{init(){const{notificationCenter:B}=Se;B.subscribeInnerEvent(jc,this._handleForceOfflineFromServerPush,this),B.subscribeInnerEvent(Gg,wl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Gg,Gu,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),B.subscribeInnerEvent(Gg,jI,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Gg,ME,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Gg,II,this._handleForceOfflineFromResponse,this),B.subscribeInnerEvent(Ua,this._dispose,this)}_handleForceOfflineFromServerPush(B){var v;if(((v=Se.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)===!0){const{EventArray:G=[]}=B?.body||{};this._extractKickedOutMessages(G).forEach(O=>{const{KickoutMsgNotify:{KickType:z,NewInstInfo:X,Instid:rA}}=O;this._isCurrentInstanceKickedOut(rA)&&this._processKickedOutReasonInfo({kickedOutReasonCode:z,newInstanceInfo:X})})}}_extractKickedOutMessages(B){return B.reduce((v,G)=>[...v,...G.C2cNotifyMsgArray||[]],[]).filter(v=>{var G;return this._isKickedOut((G=v?.KickoutMsgNotify)===null||G===void 0?void 0:G.KickType)})}_handleForceOfflineFromResponse(B){const{errorCode:v}=B;this._processKickedOutReasonInfo({kickedOutReasonCode:v})}_processKickedOutReasonInfo(B){return mA(this,void 0,void 0,function*(){const{kickedOutReasonCode:v}=B,{ssoLog:G,utils:{safeStringify:O}}=Se;try{this._logKickedOutEvent(B),this._shouldLogoutAfterKickedOut(v)?yield Se.login.loginAction.logout(za.KICKED_OUT):Se.login.loginAction.handleLogoutCompleted()}catch(z){G.debug("_processKickedOutReasonInfo",` fail ${O(z)}`)}finally{Se.notificationCenter.emitOuterEvent(Dn.KICKED_OUT,{data:{type:Sn[v]},name:Dn.KICKED_OUT})}})}_logKickedOutEvent(B){const{kickedOutReasonCode:v,newInstanceInfo:G={}}=B,O=`type:${Sn[v]} newInstanceInfo: ${JSON.stringify(G)}`;Se.ssoLog.warn("kickedOut",O)}_isKickedOut(B){return[ra.multipleAccount,ra.multipleDevice,ra.restApi].includes(B)}_isChatLoginEvent(B){const{requestHead:v}=B||{};return v?.idtype!==1}_shouldLogoutAfterKickedOut(B){return![un.usersigExpired,ra.restApi].includes(B)}_isCurrentInstanceKickedOut(B){const{isLoggedIn:v,statusInstanceId:G}=Se.store.get("login")||{};return v===!0&&B===G}_dispose(){const{notificationCenter:B}=Se;B.unSubscribeInnerEvent(jc,this._handleForceOfflineFromServerPush,this),B.unSubscribeInnerEvent(Gg,Gu,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,wl,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,jI,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,ME,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Gg,II,this._handleForceOfflineFromResponse,this),B.unSubscribeInnerEvent(Ua,this._dispose,this)}}function bu(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.wslogin",v=Se.common.generateProtocolData({servcmd:B,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:p}}),G=`${v.head.seq}${B}`,O=yield Se.channel.sendPacket(v,{timeout:9e4,requestId:G});if(O){const{HelloInterval:z,InstId:X,TinyId:rA,TimeStamp:DA,CustomStatus:GA,PurchaseBits:JA,A2Key:ne,RichMsgAuthKey:he,ErrorCode:Ze,ErrorInfo:st,ActionStatus:at}=O;return{helloInterval:z,instanceID:X,tinyID:rA,timeStamp:DA,customStatus:GA,purchaseBits:JA,a2Key:ne,authKey:he,errorCode:Ze,errorInfo:st,actionStatus:at}}})}function ku(){const{store:p}=Se;return ua(p.get("instance").sdkAppId)!==gt.CHINA}function _l(p){var B;try{const v=eo.getStorage("errorMessage");if(!p||!v)return"";const G=((B=JSON.parse(v))===null||B===void 0?void 0:B.errorMessage)||{},{code:O,replacement1:z="",replacement2:X=""}=p;if(!O)return"";const rA=ku()?`${O}_en`:`${O}_cn`;let DA=G[G[rA]?rA:O]||"";return DA&&(z&&(DA=DA.replace("$replacement1",z)),X&&(DA=DA.replace("$replacement2",X))),DA}catch(v){return console.warn("Error parsing stored error messages:",v),""}}class rs extends Error{constructor(B={}){B.code=B.code||B.errorCode;let{functionName:v="Unknown",code:G,message:O="",data:z="",moreMessage:X="",errorMessage:rA=""}=B;rA=(G?_l(B):"")||rA||O;let DA=G?`${v} failed. error: {"message": ${rA}, "code": ${G}}`:`${v} failed. error: {"message": ${rA}}`;DA=`${DA} ${X}`,super(),this.code=G,this.errorCode=G,this.errorMessage=rA,this.message=DA,this.data=z}}function gs(p,B){var v;if(p&&((v=Se.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)!==!0)throw new rs({code:Uo.USER_NOT_LOGGED_IN,functionName:B})}function ud(p,B,v){if(Array.isArray(p))for(let G=0;G{return GA===(JA=G,Object.prototype.toString.call(JA).match(/^\[object (.*)\]$/)[1].toLowerCase());var JA})){for(let JA=0;JA{const{interceptor:O,context:z}=G;O.apply(z,[v])})}(p)}function vr(p,B){EI.push({interceptor:p,context:B})}function Mc(p){const{params:B,auth:v}=p;B&&typeof B=="object"&&Object.assign(Ed,B),v&&typeof v=="object"&&Object.assign(vE,v)}function Wc(p){return Se.store.get("commercialConfig").get(p)}class tn{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(B,v)=>{const G=Date.now();v?(this._stepStartTimes.set(`${B}-${v}`,G),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${v} started at ${new Date(G).toISOString()}`)):(this._workflowStartTimes.set(B,G),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] started at ${new Date(G).toISOString()}`))},success:(B,v)=>{const G=Date.now();if(v){const O=this._stepStartTimes.get(`${B}-${v}`),z=O?G-O:0;this._stepStartTimes.delete(`${B}-${v}`),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] Step ${v} completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}else{const O=this._workflowStartTimes.get(B),z=O?G-O:0;this._workflowStartTimes.delete(B),Se.ssoLog.debug("_executeWorkflowStep",`[Workflow ${B}] completed successfully at ${new Date(G).toISOString()} (${z}ms)`)}},error:(B,v,G)=>{const{ssoLog:O,utils:{safeStringify:z}}=Se,X=Date.now();if(v){const rA=this._stepStartTimes.get(`${B}-${v}`),DA=rA?X-rA:0;this._stepStartTimes.delete(`${B}-${v}`),O.error("_executeWorkflowStep",`[Workflow ${B}] Step ${v} failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}else{const rA=this._workflowStartTimes.get(B),DA=rA?X-rA:0;this._workflowStartTimes.delete(B),O.error("_executeWorkflowStep",`[Workflow ${B}] failed at ${new Date(X).toISOString()} (${DA}ms) ${z(G)}`,{error:G})}}}}static getInstance(){return tn._instance||(tn._instance=new tn),tn._instance}static setInstance(B){tn._instance=B}init(){this._initializeWorkflows()}registerWorkflowStep(B,v,G,O){if(!this._handlers.has(B))return void Se.ssoLog.debug("registerWorkflowStep",`Workflow '${B}' not defined in core`);if(!Wt[B].find(X=>X.stepId===v))return void Se.ssoLog.debug("registerWorkflowStep",`Step '${v}' not defined in workflow '${B}'`);const z=this._handlers.get(B);z.has(v)||z.set(v,O?G.bind(O):G)}executeWorkflow(B,v){return mA(this,void 0,void 0,function*(){if(!this._validateWorkflow(B))return;Se.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Started execution at ${new Date().toISOString()}`);const G=Wt[B],O={},z={cancelled:!1};this._activeWorkflows.set(B,{cancelToken:z});try{const X=new Map;G.forEach(DA=>{X.set(DA.stepId,DA)});const rA={workflowName:B,pendingSteps:new Set(G.map(DA=>DA.stepId)),completedSteps:new Set,runningSteps:new Set,stepMap:X,stepResults:O,data:v,cancelToken:z};yield new Promise((DA,GA)=>{const JA=()=>{if(z.cancelled)return void DA();this._getExecutableSteps({pendingSteps:rA.pendingSteps,completedSteps:rA.completedSteps,stepMap:rA.stepMap,workflowName:B}).filter(ne=>!rA.runningSteps.has(ne)).forEach(ne=>{rA.completedSteps.has(ne)||rA.runningSteps.has(ne)||this._executeWorkflowStep(ne,rA,{onComplete:()=>{if(rA.pendingSteps.size===0)return void DA();this._getExecutableSteps({pendingSteps:rA.pendingSteps,completedSteps:rA.completedSteps,stepMap:rA.stepMap,workflowName:B}).filter(he=>!rA.runningSteps.has(he)).length===0&&rA.runningSteps.size===0&&(Se.ssoLog.debug("executeWorkflow",`Workflow ${B} completed with some steps skipped due to dependency failures`),DA())},onError:GA,onStepComplete:JA})})};JA()}),Se.ssoLog.debug("executeWorkflow",`[Workflow ${B}] Completed execution at ${new Date().toISOString()}`)}catch(X){Se.ssoLog.error("executeWorkflow",`[Workflow ${B}] Failed execution at ${new Date().toISOString()}`,{error:X})}finally{this._activeWorkflows.delete(B)}})}_executeWorkflowStep(B,v,G){return mA(this,void 0,void 0,function*(){const{workflowName:O,runningSteps:z,stepMap:X,stepResults:rA,data:DA}=v;z.add(B),this._logWorkflowExecution(O,B,"start");try{const GA=X.get(B);let JA=null;GA?.dependency&&(c(GA.dependency)?JA=rA[GA.dependency]:Array.isArray(GA.dependency)&&(JA={},GA.dependency.forEach(he=>{JA[he]=rA[he]})));const ne=this._handlers.get(O).get(B);if(ne){const he=yield Promise.resolve(ne({data:DA,result:JA}));rA[B]=he,this._logWorkflowExecution(O,B,"success")}v.completedSteps.add(B)}catch(GA){const JA=`[Workflow].${O}.${B}`,{errorCode:ne,errorInfo:he=`${JA} failed`}=GA||{},Ze=new rs({functionName:JA,code:ne,message:he});Se.ssoLog.error(JA,he,{error:Ze}),this._logWorkflowExecution(O,B,"error",GA),G.onError(GA)}finally{z.delete(B),v.pendingSteps.delete(B),G.onStepComplete(),G.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Wt).forEach(B=>{this._handlers.has(B)||this._handlers.set(B,new Map)})}_cancelWorkFlow(B){const v=this._activeWorkflows.get(B);if(!v)return;const{cancelToken:G}=v;G.cancelled=!0,this._activeWorkflows.delete(B)}_cancelAllWorkflows(){Object.keys(Wt).forEach(B=>{this._cancelWorkFlow(B)})}_validateWorkflow(B){return Wt[B]?!!this._handlers.get(B):!1}_getExecutableSteps(B){const{pendingSteps:v,completedSteps:G,stepMap:O,workflowName:z}=B;return Array.from(v).filter(X=>{const rA=O.get(X)||{},{dependency:DA,skipIfDependencyMissing:GA=!0}=rA;if(!DA)return!0;if(c(DA))return this._isStepRegistered({workflowName:z,stepId:DA})?G.has(DA):!GA;if(C(DA)){if(DA.filter(JA=>!this._isStepRegistered({workflowName:z,stepId:JA})).length>0&&GA)return!1;for(const JA of DA)if(!G.has(JA))return!1;return!0}return!1})}_isStepRegistered(B){var v;const{workflowName:G,stepId:O}=B;return(v=this._handlers.get(G))===null||v===void 0?void 0:v.has(O)}_logWorkflowExecution(B,v,G,O){this._logHandlers[G](B,v)}}const ws=new Map,Ca=({type:p,groupID:B})=>p===Bs.GRP_COMMUNITY||`${B}`.startsWith(La.COMMUNITY)&&!`${B}`.includes(La.TOPIC),$r=(p="")=>{const B=p.startsWith("GROUP")?p.replace("GROUP",""):p;return B.startsWith(La.COMMUNITY)&&`${B}`.includes(La.TOPIC)},zc="openim",dd="million_group_open_http_svc";function Zg(p){return mA(this,void 0,void 0,function*(){const{servcmd:B,data:v}=function(z){const{data:X}=z;return gg(X)||RE(X)}(p)?function(z){let{servcmd:X,data:rA}=z;return RE(rA)?function(DA){const{servcmd:GA,data:JA}=DA;let{GroupId:ne=""}=JA;const he=ne;return[ne]=he.split(La.TOPIC),{servcmd:Xg(GA),data:Object.assign(Object.assign({},JA),{GroupId:ne,TopicId:he})}}(z):(gg(rA)&&(X=Xg(X)),{servcmd:X,data:rA})}(p):p,G=Se.common.generateProtocolData({servcmd:B,data:v}),O=`${G.head.seq}${B}`;return Se.channel.sendPacket(G,{requestId:O,timeout:p.timeout})})}function gg(p){const{Type:B,GroupId:v,GroupIdList:G=[]}=p,O=v||G[0]||"";return Ca({type:B,groupID:O})}function RE(p){const{GroupId:B=""}=p;return $r(B)}function Xg(p){if(p.includes(zc))return p;const B=p.split(".")[1];return`${dd}.${B}`}function jn(){var p;return(p=Se.store.get("login"))===null||p===void 0?void 0:p.userId}const ir=p=>C(p)||f(p),Fa=(p,B,v,G)=>{if(!ir(p)||!ir(B))return 0;let O=0;const z=Object.keys(B);let X;for(let rA=0,DA=z.length;rA{if(n(B))return"";if(p===Bs.MSG_TEXT)return B.text||"";const v=Lu[p];return v?EC(v):""},Zc=[{cmd:"ws_get_user_status",interval:5,count:20},{cmd:"ws_status_subscribe",interval:5,count:20},{cmd:"ws_status_unsubscribe",interval:5,count:20},{cmd:"get_group_self_member_info",interval:5,count:20},{cmd:"modify_group_base_info",interval:1,count:8},{cmd:"get_pendency",interval:1,count:15},{cmd:"set_group_attr",interval:5,count:10},{cmd:"modify_group_attr",interval:5,count:10},{cmd:"delete_group_attr",interval:5,count:10},{cmd:"clear_group_attr",interval:5,count:10},{cmd:"get_group_attr",interval:5,count:20},{cmd:"update_group_counter",interval:5,count:20},{cmd:"get_group_counter",interval:5,count:20},{cmd:"get_topic",interval:1,count:10},{cmd:"read_all_unread_msg",interval:1,count:1},{cmd:"query",interval:5,count:20}],Xc="im_sdk_config_mgr.fetch_config",zI="im_sdk_config_mgr.push_configv2",dI="cloud-config",$c=2996,Al=new class{init(p){this.core=p}};function va(p){return mA(this,void 0,void 0,function*(){const{sdkAppId:B}=Al.core.store.get("instance")||{},v=Al.core.helper.generateProtocolData({servcmd:Xc,data:{uint32_sdkappid:B,uint64_version:p}}),G=`${v.head.seq}${Xc}`;return Al.core.channel.sendPacket(v,{requestId:G})})}var bg=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,helper:G,constants:{WORKFLOW_NAME:O,WORKFLOW_STEP:z},channel:X}=p;B.subscribeInnerEvent(zI,this._handlePushedConfig,this),G.registerWorkflowStep(O.SYNC_SERVER_INFO_AFTER_LOGIN,z.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),G.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Zc),X.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(p){return mA(this,void 0,void 0,function*(){var B;const v={code:0,data:""};return p&&(v.data=((B=this._core.store.get("cloudConfig"))===null||B===void 0?void 0:B[p])||""),v})}checkMethodCallOverLimit(p){if(!this._cmdFrequencyLimitMap.has(p))return;if(!this._methodCallFrequencyMap.has(p))return void this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});const{count:B,interval:v}=this._cmdFrequencyLimitMap.get(p);let{startTime:G,methodCallCounter:O}=this._methodCallFrequencyMap.get(p);if(Date.now()-G>1e3*v)this._methodCallFrequencyMap.set(p,{startTime:Date.now(),methodCallCounter:1});else if(O+=1,this._methodCallFrequencyMap.set(p,{startTime:G,methodCallCounter:O}),O>B)throw new this._core.helper.ChatError({code:$c,replacement1:p})}_handlePushedConfig(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=this._core;B.info("_handlePushedConfig",v(p)),yield this._updateCloudConfig(p)})}_handleLoginSuccess(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;try{if(this._canFetch()){const v=yield va(this._version);p.info("_fetchCloudConfigIfLogin",B(v)),yield this._updateCloudConfig(v)}this._core.helper.taskScheduler.addTask({id:dI,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(v){p.debug("_fetchCloudConfigIfLogin",B(v))}})}_fetchCloudConfigIfReady(){return mA(this,void 0,void 0,function*(){const{ssoLog:p,utils:{safeStringify:B}}=this._core;if(this._canFetch())try{const v=yield va(this._version);p.info("_fetchCloudConfigIfReady",B(v)),yield this._updateCloudConfig(v)}catch(v){p.error("_fetchCloudConfigIfReady",B(v))}})}_updateCloudConfig(p){return mA(this,void 0,void 0,function*(){const B=this._parseCloudConfig(p);B&&(this._core.store.set("cloudConfig",B),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,B),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:B}}))})}_canFetch(){const{isLoggedIn:p}=this._core.store.get("login")||{};return p&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(p){const{int32_error_code:B,str_error_message:v,str_json_config:G,uint32_expired_time:O,uint32_sdkappid:z,uint64_version:X}=p;let rA=null;if(B===0){if(this._version!==X)try{rA=JSON.parse(G),this._version=X}catch{}this._expirationTime=Date.now()+1e3*O}else this._expirationTime=B===void 0?Date.now()+36e5:Date.now()+12e4;return rA}_parseCmdFreqLimit(){return mA(this,void 0,void 0,function*(){var p;let B=(p=yield this.getServerConfig("cmd_frequency_limit"))===null||p===void 0?void 0:p.data;const{isEmpty:v}=this._core.utils;if(!v(B))try{B=JSON.parse(B),this._updateCmdFreqLimitMap(B)}catch(G){console.warn(G)}})}_updateCmdFreqLimitMap(p){p.forEach(B=>{this._cmdFrequencyLimitMap.set(B.cmd,{interval:B.interval,count:B.count})})}_reset(){this._core.helper.taskScheduler.removeTask(dI),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Zc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(zI,this._handlePushedConfig,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}};class Ds{constructor(B=0,v=0){this.high=B,this.low=v}equal(B){return B!==null&&this.low===B.low&&this.high===B.high}toString(){const B=Number(this.high).toString(16);let v=Number(this.low).toString(16);if(v.length<8){let G=8-v.length;for(;G;)v=`0${v}`,G--}return B+v}}const Wn={SEARCH_GRP_SNS:new Ds(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new Ds(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new Ds(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new Ds(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new Ds(0,Math.pow(2,6)).toString(),USER_STATUS:new Ds(0,Math.pow(2,7)).toString(),CONV_MARK:new Ds(0,Math.pow(2,9)).toString(),CONV_GROUP:new Ds(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new Ds(0,Math.pow(2,11)).toString(),MSG_EXT:new Ds(0,Math.pow(2,13)).toString(),GRP_COUNTER:new Ds(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new Ds(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new Ds(Math.pow(2,7)).toString(),PLUGIN_CS:new Ds(Math.pow(2,8)).toString(),PLUGIN_PUSH:new Ds(Math.pow(2,9)).toString(),PLUGIN_BOT:new Ds(Math.pow(2,10)).toString(),MSG_REACTION:new Ds(Math.pow(2,16)).toString(),FOLLOW:new Ds(Math.pow(2,20)).toString()},vc="CommercialConfig",ZI="commercial-config";var XI=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(p){this._core=p;const{helper:B,notificationCenter:v,constants:{WORKFLOW_NAME:G,WORKFLOW_STEP:O,InnerEvent:z}}=p;v.subscribeInnerEvent(z.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),v.subscribeInnerEvent(z.LOGOUT,this._handleLogout,this),v.subscribeInnerEvent(z.DESTROY,this._dispose,this),B.registerWorkflowStep(G.SYNC_SERVER_INFO_AFTER_LOGIN,O.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),p.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),p.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(p){return mA(this,void 0,void 0,function*(){const B=parseInt(p,10).toString(2),{length:v}=B;let G,O=!0;for(let z=v-1,X=0;z>=0;z--,X++)if(B.charAt(z)==="1"&&(G=X<32?new Ds(0,2**X).toString():new Ds(2**(X-32),0).toString(),!this._featureMap.get(G))){O=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${vc}.isFeatureEnabled decimalNumber:${p} key:${G} ret:${O}`),{code:0,data:{enabled:O}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return mA(this,void 0,void 0,function*(){var p;const{ssoLog:B,utils:{safeStringify:v},common:{buildAndSendPacket:G}}=this._core;try{this._isFetching=!0;const O=yield G({servcmd:"im_sdk_config_mgr.fetch_imsdk_purchase_bitsv2",data:{uint32_sdkappid:(p=this._core.store.get("instance"))===null||p===void 0?void 0:p.sdkAppId}});O&&(this._parseCommercialConfig(O),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(O){B.error("_fetchAndParseCommercialConfig",v(O))}finally{this._isFetching=!1}})}_syncCommercialConfig(p){return mA(this,void 0,void 0,function*(){const{purchaseBits:B}=p?.data||{};B&&(this._parsePurchaseBits(B),this._core.store.set("commercialConfig",this._methodKeyMap)),this._canFetch()&&(yield this._fetchAndParseCommercialConfig()),this._core.helper.taskScheduler.addTask({id:ZI,intervalMs:1e3,callback:this._fetchCommercialConfigIfReady,context:this})})}_canFetch(){var p;const B=(p=this._core.store.get("login"))===null||p===void 0?void 0:p.isLoggedIn,v=Date.now()>=this._expirationTime;return B&&!this._isFetching&&v}_handlePushedConfig(p){p?.body&&(this._parseCommercialConfig(p.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return mA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(p){const{ssoLog:B}=this._core;if(typeof p!="object")return;const{int32_error_code:v,str_error_message:G,str_purchase_bits:O,uint32_expired_time:z}=p;v===0?(this._parsePurchaseBits(O),this._expirationTime=Date.now()+1e3*z):v===void 0?(B.warn("_parseCommercialConfig",`${vc}._parseCommercialConfig failed. Invalid message format:`,p),this._expirationTime=Date.now()+36e5):(B.warn("_parseCommercialConfig",`${vc}._parseCommercialConfig errorCode:${v} errorMessage:${G}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(p){return p&&typeof p=="string"&&p.length>=1&&p.length<=64&&/[01]{1,64}/.test(p)}_parsePurchaseBits(p){const{ssoLog:B,utils:{safeStringify:v}}=this._core;if(this._isValidPurchaseBits(p)){this._purchaseBits=p,this._featureMap.clear(),this._methodKeyMap.clear();let G=null;for(let O=p.length-1,z=0;O>=0;O--,z++)if(G=z<32?new Ds(0,2**z).toString():new Ds(2**(z-32),0).toString(),p[O]==="1"){this._featureMap.set(G,!0);const X=this._getKeyByValue(Wn,G);X&&this._methodKeyMap.set(X,!0)}else{this._featureMap.set(G,!1);const X=this._getKeyByValue(Wn,G);X&&this._methodKeyMap.set(X,!1)}}else B.warn("_parsePurchaseBits",`${vc}.parsePurchaseBits invalid purchases:${v(p)}`)}_getKeyByValue(p,B){const v=Object.entries(p).find(([G,O])=>O===B);return v?v[0]:void 0}_handleLogout(){this._reset()}_dispose(){this._reset(),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),this._core.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this)}_reset(){this._core.helper.taskScheduler.removeTask(ZI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},wE=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,channel:G}=this._core;B.subscribeInnerEvent(v.OVERLOAD_PUSH,this._handleOverLoadPush,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),G.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(p){if(!this._serverOverloadInfoMap.has(p))return;const{overloadStartTimestamp:B,delaySeconds:v}=this._serverOverloadInfoMap.get(p);if(Date.now()-B<=1e3*v)throw new this._core.helper.ChatError({functionName:p,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(p)}_handleOverLoadPush(p){const{OverLoadServCmd:B,DelaySecs:v}=p;this._serverOverloadInfoMap.set(B,{overloadStartTimestamp:Date.now(),delaySeconds:v})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.OVERLOAD_PUSH,this._handleOverLoadPush,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this)}},ch=new class{constructor(){this.name="ConfigCenter"}install(p){Al.init(p),bg.install(p),XI.install(p),wE.install(p)}},dC=new class{constructor(){this.name="ErrorMessage",this._core=null}install(p){return mA(this,void 0,void 0,function*(){if(this._core=p,this._canFetch()){const B=yield this._fetchErrorMessage();if(!B)return;const v=this._parseResponse(B);this._saveErrorMessage(v)}})}_canFetch(){const p=this._core.store.getStorage("errorMessage");return!p||this._isExpired(p)}_saveErrorMessage(p){this._core.store.setStorage("errorMessage",{errorMessage:p,errorMessageSavedTime:new Date().getTime()})}_fetchErrorMessage(){return mA(this,void 0,void 0,function*(){try{return yield this._core.helper.httpRequest({method:"GET",url:"https://web.sdk.qcloud.com/im/download/error-message/v3/0.0.6/tim-error-message.txt"})}catch(p){console.error(p)}})}_isExpired(p){if(!p)return!0;const{errorMessageSavedTime:B}=p;return B&&new Date().getTime()-B>=6048e5}_parseResponse(p){if(typeof p=="string"){const B=p.split(`; +`),v={},G=new RegExp(/'/g);for(let O=0;O{var co,Xi,di;const xo=function(ts,mi){const{From_Account:zi,From_AccountHeadurl:Ws,From_AccountNick:Ne,IsNeedReadReceipt:Tt,MsgBody:FA,MsgClientTime:Ai,MsgRandom:En,MsgSeq:ii,MsgTimeStamp:us,SendMsgControl:wi,SupportMessageExtension:Bo,To_Account:Bt,TinyId:mt,MsgCheckResult:ug,CloudCustomData:Ls,IsPeerRead:Zi,MsgFlagBits:Hr,MsgVersion:oc,EventArray:os}=ts;return{from:zi,avatar:Ws,nick:Ne,needReadReceipt:Tt===1,readReceiptSentByPeer:Zi,clientTime:Ai,messageFlagBits:Hr,random:En,sequence:ii,time:us,messageControlInfo:wi,isSupportExtension:Bo,to:Bt,tinyID:mt,checkResult:ug,cloudCustomData:Ls,messageVersion:oc,eventArray:os,elements:mi.message.messageHelper.parseServerPushMessageElement(FA)}}(Pi,at);if(!((di=(Xi=(co=Pi?.EventArray)===null||co===void 0?void 0:co[0])===null||Xi===void 0?void 0:Xi.hasOwnProperty)===null||di===void 0)&&di.call(Xi,"C2cNotifyMsgArray"))Ht.push(...function(ts){var mi;const zi=[];return(mi=ts.EventArray)===null||mi===void 0||mi.forEach(Ws=>{var Ne,Tt;const{C2cNotifyMsgArray:FA}=Ws,Ai=(Tt=(Ne=FA?.[0])===null||Ne===void 0?void 0:Ne.WithdrawC2cMsgNotify)===null||Tt===void 0?void 0:Tt.C2cWithdrawInfoArray;Array.isArray(Ai)&&zi.push(...Ai)}),zi}(Pi));else{const ts=at.message.messageFactory.createMessage(Object.assign(Object.assign({},xo),{conversationType:"C2C",flow:"in"})),{elements:mi}=xo;ts.setElement(mi),Ft.push(ts)}}),{unreadMessageList:Ft,revokedMessageList:Ht}}(DA.MsgList,B);return{syncFlag:DA?.SyncFlag,unreadMessageList:he,revokedMessageList:Ze,unreadCountList:GA,overflowUnreadCountList:JA,cookie:DA?.Cookie,groupTipList:ne}}catch(DA){console.warn(DA)}})}var el,kg;(function(p){p[p.START_SYNC=0]="START_SYNC",p[p.SYNCING=1]="SYNCING",p[p.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(el||(el={})),function(p){p[p.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",p[p.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(kg||(kg={}));var ao=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(p){this._core=p;const{constants:B}=p;p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),p.helper.registerWorkflowStep(B.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,B.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(p){return mA(this,void 0,void 0,function*(){const{isAfterReOnline:B=!1,isAfterNewMessageReceived:v=!1,isAfterLogin:G=!1}=p||{};let O=el.START_SYNC;const z=[],X=[],rA=[],DA=[];for(;this._canContinueSync({cookie:this._cookie,syncFlag:O});){const GA=yield this._fetchUnreadDBMessage({cookie:this._cookie,syncFlag:O,syncTriggerEvent:v?kg.NEW_MESSAGE_RECEIVED:kg.LOGIN_SUCCESS});if(!GA)break;const{unreadMessageList:JA=[],revokedMessageList:ne=[],overflowUnreadCountList:he,unreadCountList:Ze,groupTipList:st}=GA;if(this._cookie=GA?.cookie||"",O=GA?.syncFlag,this._parseAndSaveUnreadMessageList(JA),rA.push(...ne),this._updateConversationUnreadOptions({unreadCountList:Ze,overflowUnreadCountList:he,conversationUpdateFieldList:z}),Array.isArray(st)&&X.push(...st),B){const{messages:at}=this._handleNewMessageList(JA);DA.push(...at)}}return B?{conversationUpdateFieldList:z,revokedMessageList:rA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X,messages:DA,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:z,isInstantMessage:!G,isUnreadC2CMessage:!0,revokedMessageList:rA,unreadMessageMap:this._unreadDBMessageMap,groupTipList:X}})}_syncUnreadDBMessageAfterLogin(){return mA(this,void 0,void 0,function*(){return this._cookie="",this._syncUnreadMessage({isAfterLogin:!0})})}_syncUnreadDBMessageAfterNewMessageReceived(p){return mA(this,void 0,void 0,function*(){if(p.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(p){const{unreadCountList:B,overflowUnreadCountList:v,conversationUpdateFieldList:G}=p,{constants:{OuterConstant:{CONV_C2C:O,CONV_SYSTEM:z}}}=this._core;B?.forEach(X=>{const{From_Account:rA,UnreadCount:DA}=X;if(rA!==z){const GA=G.find(({conversationID:JA})=>JA===`${O}${rA}`);GA?GA.unreadCount=DA:G.push({conversationID:`${O}${rA}`,unreadCount:DA,type:O})}}),v?.forEach(X=>{const{From_Account:rA,LastMsgTime:DA}=X;rA!==z&&(G.find(({conversationID:GA})=>GA===`${O}${rA}`)||G.push({conversationID:`${O}${rA}`,type:O,lastMsgTime:DA}))})}_syncUnreadDBMessageAfterReOnline(){return mA(this,void 0,void 0,function*(){return this._syncUnreadMessage({isAfterReOnline:!0})})}_updateMessageProfile(p){var B;const{messageDataHandler:v}=this._core.message||{},G=(B=this._core.store.get("login"))===null||B===void 0?void 0:B.userId,{from:O,nick:z,avatar:X,conversationID:rA=""}=p;if(O!==G){const DA=v.getLatestMsgSentByPeer(rA);if(DA){const{nick:GA,avatar:JA}=DA;z&&X?z===GA&&X===JA||v.updateNickAndAvatarOfSentMessage({conversationID:rA,latestNick:z,latestAvatar:X,isSentByMe:!1}):(p.nick=GA,p.avatar=JA)}}else{const DA=v.getLatestMsgSentByMe(rA);!DA||z===DA.nick&&X===DA.avatar||v.updateNickAndAvatarOfSentMessage({conversationID:rA,latestNick:z,latestAvatar:X,isSentByMe:!0})}}_handleNewMessageList(p){const{messageDataHandler:B}=this._core.message||{},v=new Map,G=[];return p.forEach(O=>{this._updateMessageProfile(O);let z=O.isModified===1;if(B.isMessageSentByCurrentInstance(O)?O.isModified=z:z=!1,O.isOnlineMessage())O._onlineOnlyFlag=!0,B.isMessageSentByCurrentInstance(O)||G.push(O);else if(this._shouldStoreUnreadMessage(O)){if(B.storeConversationMessage(O)){const{conversationID:X,conversationType:rA,conversationSubType:DA,flow:GA,_isExcludedFromUnreadCount:JA,_isExcludedFromLastMessage:ne}=O,he=ne?"":O;v.has(X)?(v.get(X).lastMessage=he,GA==="in"&&(JA||v.get(X).unreadCount++)):v.set(X,{conversationID:X,type:rA,subType:DA,unreadCount:JA||GA!=="in"?0:1,lastMessage:he})}B.isMessageSentByCurrentInstance(O)&&!z||G.push(O)}}),{messages:G,conversationOptions:v}}_shouldStoreUnreadMessage(p){var B;const{conversationID:v}=p,{message:G,appStore:O,utils:{isEmpty:z}}=this._core||{},X=Array.from(((B=O.conversationStore.getConversationMap())===null||B===void 0?void 0:B.keys())||[]),rA=this._getLocalLastMessageTime(v);return!G.messageDataHandler.isInMessageList(p)&&X.includes(v)&&this._localConversationIDListBeforeDisconnect.includes(v)&&!z(rA)}_fetchUnreadDBMessage(p){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=this._core;try{B.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${v(p)}`);const O=yield lh(p,this._core);if(!O)return null;const{syncFlag:z,unreadMessageList:X,revokedMessageList:rA,cookie:DA,unreadCountList:GA,overflowUnreadCountList:JA,groupTipList:ne}=O;return this._parseAndSaveUnreadMessageList(X),{syncFlag:z,cookie:DA,unreadMessageList:X,revokedMessageList:rA,unreadCountList:GA,overflowUnreadCountList:JA,groupTipList:ne}}catch(G){console.log(G)}})}_canContinueSync({cookie:p,syncFlag:B}){var v;return B===el.START_SYNC||B===el.SYNCING&&!(!((v=this._core)===null||v===void 0)&&v.helper.isEmpty(p))}_parseAndSaveUnreadMessageList(p){p.forEach(B=>{const{ID:v}=B;this._unreadDBMessageMap.set(v,B)})}_handleDisconnect(){var p;const{appStore:B}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((p=B.conversationStore.getConversationMap())===null||p===void 0?void 0:p.keys())||[])}_getLocalLastMessageTime(p){const{message:B}=this._core,v=B.messageDataHandler.getLocalMessageList(p),G=v[v.length-1];return G?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(B=this._core)===null||B===void 0||B.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},CC=new class{init(p){var B;this._core=p,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var p,B;const v=document?.visibilityState==="visible";(p=this._core)===null||p===void 0||p.store.set("activityMonitor",{isActive:v}),(B=this._core)===null||B===void 0||B.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:v})}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},_E=new class{init(p){var B;this._core=p,this._bindAppActivityEvent(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this),(B=this._core)===null||B===void 0||B.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var p,B,v,G,O;const{MINI_APP_NAMESPACE:z,IN_TT_MINI_GAME:X,IN_WX_MINI_GAME:rA}=((p=this._core)===null||p===void 0?void 0:p.utils)||{};X||rA?((B=z?.onShow)===null||B===void 0||B.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(v=z?.onHide)===null||v===void 0||v.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})})):((G=z?.onAppShow)===null||G===void 0||G.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!0}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!0})}),(O=z?.onAppHide)===null||O===void 0||O.call(z,()=>{var DA,GA;(DA=this._core)===null||DA===void 0||DA.store.set("activityMonitor",{isActive:!1}),(GA=this._core)===null||GA===void 0||GA.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:!1})}))}_reset(){var p;(p=this._core)===null||p===void 0||p.store.clear("activityMonitor")}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),this._reset()}},TE=new class{init(p){const{IN_MINI_APP:B,IN_WX_MINI_PLUGIN:v}=p.helper;v||(B?_E.init(p):CC.init(p))}};const hd="none",NE="online";var tl=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){navigator.onLine?this._onOnline():this._onOffline(),this._onOnlineCallback=this._onOnline.bind(this),this._onOfflineCallback=this._onOffline.bind(this),window.addEventListener("online",this._onOnlineCallback),window.addEventListener("offline",this._onOfflineCallback)})}_deactivateNetworkMonitoring(){this._onOnlineCallback!==null&&(window.removeEventListener("online",this._onOnlineCallback),this._onOnlineCallback=null),this._onOfflineCallback!==null&&(window.removeEventListener("offline",this._onOfflineCallback),this._onOfflineCallback=null)}_onNetworkStatusChange(p){var B,v;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(v=this._core)===null||v===void 0||v.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:NE})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:hd})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},CI=new class{init(p){this._core=p,this._activateNetworkMonitoring(),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return mA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:p}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),p.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(p){console.error(p)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:p}}=this._core;p.offNetworkStatusChange&&p.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(p){var B,v;const{isConnected:G,networkType:O}=p;(B=this._core)===null||B===void 0||B.store.set("netWorkMonitor",{isNetworkOnline:G,networkType:O}),(v=this._core)===null||v===void 0||v.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:G,networkType:O})}_reset(){var p;this._deactivateNetworkMonitoring(),(p=this._core)===null||p===void 0||p.store.clear("netWorkMonitor")}_dispose(){var p,B;(p=this._core)===null||p===void 0||p.notificationCenter.unSubscribeInnerEvent((B=this._core)===null||B===void 0?void 0:B.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Uu=new class{init(p){const{IN_MINI_APP:B}=p.utils;B?CI.init(p):tl.init(p)}},Fu=new class{constructor(){this.name="SystemStateMonitor"}install(p){TE.init(p),Uu.init(p)}};const hC=new Set(["tui_room_svr.*","callkit_records_svr.*","room_engine_srv.*","room_engine_http_srv.*","room_engine_mic.*","live_engine_srv.*","live_engine_http_srv.*","live_engine_pk.*","trtc_ai_service.*","call_engine_srv.*"]),wr="tui_room_svr.*";var cg=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=hC}install(p){this._core=p;const{notificationCenter:B,InnerEvent:v,helper:G}=p;B.subscribeInnerEvent(v.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),B.subscribeInnerEvent(v.LOGOUT,this._reset,this),B.subscribeInnerEvent(v.DESTROY,this._dispose,this),B.subscribeInnerEvent("im_open_push.msg_push",B.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),G.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),G.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(p){return mA(this,void 0,void 0,function*(){const B="transferBusinessCommand";try{const{serviceCommand:v=wr}=p||{};if(!this._isValidTransferredCommand(v))throw new this._core.helper.ChatError({code:2995,functionName:B});return{code:0,data:(yield function(O,z){return mA(this,void 0,void 0,function*(){const{helper:X,channel:rA}=z,{serviceCommand:DA=wr,data:GA}=O||{};let JA={};try{JA=typeof GA=="string"?JSON.parse(GA):GA}catch(Ze){console.warn(Ze)}const ne=X.generateProtocolData({servcmd:DA,data:JA}),he=`${ne.head.seq}${DA}`;return rA.sendPacket(ne,{requestId:he,shouldRejectOnError:!1})})}(p,this._core))||{}}}catch(v){throw console.warn(v),new this._core.helper.ChatError({code:v?.errorCode,message:v?.errorInfo,data:{},functionName:B})}})}_onCloudConfigUpdate(p={}){try{if(typeof p.rtc_cmd!="string")return;const B=JSON.parse(p.rtc_cmd);Array.isArray(B)&&(this._transferredCommands=new Set([...this._transferredCommands,...B]))}catch(B){console.log(B)}}_isValidTransferredCommand(p=""){const B=`${p?.split(".")[0]}.*`;return this._transferredCommands.has(B)}_onServerPushBusinessCommand(p){const{OuterEvent:B,notificationCenter:v}=this._core,{MsgContent:G}=p||{},{ROOM_CUSTOM_DATA_RECEIVED:O}=B;v.emitOuterEvent(O,{name:O,data:G})}_reset(){this._transferredCommands=hC}_dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;this._reset(),p.unSubscribeInnerEvent(B.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this._dispose,this),p.unSubscribeInnerEvent("im_open_push.msg_push",p.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const Rc=new class{init(p){this.core=p}};function Ou(p){return mA(this,void 0,void 0,function*(){var B;const{message:v,user:G,appStore:O,constants:{OuterConstant:z}}=Rc.core,X=O.conversationStore.getConversationMap();if(X.has(p)){const DA=(B=X.get(p))===null||B===void 0?void 0:B.userProfile;if(DA&&p.startsWith(z.CONV_C2C)){const{avatar:GA,nick:JA}=DA;Rc.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:GA,latestNick:JA,isSentByMe:!1})}}const{data:rA}=(yield G.userProfile.getMyProfile())||{};if(rA){const{avatar:DA,nick:GA}=rA;v.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:p,latestAvatar:DA,latestNick:GA,isSentByMe:!0})}})}function Nl(p){return mA(this,void 0,void 0,function*(){const B=p.map(v=>v.revoker);try{const v=yield function(G){return mA(this,void 0,void 0,function*(){var O,z;const X=yield(O=Rc.core.user.userProfile)===null||O===void 0?void 0:O.getUserProfile({userIDList:G});return X?.data?(z=X.data)===null||z===void 0?void 0:z.reduce((rA,{userID:DA,nick:GA,avatar:JA})=>(rA[DA]={nick:GA||"",avatar:JA||""},rA),{}):null})}(B);v&&p.forEach(G=>{const{revoker:O}=G;v[O]&&(G.revokerInfo.nick=v[O].nick||"",G.revokerInfo.avatar=v[O].avatar||"",G.revokerInfo.userID=O)})}catch(v){console.debug(v)}})}const Bd=1,Aa=2,hI=20,_n=2500,BC=1,il=300;function Qd(p){return mA(this,void 0,void 0,function*(){var B,v;const{appStore:G,utils:{isEmpty:O},common:{getCurrentUserID:z},notificationCenter:X,OuterEvent:rA,OuterConstant:{CONV_C2C:DA}}=Rc.core,{messageList:GA,conversationID:JA}=p,ne=G.conversationStore.getConversationMap();let he=(B=ne.get(JA))===null||B===void 0?void 0:B.peerReadTime;if(!he){const st=JA.replace(DA,""),at=yield function(Ft){return mA(this,void 0,void 0,function*(){const Ht={To_Account:Ft};return Rc.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:Ht})})}([st]);if(at){const{ReadTime:Ft}=at;he=Ft?.[0],ne.has(JA)&&(ne.get(JA).peerReadTime=he)}}if(ne.has(JA)){const st=(v=ne.get(JA))===null||v===void 0?void 0:v.lastMessage;O(st)||st.fromAccount===z()&&st.lastTime<=he&&!st.isPeerRead&&(st.isPeerRead=!0,G.conversationStore.updateConversation(JA,{lastMessage:st}))}const Ze=[];GA.forEach(st=>{st.time<=he&&!st.isPeerRead&&st.flow==="out"&&(st.isPeerRead=!0,Ze.push(st))}),Ze.length>0&&X.emitOuterEvent(rA.MESSAGE_READ_BY_PEER,{name:rA.MESSAGE_READ_BY_PEER,data:Ze})})}var BI=new class{init(p){this._core=p,p.helper.registerApi({apiName:"getMessageList",context:this}),p.helper.registerApi({apiName:"getMessageListHopping",context:this}),p.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(p){return mA(this,void 0,void 0,function*(){try{const{message:B,OuterConstant:{Direction:v,CONV_C2C:G,CONV_GROUP:O},InnerEvent:{HISTORY_MESSAGE_FETCHED:z},notificationCenter:X}=this._core,{conversationID:rA,nextReqMessageID:DA}=p,GA=hI;if(rA==="@TIM#SYSTEM")return{code:0,data:{messageList:[],isCompleted:!1,nextMessageSeq:""}};const JA=this._getAvailableLocalMessagesCount({conversationID:rA,nextReqMessageID:DA});if(this._needFetchHistoryMessageList({conversationID:rA,availableLocalMessagesCount:JA,targetCount:GA})){let ne=null;if(rA.startsWith(O)?ne=yield B.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:Number(DA),count:GA,direction:v.FORWARD,shouldMarkCompleted:!0}):rA.startsWith(G)&&(ne=yield B.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,messageID:DA,count:GA,direction:v.FORWARD,shouldMarkCompleted:!0})),ne){const{nextReqMessageIDFromServer:he,hasNoMoreHistoryMessage:Ze,messageList:st}=ne,at=B.messageDataHandler.prependLocalMessageList({messageList:st,conversationID:rA});(function(Xi){const{appStore:di,message:xo,OuterConstant:ts}=Rc.core,mi=di.conversationStore.getConversation(Xi),zi=xo.messageDataHandler.getLocalMessageList(Xi);if(!mi||zi.length===0||Xi===ts.CONV_SYSTEM)return;const Ws=[];for(let Tt=0;TtFA.isRevoked).length;Ne=Ws.length-mi.unreadCount-Tt}else Ne=Ws.length-mi.unreadCount;for(let Tt=0;TtXi.isRevoked);yield Nl(Ht),X.emitInnerEvent(z,at);const Pi={nextReqMessageID:Ze?"":String(he),messageList:Ft,isCompleted:Ze},co=Ft.map(Xi=>Xi.sequence);return{code:0,data:Pi,successLog:{message:`conversationID: ${rA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${JA} sequenceList: ${JSON.stringify(co)}`}}}return{code:0,data:{messageList:[],isCompleted:!1,nextReqMessageID:""}}}return{code:0,data:yield this._getMessageListFromMemory({conversationID:rA,nextReqMessageID:DA,count:GA}),successLog:{message:`conversationID: ${rA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${JA}}`}}}catch(B){const{code:v,message:G}=B||{};throw new this._core.helper.ChatError({code:v,message:G,moreMessage:`options: ${this._core.utils.safeStringify(p)}`})}})}getMessageListHopping(p){return mA(this,void 0,void 0,function*(){var B,v;const{OuterConstant:{Direction:G,CONV_C2C:O,CONV_GROUP:z},utils:{safeStringify:X}}=this._core,{conversationID:rA,sequence:DA,time:GA,direction:JA=G.FORWARD}=p,{utils:{isEmpty:ne},message:he,notificationCenter:Ze,InnerEvent:{HISTORY_MESSAGE_FETCHED:st}}=this._core;if(![G.BACKWARD,G.FORWARD].includes(JA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${X(p)}`});let{count:at=hI}=p;at=at>hI?hI:at;let Ft=null;if(rA.startsWith(z)){if(Ft=yield he.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:DA,count:at,direction:JA}),Ft){const{nextReqMessageIDFromServer:Ht,hasNoMoreHistoryMessage:Pi,messageList:co,invisibleSequenceList:Xi}=Ft;if(this._core.message.messageDataHandler.storeSparseMessageList(co),Ze.emitInnerEvent(st,co),JA===G.FORWARD){const di=Pi&&Ht<1;return{code:0,data:{messageList:co,isCompleted:di,nextMessageSeq:di?"":Ht}}}if(JA===G.BACKWARD){if(ne(co)&&ne(Xi))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const di=((B=co?.[co.length-1])===null||B===void 0?void 0:B.sequence)||0,xo=((v=Xi?.[Xi.length-1])===null||v===void 0?void 0:v.sequence)||0;return{code:0,data:{messageList:co.filter(ts=>ts.sequence>=DA),isCompleted:!Pi,nextMessageSeq:Pi?Math.max(di,xo)+1:""}}}return{code:0,data:Ft}}}else if(rA.startsWith(O)&&(Ft=yield he.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,count:at+1,time:GA,direction:JA}),Ft)){const{messageList:Ht,lastMessageTime:Pi,hasNoMoreHistoryMessage:co}=Ft;return Ze.emitInnerEvent(st,Ht),co||(JA===G.FORWARD?Ht.shift():Ht.pop()),he.messageDataHandler.storeSparseMessageList(Ht),yield Qd({messageList:Ht,conversationID:rA}),{code:0,data:{messageList:Ht,isCompleted:co,nextMessageTime:co?"":Pi}}}})}clearHistoryMessage(p){return mA(this,void 0,void 0,function*(){var B;const{appStore:v,common:{ChatError:G,getCurrentUserID:O},OuterConstant:{CONV_C2C:z,CONV_GROUP:X},apiMap:rA,message:DA}=this._core,GA=v.conversationStore.getConversation(p);if(!GA)throw new G({code:_n});const JA={fromAccount:O()},{type:ne}=GA;ne===z?(JA.type=Bd,JA.toAccount=p.replace(z,"")):ne===X&&(JA.type=Aa,JA.toGroupID=p.replace(X,""));try{return yield(B=rA?.setMessageRead)===null||B===void 0?void 0:B.call(rA,{conversationID:p}),(yield function(Ze){return mA(this,void 0,void 0,function*(){const{fromAccount:st,type:at,toAccount:Ft,toGroupID:Ht}=Ze,Pi={From_Account:st,Type:at,To_Account:Ft,ToGroupid:Ht};return Rc.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:Pi})})}(JA))&&(DA.messageDataHandler.deleteConversationMessageList(p),DA.messageHistory.completedHistoryConversations.delete(p),DA.messageHistory.clearHistoryMessageListFetchAnchors(p),this._updateConversationLastMessage(p)),{code:0,data:{conversationID:p},successLog:{message:`convID:${p}`}}}catch(he){const{errorCode:Ze}=he;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:Ze,moreMessage:`convID:${p}`})}})}_updateConversationLastMessage(p){const{appStore:B}=this._core;B.conversationStore.updateConversation(p,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:p,nextReqMessageID:B}){const{OuterConstant:{CONV_C2C:v,CONV_GROUP:G}}=this._core,O=this._core.message.messageDataHandler.getLocalMessageList(p),{length:z}=O;if(!B)return z;let X=-1;return p?.startsWith(v)?X=O.findIndex(rA=>rA.ID===B):p?.startsWith(G)&&(X=O.findIndex(rA=>B.includes("-")?rA.ID===B:String(rA.sequence)===B)),X===-1?0:X}_needFetchHistoryMessageList({conversationID:p,availableLocalMessagesCount:B,targetCount:v}){const{message:G}=this._core;return BB.startsWith(O)?he.ID===v:String(he.sequence)===v),JA=ne>G?ne-G:0,DA=ne):JA=rA>G?rA-G:0,GA.messageList=X.slice(JA,ne),GA.isCompleted=DA<=G&&z.messageHistory.completedHistoryConversations.has(B),GA.isCompleted?GA.nextReqMessageID="":GA.nextReqMessageID=this._generateNextReqMessageID({conversationID:B,targetIndex:JA}),B.startsWith(O)&&(yield Ou(B),yield Qd({messageList:GA.messageList,conversationID:B})),GA})}_generateNextReqMessageID({conversationID:p,targetIndex:B}){const v=this._core.message.messageDataHandler.getLocalMessageList(p);return p.startsWith("C2C")?v[B].ID:String(v[B].sequence)}_generateLastMessage(){return{lastTime:0,lastSequence:0,fromAccount:"",messageForShow:"",payload:null,type:"",isRevoked:!1,cloudCustomData:"",onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:!1,revoker:null}}},Oa=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(p){this._core=p;const{common:{workflowManager:B},constants:{WORKFLOW_NAME:v,WORKFLOW_STEP:G,InnerEvent:O}}=p;B.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),B.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,G.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),p.notificationCenter.subscribeInnerEvent(O.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(p){const{conversationList:B}=p?.result||{},{OuterConstant:v,utils:{isArray:G}}=this._core;if(G(B)){const O=B.filter(z=>z.type===v.CONV_GROUP&&z.groupProfile.type!==v.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(O)}}_recoverGroupHistoryMessage(p){return mA(this,void 0,void 0,function*(){const{OuterConstant:B}=this._core,v=[],G=[];return yield Promise.all(p?.map(O=>mA(this,void 0,void 0,function*(){const{groupProfile:{groupID:z}={},lastMessage:{lastSequence:X}={}}=O,rA=`${B.CONV_GROUP}${z}`;let DA=this._getLocalLastMessageSequence(rA);this._shouldRecoverHistory({localLastMessageSequence:DA,serverLastMessageSequence:X})&&(yield this._recoverGroupHistoryForConversation({conversationID:rA,localLastMessageSequence:DA,serverLastMessageSequence:X,groupTipList:G})),v.push(rA.replace(B.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:v,groupTipList:G}})}_recoverGroupHistoryForConversation(p){return mA(this,arguments,void 0,function*({conversationID:B,localLastMessageSequence:v,serverLastMessageSequence:G,groupTipList:O}){try{const{utils:{isArray:z,isObject:X,isEmpty:rA},OuterEvent:DA,OuterConstant:GA,notificationCenter:JA,message:ne,appStore:he,common:{getMessagePreviewText:Ze,buildLastMessage:st}}=this._core,at=G-v,Ft=Math.min(20,at),Ht={},Pi=yield ne.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:B,sequence:v+Ft,direction:GA.Direction.FORWARD,count:Ft}),{nextReqMessageIDFromServer:co,hasNoMoreHistoryMessage:Xi,messageList:di,serverGroupTipList:xo}=Pi;z(xo)&&O.push(...xo);const ts=Xi&&co<0,mi=[];if(z(di)&&(di.forEach(zi=>{ne.messageReceiver.groupMessageReceiver.updateMessageProfile(zi),zi.from===GA.CONV_SYSTEM&&(zi.isSystemMessage=!1),ne.messageDataHandler.storeConversationMessage(zi)&&!rA(zi.payload)&&(mi.push(zi),zi._isExcludedFromLastMessage||(Ht.lastMessage=st(zi)))}),mi.length>0&&JA.emitOuterEvent(DA.MESSAGE_RECEIVED,{name:DA.MESSAGE_RECEIVED,data:mi})),!ts&&di.length>0){const zi=di[di.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:B,localLastMessageSequence:zi,serverLastMessageSequence:G,groupTipList:O})}X(Ht.lastMessage)&&(Ht.lastMessage.messageForShow=Ze(Ht.lastMessage.type,Ht.lastMessage.payload),he.conversationStore.updateConversation(B,Ht))}catch(z){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${B}`,{error:z})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:p}=this._core,B=p.messageDataHandler.getContinuousMessagesByConversation();for(const[v,G]of B){const O=Array.from(G.values());if(O?.length>0){const z=O[O.length-1];v.startsWith("C2C")?this._lastMessageTimeMapOnDisconnect.set(v,z.time):v.startsWith("GROUP")&&this._lastMessageSequenceMapOnDisconnect.set(v,z.sequence)}}}_getLocalLastMessageSequence(p){const{message:B}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(p))return this._lastMessageSequenceMapOnDisconnect.get(p);const v=B.messageDataHandler.getLocalMessageList(p),G=v[v.length-1];return G?.sequence}_shouldRecoverHistory(p){const{localLastMessageSequence:B,serverLastMessageSequence:v}=p;if(typeof B!="number"||typeof v!="number")return!1;const G=v-B;return v!==0&&B>0&&G>=BC&&G{z.type===v.CONV_C2C&&O.push(z)}),this._recoverC2CHistoryMessage(O)}}_recoverC2CHistoryMessage(p){return mA(this,void 0,void 0,function*(){yield Promise.all(p?.map(B=>mA(this,void 0,void 0,function*(){const{conversationID:v,lastMessage:{lastTime:G}={}}=B,O=this._getLocalLastMessageTime(v);this._shouldRecoverC2CHistory({localLastMessageTime:O,serverLastMessageTime:G})&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:O,serverLastMessageTime:G}))})))})}_shouldRecoverC2CHistory(p){const{localLastMessageTime:B,serverLastMessageTime:v}=p,G=v-B;return B>0&&G>=1&&G<=600}_recoverHistoryForC2CConversation(p){return mA(this,void 0,void 0,function*(){var B;const{conversationID:v,localLastMessageTime:G,serverLastMessageTime:O}=p,{utils:{isArray:z,isObject:X,isEmpty:rA,safeStringify:DA},OuterEvent:GA,OuterConstant:JA,notificationCenter:ne,message:he,appStore:Ze,common:{getMessagePreviewText:st,buildLastMessage:at}}=this._core;try{const Ft={},Ht=yield he.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,direction:JA.Direction.BACKWARD,time:G,count:20});if(rA(Ht))return;const{hasNoMoreHistoryMessage:Pi,messageList:co}=Ht,Xi=[];z(co)&&(co.forEach(xo=>{he.messageDataHandler.storeConversationMessage(xo)&&!rA(xo.payload)&&(Xi.push(xo),xo._isExcludedFromLastMessage||(Ft.lastMessage=at(xo)))}),Xi.length>0&&ne.emitOuterEvent(GA.MESSAGE_RECEIVED,{name:GA.MESSAGE_RECEIVED,data:Xi}));const di=(B=co[co.length-1])===null||B===void 0?void 0:B.time;!Pi&&di>O&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:di,serverLastMessageTime:O})),X(Ft.lastMessage)&&(Ft.lastMessage.messageForShow=st(Ft.lastMessage.type,Ft.lastMessage.payload),Ze.conversationStore.updateConversation(v,Ft))}catch(Ft){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${v} error: ${DA(Ft)}`)}})}_getLocalLastMessageTime(p){const{message:B}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(p))return this._lastMessageTimeMapOnDisconnect.get(p);const v=B.messageDataHandler.getLocalMessageList(p),G=v[v.length-1];return G?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},QC=new class{constructor(){this.name="HistoryMessage"}install(p){this._core=p,Rc.init(p),BI.init(p),Oa.init(p),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.LOGOUT,this._reset,this),p.notificationCenter.subscribeInnerEvent(p.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:p,InnerEvent:B}=this._core;p.unSubscribeInnerEvent(B.LOGOUT,this._reset,this),p.unSubscribeInnerEvent(B.DESTROY,this.dispose,this),Oa.dispose()}_reset(){Oa.reset()}},Pa=new class{init(p){this.core=p}},hr=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(p){const{helper:{registerExperimentalAPI:B}}=p;this._core=p,B("reportModalView",this),B("reportTUIFeatureUsage",this),B("reportRoomEngineEvent",this)}reportModalView(p){const{ssoLog:B,utils:{safeStringify:v,isString:G}}=this._core;try{if(!G(p))throw new Error("reportModalView data is not a string");B.createSSOLogData({method:"reportModalView",message:p,eventType:30}).end(!0)}catch(O){B.debug(`reportModalView Report failed: ${v(O)}`)}}reportTUIFeatureUsage(p){const{ssoLog:B,utils:{safeStringify:v,isEmpty:G}}=this._core,{atomicStoreID:O}=p;try{G(O)||this._reportedAtomicStoreIDs.has(O)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${p.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:O}),this._reportedAtomicStoreIDs.add(O))}catch(z){B.debug(`reportTUIFeatureUsage Report failed: ${v(z)}`)}}reportRoomEngineEvent(p){const{utils:{safeStringify:B},ssoLog:v}=this._core;try{v.debug(`reportRoomEngineEvent Report: ${B(p)}`);const{eventId:G,eventCode:O,eventResult:z,eventMessage:X,moreMessage:rA,extensionMessage:DA}=p;v.createSSOLogData({method:DA,code:G,message:X,eventType:30,costTime:O,uiPlatform:z,moreMessage:rA}).end(!0)}catch(G){v.debug(`reportRoomEngineEvent Report failed: ${B(G)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},pd=new class{constructor(){this.name="DataReport"}install(p){this._core=p;const{notificationCenter:B,InnerEvent:{LOGOUT:v,DESTROY:G}}=p;Pa.init(p),hr.init(p),B.subscribeInnerEvent(v,this._reset,this),B.subscribeInnerEvent(G,this._dispose,this)}_reset(){hr.reset()}_dispose(){const{notificationCenter:p,InnerEvent:{LOGOUT:B,DESTROY:v}}=this._core;p.unSubscribeInnerEvent(B,this._reset,this),p.unSubscribeInnerEvent(v,this._dispose,this),hr.dispose()}};let Pu=da.STANDARD,Br=[];Pu=da.BASIC,Br=[dC,ch,ao,Fu,cg,QC,pd];function wc(p,B){const{operationType:v,memberInfoList:G,operatorInfo:O}=p||{};let z={};if(Rs(G)?Rs(O)||(z=O):v!==na.JOINED&&v!==na.KICKED&&v!==na.ADMIN_SET&&v!==na.ADMIN_CANCELED||(z=Object.assign({},G[0])),!Rs(z)){const{nick:X="",avatar:rA=""}=z;B.nick=X,B.avatar=rA}}const ol=p=>({lastTime:p?.time||p?.lastTime||0,lastSequence:p?.sequence||p?.lastSequence||0,fromAccount:p?.from||p?.fromAccount||"",messageForShow:WI(p?.type,p?.payload),payload:p?.payload||null,type:p?.type||"",isRevoked:p?.isRevoked||!1,cloudCustomData:p?.cloudCustomData||"",onlineOnlyFlag:p?._onlineOnlyFlag||!1,nick:p?.nick||"",nameCard:p?.nameCard||"",version:p?.version||0,isPeerRead:p?.isPeerRead||!1,revoker:p?.revoker||null});var Lg=Object.freeze({__proto__:null,ChatError:rs,WorkflowManager:tn,buildAndSendPacket:Zg,buildLastMessage:ol,get builtInPlugins(){return Br},checkBusinessCapabilityBits:Wc,deepMerge:Fa,getCurrentUserID:jn,getErrorMessage:_l,getMessagePreviewText:WI,isC2CConv:p=>c(p)&&p.slice(0,3)===_g.CONV_C2C,isCommunity:Ca,isGroupConv:p=>c(p)&&p.slice(0,5)===_g.CONV_GROUP,isInternational:ku,isTopic:$r,isUnlimitedAVChatRoom:function(){var p;return!!(!((p=Se.store.get("instance"))===null||p===void 0)&&p.unlimitedAVChatRoom)},liteChatInstanceMap:ws,registerInterceptor:vr,registerValidateConfig:Mc,requireAuth:gs,get sdkEdition(){return Pu},setGroupTipsUserInfo:wc,t:EC,updateGroupAtInfo:(p,B)=>{const{CONV_AT_ME:v,CONV_AT_ALL:G,CONV_AT_ALL_AT_ME:O}=Bs;if(function(rA,DA){const{CONV_AT_ME:GA,CONV_AT_ALL:JA,CONV_AT_ALL_AT_ME:ne}=Bs,{groupID:he,sequence:Ze}=rA;let st=!1;return Ca({groupID:he})&&DA.forEach(at=>{at.messageSequence===Ze&&(at.atTypeArray.includes(GA)&&rA.groupAtType.includes(JA)&&(at.atTypeArray=[ne]),at.atTypeArray.includes(JA)&&rA.groupAtType.includes(GA)&&(at.atTypeArray=[ne],at.__random=rA.__random,at.__sequence=rA.__sequence),st=!0)}),st}(p,B))return;let z=[...p.groupAtType];z.includes(v)&&z.includes(G)&&(z=[O]);const X={from:p.from,groupID:p.groupID,topicID:p.topicID,messageSequence:p.sequence,atTypeArray:z,__random:p.__random,__sequence:p.__sequence};B.push(X)},validateAndExecute:Tl,validateParameters:ud});class Po{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Po._instance||(Po._instance=new Po),Po._instance}static setInstance(B){Po._instance=B}installBuiltInPlugin(B){B&&this._installPlugin(B,this._builtInPlugins)}installExternalPlugin(B){B&&this._installPlugin(B,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(B,v){let G=[];G=C(B)?B:[B];const O=G.findIndex(X=>X?.name==="AVChatRoom"),z=O>-1?G.splice(O,1):[];G.forEach(X=>{this._isPluginInstalled(X.name)||(X&&De(X.install)?(v.add(X.name),De(X.getInstalledSubPlugins)?(z?.forEach(rA=>v.add(rA?.name)),X.install(js.getInstance().exposeApiForPlugin(),z)):X.install(js.getInstance().exposeApiForPlugin()),De(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):De(X)?(v.add(X.name),X(js.getInstance().exposeApiForPlugin()),De(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(B){return this._builtInPlugins.has(B)||this._externalPlugins.has(B)}_isLoggedIn(){var B;return((B=Se.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}}var $g=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(p){return this._conversationMap.get(p)}updateConversation(p,B,v){const{emit:G=!0,needSort:O=!1}=v||{},z=this._conversationMap.get(p);z&&!Rs(B)&&(Object.keys(B).forEach(X=>{z[X]=B[X]}),G&&Se.notificationCenter.emitInnerEvent(Ei.CONVERSATION_UPDATED,{needSort:O}))}deleteConversation(p){this._conversationMap.has(p)&&(this._conversationMap.delete(p),Se.notificationCenter.emitInnerEvent(Ei.CONVERSATION_UPDATED))}},Za=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(p){return this._groupMap.get(p)}updateGroup(p,B){const v=this._groupMap.get(p);v&&!Rs(B)&&Object.keys(B).forEach(G=>{v[G]=B[G]})}},Gl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(p,B,v){var G;const{operation:O,updateUnreadCount:z=!0}=v,X=So(v,["operation","updateUnreadCount"]),rA=[];for(const DA of B){const GA=(G=this._messagesByConversation.get(p))===null||G===void 0?void 0:G.get(DA);if(!GA)return!1;Object.keys(X).forEach(JA=>{GA[JA]=X[JA]}),rA.push(GA)}return this._emitMessageStoreOperationEvent(O,{conversationID:p,messageList:rA,updateUnreadCount:z}),rA}getMessagesByConversation(p){var B;return[...((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(p,B){const{conversationID:v}=B;$r(v)?Se.notificationCenter.emitInnerEvent(ag[p],B):Se.notificationCenter.emitInnerEvent(p,B)}},ea=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(p){return this.userProfileMap.get(p)}getFriend(p){return this.friendMap.get(p)}},Ih=Object.freeze({__proto__:null,conversationStore:$g,groupStore:Za,messageStore:Gl,userStore:ea});class js{static getInstance(){return js._instance||(js._instance=new js),js._instance}static setInstance(B){js._instance=B}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:Se.notificationCenter.subscribeOuterEvent.bind(Se.notificationCenter),off:Se.notificationCenter.unSubscribeOuterEvent.bind(Se.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:Po.getInstance().installExternalPlugin.bind(Po.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(B){Se.ssoLog.debug("registerPlugin",B)}statKeyFeatureUsage(B){Se.ssoLog.debug("statTUIKeyFeatures",B)}setLogLevel(B){Se.ssoLog.debug("setLogLevel",B),Se.ssoLog.setLogLevel(B)}setApplicationID(B){Se.store.set("instance",{applicationID:B})}getApiMap(){return this._apiMap}setApiMap(B){this._apiMap=B}registerApi(B){const{common:{timeManager:v},utils:{safeStringify:G}}=Se,{apiName:O,context:z,methodName:X=O,matcher:rA}=B;this._apiHandlersMap[O]||(this._apiHandlersMap[O]=[]),this._apiHandlersMap[O].push({context:z,methodName:X,matcher:rA}),this._apiMap[O]&&this._apiHandlersMap[O].length!==1||(this._apiMap[O]=(...DA)=>{const GA=v.getServerTimeMs();let JA=0;O==="login"&&(JA=4),cr.includes(O)&&Se.ssoLog.debug(O,`${O} start params: ${G(DA)}`),Tl(X,DA);const ne=this._apiHandlersMap[O];for(const he of ne)if(!he.matcher||he.matcher(DA))try{const Ze=he.context[he.methodName].bind(he.context)(...DA);return this._isPromiseLike(Ze)?this._handleAsyncResult(Ze,O,JA,GA):(this._reportApiSuccessLog({result:Ze,apiName:O,eventType:JA,startTime:GA}),Ze)}catch(Ze){throw Se.ssoLog.error(O,`${O} fail ${Ze?.message||Ze?.errorMessage})`,{error:Ze,costTime:v.getServerTimeMs()-GA,eventType:JA,method:O}),Ze}})}registerExperimentalAPI(B,v,G){const O=G||B;this._experimentalApiMap[B]=v[O].bind(v)}destroy(){return mA(this,void 0,void 0,function*(){var B,v;try{!((B=Se.store.get("login"))===null||B===void 0)&&B.isLogin&&(yield this._apiMap.logout()),Se.notificationCenter.emitInnerEvent(Ei.DESTROY)}catch(G){console.debug("destroy error: ",G)}finally{Se.notificationCenter.emitOuterEvent(Dn.SDK_DESTROY,{SDKAppID:(v=Se.store.get("instance"))===null||v===void 0?void 0:v.sdkAppId}),ws.clear(),Po.getInstance().clear(),tn.getInstance().destroy(),Se.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Ei,InnerEventSubType:Se.notificationCenter.InnerEventSubType,OuterEvent:Dn,OuterConstant:Bs,SignalingEvent:ro,helper:Object.assign(Object.assign(Object.assign({},Se.utils),Se.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:vr,registerValidateConfig:Mc,checkBusinessCapabilityBits:Wc,registerWorkflowStep:tn.getInstance().registerWorkflowStep.bind(tn.getInstance()),ChatError:rs}),apiMap:this._apiMap},Se),{constants:Object.assign(Object.assign({},KI),Se.constants),common:Object.assign(Object.assign(Object.assign({},Lg),Se.common),{workflowManager:tn.getInstance()}),utils:Se.utils,appStore:Ih})}callExperimentalAPI(B,v){return Se.ssoLog.debug(`callExperimentalAPI.${B} start params: ${Se.utils.safeStringify(v)}`),this._experimentalApiMap[B]?this._experimentalApiMap[B](v):(Se.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${B} not found, params: ${Se.utils.safeStringify(v)}`),Promise.reject(new rs({code:Uo.INVALID_OPERATION})))}_isPromiseLike(B){return B!==null&&typeof B=="object"&&typeof B.then=="function"}_handleAsyncResult(B,v,G,O){return B.then(z=>(this._reportApiSuccessLog({result:z,apiName:v,eventType:G,startTime:O}),z)).catch(z=>{throw Se.ssoLog.error(v,`${v} fail ${z?.message||z?.errorMessage})`,{error:z,costTime:Se.common.timeManager.getServerTimeMs()-O,eventType:G,method:v,startTime:O}),z})}_reportApiSuccessLog(B){let{result:v,apiName:G,startTime:O,eventType:z}=B;const{timeManager:X}=Se.common,{successLog:{message:rA,moreMessage:DA}={message:"",moreMessage:""}}=v||{},GA=X.getServerTimeMs();G==="login"&&(O+=X.getTimeOffsetWithServer()),cr.includes(G)&&Se.ssoLog.info(G,`${G} success ${rA} ${DA}`,{costTime:GA-O,eventType:z,message:rA,moreMessage:DA,startTime:O}),v?.successLog&&delete v.successLog}}class $I{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:B,store:v}=Se;v.set("login",{isReady:!1}),js.getInstance().registerApi({apiName:"login",context:this}),js.getInstance().registerApi({apiName:"logout",context:this}),js.getInstance().registerApi({apiName:"getLoginUser",context:this}),js.getInstance().registerApi({apiName:"isReady",context:this}),js.getInstance().registerApi({apiName:"getServerTime",context:this}),js.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),B.subscribeInnerEvent(Ei.RECONNECTED,this._reLogin,this),Se.notificationCenter.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}login(B){return mA(this,void 0,void 0,function*(){var v;const{sdkEdition:G}=Se.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new rs({functionName:"login",code:Uo.REPEAT_LOGIN});const O=yield this._performLogin(B);this._validateAfterLogin(O),this._handleLoginSuccess(O),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const z=(v=Se.channel.getSocketAdapter())===null||v===void 0?void 0:v.getId(),{appId:X,href:rA}=Se.store.get("instance")||{},{instanceID:DA,customStatus:GA}=O||{};return{code:0,data:O,successLog:{message:G,moreMessage:`socketID:${z} instanceID:${DA} customStatus:${GA} href: ${rA} appId: ${X}`}}}catch(O){const{errorCode:z}=O;z!==Uo.REPEAT_LOGIN&&(this._latestLoginAt=0);const X=new rs({functionName:"login",code:z});throw console.error(X),X}})}_reLogin(){return mA(this,void 0,void 0,function*(){var B;try{if(!this._isLoginIn())return;const v=yield bu(this._customLoginInfo);if(v){const{instanceID:G,customStatus:O}=v;Se.store.set("login",{statusInstanceId:G}),tn.getInstance().executeWorkflow(gr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:O,statusType:Tu.USER_STATUS_ONLINE});const z=(B=Se.channel.getSocketAdapter())===null||B===void 0?void 0:B.getId();Se.ssoLog.info("reLogin",`socketId:${z} instanceId:${G}`)}}catch(v){console.warn(v)}})}logout(){return mA(this,arguments,void 0,function*(B=za.USER_INITIATED){const{ssoLog:v}=Se;v.debug("logout",`logout start logoutReason: ${B}`);try{yield this._performLogout(B),v.info("logout","logout success"),Se.ssoLog.uploadSSOLogData()}catch(G){const{errorCode:O}=G;throw new rs({functionName:"logout",code:O})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?jn():""}isReady(){var B;return(B=Se.store.get("login"))===null||B===void 0?void 0:B.isReady}setCustomLoginInfo(B=""){this._customLoginInfo=B}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),tn.getInstance().reset(),Se.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:B}=Se.common;return B.getServerTimeMs()}_updateAndEmitSDKReady(){Se.store.set("login",{isReady:!0}),setTimeout(()=>{Se.notificationCenter.emitOuterEvent(Dn.SDK_READY,{name:Dn.SDK_READY})},1)}_updateAndEmitSDKNotReady(){Se.store.set("login",{isReady:!1}),Se.notificationCenter.emitOuterEvent(Dn.SDK_NOT_READY,{name:Dn.SDK_NOT_READY})}_validateAfterLogin(B){const v="login";if(!B)throw new rs({functionName:v,message:"login response is empty"});const{tinyID:G,a2Key:O}=B||{};if(!G)throw new rs({functionName:v,code:Uo.NO_TINYID});if(!O)throw new rs({functionName:v,code:Uo.NO_A2KEY})}_createRepeatLoginResponse(){var B;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:_l({code:"RepeatLogin",replacement1:(B=Se.store.get("login"))===null||B===void 0?void 0:B.userId}),repeatLogin:!0}}}_performLogin(B){return mA(this,void 0,void 0,function*(){const{userID:v,userSig:G}=B;return Se.store.set("login",{userId:v,userSig:G}),this._latestLoginAt=Date.now(),bu(this._customLoginInfo)})}_ensureAsyncComplete(){return mA(this,void 0,void 0,function*(){yield new Promise(B=>{setTimeout(()=>B(null),1)})})}_handleLoginSuccess(B){const{timeManager:v}=Se.common,{helloInterval:G,timeStamp:O,customStatus:z,purchaseBits:X}=B,rA=1e3*O;v.calculateTimeOffsetWithServer(this._latestLoginAt,rA),this._helloInterval=G||120,this._updateLoginStore(B),Se.user.userStatus.setCustomStatus(z),tn.getInstance().executeWorkflow(gr.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:X}),Se.common.taskScheduler.addTask({id:Nu,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(B){return function(v){return mA(this,void 0,void 0,function*(){const{logoutReason:G}=v,O="im_open_status.wslogout",z=Se.common.generateProtocolData({servcmd:O,data:{wslogout_type:G,isWebUniapp:0}}),X=`${z.head.seq}${O}`;return yield Se.channel.sendPacket(z,{requestId:X})})}({logoutReason:B})}_updateLoginStore(B){const{a2Key:v,tinyID:G,instanceID:O,authKey:z}=B;Se.store.set("login",{a2Key:v,tinyID:G,statusInstanceId:O,authKey:z,isLoggedIn:!0})}_sendOnlinePresenceRequest(){return mA(this,void 0,void 0,function*(){this._latestSendOnlinePresenceRequestTime=Date.now();try{yield function(){const B="im_open_status.wshello",v=Se.common.generateProtocolData({servcmd:B,data:{isWebUniapp:0}}),G=`${v.head.seq}${B}`;return Se.channel.sendPacket(v,{requestId:G})}()}catch(B){Se.ssoLog.warn("_sendOnlinePresenceRequest",` error:${B.message}`)}})}_isLoginIn(){var B;return((B=Se.store.get("login"))===null||B===void 0?void 0:B.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){Se.common.taskScheduler.removeTask(Nu),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",Se.store.clear("login"),Se.store.set("login",{isReady:!1}),Se.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:B}=Se;B.unSubscribeInnerEvent(Ei.RECONNECTED,this._reLogin,this),B.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this)}}const Fs={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},_c={logout:!0};class Ac{constructor(){this.loginAction=new $I,this.kickedOutHandler=new Sc,this.loginAction.init(),this.kickedOutHandler.init(),Mc({auth:_c,params:Fs})}}var Qr,Vr,Xa;(function(p){p.CONV_C2C="C2C",p.CONV_GROUP="GROUP",p.CONV_TOPIC="TOPIC",p.CONV_SYSTEM="@TIM#SYSTEM"})(Qr||(Qr={})),function(p){p.MSG_PRIORITY_HIGH="High",p.MSG_PRIORITY_NORMAL="Normal",p.MSG_PRIORITY_LOW="Low",p.MSG_PRIORITY_LOWEST="Lowest"}(Vr||(Vr={})),function(p){p.MSG_TEXT="TIMTextElem",p.MSG_CUSTOM="TIMCustomElem",p.MSG_LOCATION="TIMLocationElem",p.MSG_FACE="TIMFaceElem",p.MSG_IMAGE="TIMImageElem",p.MSG_AUDIO="TIMSoundElem",p.MSG_FILE="TIMFileElem",p.MSG_VIDEO="TIMVideoFileElem",p.MSG_GRP_TIP="TIMGroupTipElem",p.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",p.MSG_MERGER="TIMRelayElem"}(Xa||(Xa={}));const GE={1:Vr.MSG_PRIORITY_HIGH,2:Vr.MSG_PRIORITY_NORMAL,3:Vr.MSG_PRIORITY_LOW,4:Vr.MSG_PRIORITY_LOWEST},pC=0,uh=1;var go;(function(p){p.IN="in",p.OUT="out"})(go||(go={}));const Tc=2,bl={};function mC(p){if(!p)return 0;if(bl[p]===void 0){const B=new Date,v=`3${B.getHours()}`.slice(-2),G=`0${B.getMinutes()}`.slice(-2),O=`0${B.getSeconds()}`.slice(-2);bl[p]=parseInt([v,G,O,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${bl[p]}`)}else bl[p]+=1;return bl[p]}class fC{constructor(B){this.ID="",this.random=0,this.sequence=0,this.nameCard="",this.isRead=!1,this.isPeerRead=!1,this.isDeleted=!1,this.isResend=!1,this.hasRiskContent=!1,this._onlineOnlyFlag=!1,this.atUserList=[],this._groupAtInfoList=[],this.isBroadcastMessage=!1,this.priority=Vr.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:v=Se.common.timeManager.getServerTimeSeconds()||0,senderTinyID:G,currentUser:O,needReadReceipt:z,isSupportExtension:X,customModerationConfigurationId:rA,to:DA,from:GA,nick:JA="",avatar:ne="",time:he,messageControlInfo:Ze,tinyID:st,cloudCustomData:at="",messageLifeTime:Ft,messageVersion:Ht=0,conversationType:Pi,sequence:co,checkResult:Xi=0,isPlaceMessage:di=0,messageFlagBits:xo,receiverList:ts,isSystemMessage:mi=!1,status:zi=wg.SUCCESS,revokeReason:Ws="",conversationSubType:Ne,clientSequence:Tt,protocol:FA="JSON",revokerInfo:Ai={userID:"",nick:"",avatar:""},readReceiptInfo:En={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:ii,groupProfile:us,atUserList:wi,flow:Bo,isRead:Bt=!1,priority:mt=Vr.MSG_PRIORITY_NORMAL,onlineOnlyFlag:ug=!1,nameCard:Ls="",quoteInfo:Zi}=B;var Hr;this.clientTime=v,this.senderTinyID=G||st,this.needReadReceipt=z===!0||z===1,this.isSupportExtension=X===!0||X===1,this._cmConfigID=rA,this.to=DA,this.nick=JA,this.avatar=ne,this.protocol=FA,this.random=ii===void 0?(Hr=Hr||99999999,Math.round(Math.random()*Hr)):ii,this.time=he||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!Ze?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!Ze?.excludedFromUnreadCount,this.isModified=!!Ht,this.cloudCustomData=at,this.messageLifeTime=Ft,this.from=GA||null,this.sequence=co||0,this.conversationType=Pi||Qr.CONV_C2C,this.hasRiskContent=Xi>1,this.version=Ht,this.isPlaceMessage=di,this.isRevoked=di===2||xo===8,this.isSystemMessage=mi,this.readReceiptInfo=En,this.revokeReason=Ws,this.revokerInfo=Ai,this._receiverList=ts,this.conversationSubType=Ne,this.revoker=Ai?.revoker||"",this.clientSequence=Tt||co||0,this.status=zi,this.atUserList=wi||[],this.flow=Bo,this.isRead=Bt,this.priority=mt,this._onlineOnlyFlag=ug,this.nameCard=Ls,this.quoteInfo=Zi,this.reInitialize(O),this._initC2CReadReceiptInfo(B),this._extractGroupInfo(us)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(B){Array.isArray(B)?this._elements=B:this._elements=[B],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(B=>B.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(B){this._relayFlag=B}validateBeforeSend(){var B,v,G;return this._relayFlag?{isValid:!0}:((B=this._elements)===null||B===void 0?void 0:B.length)>0?(G=(v=this._elements[0])===null||v===void 0?void 0:v.validateBeforeSend)===null||G===void 0?void 0:G.call(v):{isValid:!1}}_updatePayloadAndType(){this._elements[0]&&(this.payload=this._elements[0].content,this.type=this._elements[0].type)}_initC2CReadReceiptInfo(B){const{readReceiptSentByPeer:v,timestamp:G=0}=B;this.conversationType===Qr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=v===1,this.readReceiptInfo.timestamp=G)}_extractGroupInfo(B){if(!B)return;const{From_AccountNick:v,From_AccountHeadurl:G,MsgFrom_AccountExtraInfo:O,GroupType:z}=B,{NameCard:X}=O||{};typeof v=="string"&&(this.nick=v),typeof G=="string"&&(this.avatar=G),typeof X=="string"&&(this.nameCard=X),this.conversationSubType=z}reInitialize(B){B===this.from&&(this.isRead=!0),this._initSequence(B),this._concatConversationID(B),this.generateMessageID()}_concatConversationID(B){let v="";const G=this.conversationType;G!==Qr.CONV_SYSTEM?(v=G===Qr.CONV_C2C?B===this.from?this.to:this.from:this.to,this.conversationID=v?`${G}${v}`:null):this.conversationID=Qr.CONV_SYSTEM}_initSequence(B){this.clientSequence===0&&B&&(this.clientSequence=mC(B)),this.sequence===0&&this.conversationType===Qr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Qr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(B){this.isRead=B}}class kl{static parseServerPushElement(B){const{MsgContent:v={}}=B,{Data:G,Ext:O,Desc:z}=v;return new kl({data:G,description:z,extension:O})}constructor(B){this.type=Xa.MSG_CUSTOM;const{data:v="",description:G="",extension:O=""}=B;this.content={data:v,description:G,extension:O}}transformToServerFormat(B){const{isMergerMessage:v=!1}=B||{},G=v?this.payload:this.content,{data:O,description:z,extension:X}=G;return{MsgType:this.type,MsgContent:{Data:O,Ext:X,Desc:z}}}validateBeforeSend(){const{isEmpty:B}=Se.utils,v=[this.content.data,this.content.description,this.content.extension].some(G=>!B(G));return{isValid:v,error:v?null:{message:"content can not be empty"}}}}class Au{static parseServerPushElement(B){const{MsgContent:v={Text:""}}=B,{Text:G}=v;return new Au({text:G})}constructor(B){this.type=zg.MSG_TEXT,this.content={text:B.text||""}}validateBeforeSend(){var B,v;return((v=(B=this.content)===null||B===void 0?void 0:B.text)===null||v===void 0?void 0:v.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(B){const{isMergerMessage:v=!1}=B||{},G=v?this.payload:this.content,{text:O}=G;return{MsgType:this.type,MsgContent:{Text:O}}}}var QI=new class{constructor(){this._elementClassMap={[Xa.MSG_CUSTOM]:kl,[Xa.MSG_TEXT]:Au}}init(){js.getInstance().registerApi({apiName:"createCustomMessage",context:this}),js.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(p,B){var v;(v=B).prototype!==void 0&&"constructor"in v.prototype&&(this._elementClassMap[p]=B)}getElementClass(p){return this._elementClassMap[p]}createMessage(p){const{from:B,flow:v=go.OUT}=p,{userId:G}=Se.store.get("login")||{};this._isSendByCurrentInstance({from:B,flow:v,currentUser:G})?this._updateWithSenderInfo(p):this._isMultiEndpointSyncMessage({from:B,flow:v,currentUser:G})&&(p.flow=go.OUT);const O=Object.assign(Object.assign({},p),{currentUser:G});return new fC(O)}createCustomMessage(p){const B=jn(),v=this.createMessage(Object.assign(Object.assign({},p),{from:B})),G=this._elementClassMap[Xa.MSG_CUSTOM];if(!v)return null;if(G){const O=new G(p.payload);v.setElement(O)}return v}createTextMessage(p){var B;if(!p)return null;const v=typeof p.payload=="string"?p.payload:((B=p?.payload)===null||B===void 0?void 0:B.text)||"",G=new Au({text:v}),O=jn(),z=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},p),{from:O}));return z.setElement(G),z}_updateWithSenderInfo(p){var B,v;const{nick:G,avatar:O,conversationType:z,to:X}=p,{userId:rA,tinyID:DA}=Se.store.get("login")||{},GA=ea.getUserProfile(rA);return p.nick=G||GA?.nick||"",p.avatar=O||GA?.avatar||"",p.tinyID=p.tinyID||DA||"",p.from=rA,p.status=wg.UNSENT,p.flow=go.OUT,z===_g.CONV_GROUP&&(p.nameCard=(v=(B=Za.getGroup(X))===null||B===void 0?void 0:B.selfInfo)===null||v===void 0?void 0:v.nameCard),p}_isMultiEndpointSyncMessage(p){const{from:B,flow:v,currentUser:G}=p;return B===G&&v===go.IN}_isSendByCurrentInstance(p){const{from:B,flow:v,currentUser:G}=p;return B===G&&v===go.OUT}};const pI={PushFlag:0,Title:"",Desc:"",Ext:"",ApnsInfo:{Sound:"",BadgeMode:0,IsVoipPush:void 0,Image:"",InterruptionLevel:"active",ContentAvailable:0},AndroidInfo:{Sound:"",XiaoMiChannelID:"",OPPOChannelID:"",GoogleChannelID:"",VIVOClassification:1,VIVOCategory:"",HuaWeiCategory:"",OPPOCategory:"",HuaWeiImage:"",HonorImage:"",GoogleImage:"",HonorImportance:"",MeizuNotifyType:void 0}},bE={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Ll={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Ul(p,B){return Object.keys(B).forEach(v=>{const{range:G,defaultValue:O}=B[v];p[v]=G.includes(p[v])?p[v]:O}),p}function Ug(p){const B=p.lastIndexOf(".");return B===-1?p:p.slice(0,B)}function ec(p){const{androidInfo:B={},androidOPPOChannelID:v=""}=p,G=B.OPPOChannelID||v,O=Ul(B,bE),{sound:z="",FCMChannelID:X=""}=O,rA=So(O,["sound","FCMChannelID"]);return Object.assign(Object.assign({},rA),{Sound:Ug(z),OPPOChannelID:G,GoogleChannelID:X})}function md(p){const{apnsInfo:B={},ignoreIOSBadge:v=!1,disableVoipPush:G}=p,O=Ul(B,Ll),{ignoreIOSBadge:z,disableVoipPush:X,enableIOSBackgroundNotification:rA}=O,DA=So(O,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),GA=z===!0||v===!0?1:0;let JA;return n(G)||(JA=G===!1?1:0),n(X)||(JA=X===!1?1:0),Object.assign(Object.assign({},DA),{BadgeMode:GA,IsVoipPush:JA,ContentAvailable:rA?1:0})}function kE(p){return Se.utils.isPlainObject(p)?{PushFlag:p.disablePush===!0?1:0,Title:p.title||"",Desc:p.description||"",Ext:p.extension||"",ApnsInfo:md(p),AndroidInfo:ec(p)}:pI}function Nc(p){const{From_AccountHeadurl:B,From_AccountNick:v,IsNeedReadReceipt:G,IsPeerRead:O,IsSyncMsg:z,MsgBody:X,MsgClientTime:rA,MsgLifeTime:DA,MsgRandom:GA,MsgSeq:JA,MsgTimeStamp:ne,SendMsgControl:he,SupportMessageExtension:Ze,TinyId:st,MsgCheckResult:at,CloudCustomData:Ft,MsgVersion:Ht,MsgFlagBits:Pi,RevokerInfo:co,InnerSdkCustomData:Xi}=p;let di,{From_Account:xo,To_Account:ts}=p;if(z===1){const mi=ts;ts=xo,xo=mi}if(co){const{Reason:mi,Revoker_Account:zi,Revoker_FromUin:Ws}=co;di={reason:mi,revoker:zi,revokerFromUin:Ws,userID:zi}}return{from:xo,avatar:B,nick:v,needReadReceipt:G===1,isSyncMessage:z,clientTime:rA,messageLifeTime:DA,random:GA,sequence:JA,time:ne,messageControlInfo:{excludedFromLastMessage:he?.NoLastMsg===1,excludedFromUnreadCount:he?.NoUnread===1},isSupportExtension:Ze,to:ts,tinyID:st,checkResult:at,cloudCustomData:Ft,revokerInfo:di,messageVersion:Ht,messageFlagBits:Pi,readReceiptSentByPeer:O,elements:$a(X),onlineOnlyFlag:DA===0,quoteInfo:xu(Xi)}}function eu(p){const{From_Account:B,MsgBody:v,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,To_Account:rA,MsgVersion:DA,CloudCustomData:GA,MsgCheckResult:JA}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,to:rA,elements:$a(v),messageVersion:DA,cloudCustomData:GA,checkResult:JA}}function Io(p){const{ClientSeq:B,From_Account:v,GroupInfo:G,MsgBody:O,MsgClientTime:z,MsgRandom:X,MsgSeq:rA,MsgTimeStamp:DA,SendMsgControl:GA,SupportMessageExtension:JA,TinyId:ne,CloudCustomData:he,MsgVersion:Ze,MsgCheckResult:st,NeedReadReceipt:at,IsPlaceMsg:Ft,RevokerInfo:Ht,GroupAtInfo:Pi,OnlineOnlyFlag:co,InnerSdkCustomData:Xi}=p;let di,xo=Vr.MSG_PRIORITY_NORMAL;if(Object.keys(GE).includes(String(p.MsgPriority))&&(xo=GE[p.MsgPriority]),Ht){const{Reason:mi,Revoker_Account:zi,Revoker_FromUin:Ws}=Ht;di={reason:mi,revoker:zi,revokerFromUin:Ws,userID:zi}}const ts=function(mi){const zi=[];return Array.isArray(mi)&&mi.forEach(Ws=>{Ws.GroupAtAllFlag===pC?zi.push(Ws.GroupAt_Account):Ws.GroupAtAllFlag===uh&&zi.push(Bs.MSG_AT_ALL)}),zi}(Pi);return{clientSequence:B,from:v,groupProfile:G,clientTime:z,priority:xo,random:X,sequence:rA,time:DA,messageControlInfo:{excludedFromLastMessage:GA?.NoLastMsg===1,excludedFromUnreadCount:GA?.NoUnread===1},isSupportExtension:JA,tinyID:ne,cloudCustomData:he,messageVersion:Ze,checkResult:st,needReadReceipt:at,isPlaceMessage:Ft,revokerInfo:di,atUserList:ts,elements:$a(O),to:LE(p),onlineOnlyFlag:co===1,quoteInfo:xu(Xi)}}function LE(p){const{utils:{isEmpty:B},constants:{IS_TOPIC_MESSAGE:v}}=Se,{ToGroupId:G,GroupInfo:{MillionGroupFlag:O=0,TopicId:z}={}}=p;return O!==v||B(z)?G:z}function $a(p){if(!p)return null;if(Array.isArray(p))return p.map(v=>{const G=Se.message.messageFactory.getElementClass(v.MsgType);return G?.parseServerPushElement(v)});const B=Se.message.messageFactory.getElementClass(p.MsgType);return B?.parseServerPushElement(p)}function tu(p){const{From_Account:B,MsgBody:v,MsgClientTime:G,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,GroupId:rA,TopicId:DA,MsgVersion:GA,CloudCustomData:JA,MsgCheckResult:ne}=p;return{from:B,clientTime:G,random:O,sequence:z,time:X,groupID:rA,topicID:DA,elements:$a(v),messageVersion:GA,cloudCustomData:JA,checkResult:ne}}function xu(p){const{utils:{isString:B,safeStringify:v},ssoLog:G}=Se;if(!B(p))return null;try{const{messageID:O,messageTime:z,messageSequence:X}=JSON.parse(p).businessQuote;return{msgID:O,messageTime:z,messageSequence:X}}catch(O){return G.debug("_parseServerQuoteInfo",v(O)),null}}function Gc({conversationUpdateFields:p,message:B}){const{conversationID:v,conversationType:G,conversationSubType:O,flow:z,_isExcludedFromUnreadCount:X,_isExcludedFromLastMessage:rA}=B,DA=rA?"":ol(B),GA=!X&&z===go.IN;p.has(v)?(p.get(v).lastMessage=DA,GA&&p.get(v).unreadCount++):p.set(v,{conversationID:v,type:G,subType:O,unreadCount:GA?1:0,lastMessage:DA})}function mI(p){return p.filter(B=>{const v=!Rs(B?._elements),G=B?.isPlaceMessage===1;return v||Se.ssoLog.error("emptyMessageBody",`from:${B.from} to:${B.to} sequence:${B.sequence}`),v&&!G})}function sl(p){const{messageDataHandler:B}=Se.message;return!B.isInMessageList(p)&&!B.isMessageSentByCurrentInstance(p)}var nl=Object.freeze({__proto__:null,autoIncrementIndex:mC,createAndroidPushInfo:ec,createApnsPushInfo:md,createOfflinePushInfo:kE,filterValidMessages:mI,getAndroidSoundName:Ug,parseServerGroupMessage:Io,parseServerPushC2CModifyMessage:eu,parseServerPushGroupModifyMessage:tu,parseServerPushMessage:Nc,parseServerPushMessageElement:$a,shouldStoreMessage:sl,updateConversationFields:Gc});const{isPlainObject:xa}=Se.utils;function UE(p,B={}){const{onlineUserOnly:v,messageControlInfo:G}=B;let{offlinePushInfo:O}=B;p.conversationType===Qr.CONV_C2C&&v===!0&&(O?O.disablePush=!0:O={disablePush:!0});let z="";typeof p.cloudCustomData=="string"&&p.cloudCustomData.length>0&&(z=p.cloudCustomData);const X=[];if(G&&xa(G)){const{excludedFromUnreadCount:rA,excludedFromLastMessage:DA,excludedFromContentModeration:GA}=G;rA===!0&&X.push("NoUnread"),DA===!0&&X.push("NoLastMsg"),GA===!0&&X.push("NoMsgCheck")}return{onlineUserOnly:v,cloudCustomData:z,messageControlInfo:X,offlinePushInfo:O}}function aa(p){const{webhookInfo:{disableCloudMessagePreHook:B=!1,disableCloudMessagePostHook:v=!1}={}}=p||{};if(!B&&!v)return;const G=[];return B&&G.push("ForbidBeforeSendMsgCallback"),v&&G.push("ForbidAfterSendMsgCallback"),G}function Mn(p,B){return mA(this,void 0,void 0,function*(){const v=p.conversationType===Qr.CONV_GROUP?function(O,z){var X;const rA=UE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:JA,offlinePushInfo:ne}=rA,he=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));let Ze;return C(O._receiverList)&&O._receiverList.length>0&&(Ze=O._receiverList,O._receiverList.length>50&&(Ze=O._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(X=Se.store.get("login"))===null||X===void 0?void 0:X.userId,GroupId:O.to,MsgBody:he,CloudCustomData:GA,Random:O.random,MsgPriority:O.priority,ClientSeq:O.clientSequence,GroupAtInfo:O._groupAtInfoList,OnlineOnlyFlag:DA?1:0,MsgClientTime:O.clientTime,OfflinePushInfo:kE(ne),SendMsgControl:DA?void 0:JA,NeedReadReceipt:O.needReadReceipt===!0?1:0,To_Account:Ze,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,ForbidCallbackControl:aa(z),InnerSdkCustomData:FE(O)}}}(p,B):function(O,z){var X;const rA=UE(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:JA,offlinePushInfo:ne}=rA,he=DA===!0?0:void 0,Ze=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(X=Se.store.get("login"))===null||X===void 0?void 0:X.userId,To_Account:O.to,MsgBody:Ze,CloudCustomData:GA,MsgSeq:O.sequence,MsgRandom:O.random,MsgLifeTime:he,From_AccountNick:O.nick,From_AccountHeadurl:O.avatar,SendMsgControl:he!==0?JA:void 0,MsgClientTime:O.clientTime,IsNeedReadReceipt:O.needReadReceipt===!0?1:0,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,OfflinePushInfo:kE(ne),ForbidCallbackControl:aa(z),InnerSdkCustomData:FE(O)}}}(p,B),G=yield Zg(v);return G?{time:G.MsgTime,messageDropReason:G.MsgDropReason,sequence:G.MsgSeq}:null})}function kr(p){return mA(this,void 0,void 0,function*(){const{from:B,to:v,version:G=0,sequence:O,random:z,time:X,type:rA,cloudCustomData:DA}=p,GA={From_Account:B,To_Account:v,MsgVersion:G,MsgSeq:O,MsgRandom:z,MsgTime:X,MsgType:rA,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:DA},JA=yield Zg({servcmd:"openim.modify_c2c_msg",data:GA});if(JA){const{MsgBody:ne,MsgVersion:he,CloudCustomData:Ze}=JA;return{elements:$a(ne),messageVersion:he,cloudCustomData:Ze}}})}function rl(p){return mA(this,void 0,void 0,function*(){const{to:B,version:v=0,sequence:G,cloudCustomData:O}=p,z={GroupId:B,MsgVersion:v,MsgSeq:G,MsgBody:p.transformElementsToServerFormat(),CloudCustomData:O},X=yield Zg({servcmd:"openim.modify_group_msg",data:z});if(X){const{MsgBody:rA,MsgVersion:DA,CloudCustomData:GA}=X;return{elements:$a(rA),messageVersion:DA,cloudCustomData:GA}}})}function Fl(p){return mA(this,void 0,void 0,function*(){const{groupID:B,count:v,messageSequence:G,messageSequenceList:O,getType:z}=p,X={GroupId:B,ReqMsgNumber:v,WithRecalledMsg:1,Version:1,GetType:z};return G&&(X.ReqMsgSeq=G),C(O)&&O.length>0&&(X.ReqMsgSeqList=O),yield Zg({servcmd:"group_open_http_svc.group_msg_get",data:X})})}function bc(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:v,lastMessageTime:G,messageKey:O,direction:z}=p;return Zg({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:v,WithRecalledMsg:1,LastMsgTime:G,MsgKey:O,GetDirection:z}})})}function FE(p){if(Se.utils.isObject(p.quoteInfo)){const{msgID:B,messageSequence:v,messageTime:G}=p.quoteInfo;return JSON.stringify({businessQuote:{messageID:B,messageSequence:v,messageTime:G}})}}var kc=Object.freeze({__proto__:null,createMessagePackOptions:UE,generateForbidCallbackControl:aa,getC2CRoamingMessagesByAnchor:bc,getGroupRoamingMessagesByAnchor:Fl,getRoamingMessages:function(p){return mA(this,void 0,void 0,function*(){const{peerAccount:B,count:v,lastMessageTime:G,messageKey:O}=p;return(yield Zg({servcmd:"openim.getroammsg",data:{Peer_Account:B,MaxCnt:v||15,LastMsgTime:G||0,MsgKey:O,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:kr,modifyGroupMessage:rl,sendMessage:Mn});const{isPlainObject:Yu}=Se.utils,{MSG_AUDIO:yC,MSG_FILE:iu,MSG_IMAGE:Eh,MSG_VIDEO:Vu,MSG_MERGER:fI}=Bs;class al{constructor(){this._sendProtocolMap=new Map}init(){js.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:B=>![yC,iu,Eh,Vu,fI].includes(B[0].type)})}registerSendProtocol(B,v,G){this._sendProtocolMap.set(B,v.bind(G))}sendMessage(B,v){return mA(this,void 0,void 0,function*(){const{TOTAL_COUNT:G,SEND_COST:O,SUCCESS_COUNT:z,FAILED_COUNT:X}=lI;if(!(B instanceof fC))throw new rs({code:Uo.MSG_INSTANCE_REQUIRED});const rA=B.validateBeforeSend();if(!rA.isValid){const{code:JA,message:ne=""}=rA.error||{};throw new rs({code:JA,message:ne})}this._reportMessageSendQuality({name:G,message:B});let DA=!1;const{messageDataHandler:GA}=Se.message||{};try{const{messageControlInfo:JA}=v||{};let ne=null;GA.addRandomOfSentMessage(B.random);const he=Date.now(),Ze=this._getSendProtocol(B);if(B.conversationType===Qr.CONV_C2C?(DA=v?.onlineUserOnly===!0,ne=yield Ze(B,v)):B.conversationType===Qr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(B),ne=yield Ze(B,v)),ne){const{messageDropReason:st,sequence:at,time:Ft}=ne;if(this._updateNickAndAvatarOfSentMessageByMe(B),st&&this._logRateLimitInfo(B,at,st),this._reportMessageSendQuality({name:z,message:B}),this._reportMessageSendQuality({name:O,message:B,startTs:he}),B.isResend===!0){const Ht=GA.findMessage(B.ID);Ht&&(Se.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${Ht.ID}`),GA.deleteConversationMessage(Ht))}return B.status=wg.SUCCESS,B.time=Ft,B.conversationType===Qr.CONV_GROUP&&(B.sequence=at),DA?B._onlineOnlyFlag=!0:(GA.storeConversationMessage(B),this._applySentMessageControlInfo(B,JA),this._emitOnlineMessageSent(B)),B.type===zg.MSG_STREAM?{code:0,data:{message:B,streamMessageID:ne.streamMessageID}}:{code:0,data:{message:B}}}}catch(JA){B.status=wg.FAIL,GA.removeRandomOfSentMessage(B.random);let{errorCode:ne}=JA||{},he=JA?.errorInfo||JA?.message||"";throw this._hasRiskContent(ne)&&(B.hasRiskContent=!0),DA||this._isRejectedByRestApi(ne)||GA.storeConversationMessage(B),this._reportMessageSendQuality({name:X,message:B,error:JA}),new rs({code:ne,message:he,data:{message:B},moreMessage:`type:${B.type} from:${B.from} to:${B.to}`})}})}_hasRiskContent(B){return B===80001||B===80004}_isRejectedByRestApi(B){return B>=10100&&B<=10200||B>=120001&&B<=13e4}_emitOnlineMessageSent(B){const v=B._isExcludedFromLastMessage?"":B,{conversationID:G,conversationType:O}=B,z=$r(G)?Ei.TOPIC_NEW_MESSAGE:Ei.NEW_MESSAGE;Se.notificationCenter.emitInnerEvent(z,{result:{conversationUpdateFieldList:[{conversationID:G,type:O,message:B,lastMessage:v,unreadCount:0}]}})}_applySentMessageControlInfo(B,v){v&&Yu(v)&&(v.excludedFromLastMessage===!0&&(B._isExcludedFromLastMessage=!0),v.excludedFromUnreadCount===!0&&(B._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(B,v,G){const O=`from:${B.from} to:${B.to} sequence:${v} messageDropReason:${G}`;Se.ssoLog.warn("messageDropReason",O)}_updateNickAndAvatarOfSentMessageByMe(B){const{messageDataHandler:v}=Se.message||{};let G=!1;const{conversationID:O}=B,z=v.getLatestMsgSentByMe(O);if(z){const{nick:X,avatar:rA}=z;X===B.nick&&rA===B.avatar||(G=!0),G&&v.updateNickAndAvatarOfSentMessage({conversationID:O,latestNick:B.nick,latestAvatar:B.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(B){return mA(this,void 0,void 0,function*(){var v,G,O;const{to:z,from:X}=B;let rA=z,DA=Za.getGroup(rA);if(Ca({groupID:rA})&&DA?.isSupportTopic)throw new rs({code:Uo.MSG_SEND_GRP_WITH_TOPIC_FAIL});if($r(z)&&([rA]=z.split(La.TOPIC),DA=Za.getGroup(rA)),!DA&&typeof((v=js.getInstance().getApiMap())===null||v===void 0?void 0:v.getGroupProfile)=="function"){const GA=yield js.getInstance().getApiMap().getGroupProfile({groupID:rA});if(((O=(G=GA?.data)===null||G===void 0?void 0:G.group)===null||O===void 0?void 0:O.type)===Bs.GRP_AVCHATROOM){const JA=_l({code:Uo.MSG_SEND_FAIL_NOT_IN_AV,replacement1:X,replacement2:rA});throw new rs({code:Uo.MSG_SEND_FAIL_NOT_IN_AV,message:JA})}}return!0})}_reportMessageSendQuality(B){Se.notificationCenter.emitInnerEvent(Ei.QUALITY_STAT,{label:Ng.MESSAGE_SEND_SUCCESS_RATE,data:B})}_getSendProtocol(B){return this._sendProtocolMap.get(B.type)||Mn}}var DC=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){Se.notificationCenter.subscribeInnerEvent(Ei.LOGOUT,this._reset,this),Se.notificationCenter.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}get _messagesByConversation(){return Gl.getMessages()}storeConversationMessage(p,B=!1){if(an)return!0;const{conversationID:v}=p;if(!v||(this._messagesByConversation.has(v)||this._messagesByConversation.set(v,new Map),this._shouldSkipStoreMessage(p,B)))return!1;const G=this._getUniqueIdOfMessage(p);return this._messagesByConversation.get(v).set(G,p),this._updateLatestMessageMap(p),!0}_updateLatestMessageMap(p){const{conversationID:B}=p;p.flow==="out"?this._setLatestMsgSentByMe(B,p):B.startsWith("C2C")&&this._setLatestMsgSentByPeer(B,p)}_shouldSkipStoreMessage(p,B){const v=this._getUniqueIdOfMessage(p),G=this._messagesByConversation.get(p.conversationID);if(G?.has(v)){const O=G?.get(v);if(!B||O?.isModified===!0)return!0}return!1}deleteConversationMessage(p){var B;const{conversationID:v=""}=p,G=this._getUniqueIdOfMessage(p);this._messagesByConversation.has(v)&&((B=this._messagesByConversation.get(v))===null||B===void 0||B.delete(G))}modifyConversationMessage(p,B){var v;if(!this._messagesByConversation.has(p)&&!this._sparseMessagesByConversation.has(p))return{isUpdated:!1,message:null};const G=this._getUniqueIdOfMessage(B),O=this._getMessageFromLocalMessage(p,G);if(O){const{messageVersion:z,elements:X,cloudCustomData:rA,checkResult:DA=0}=B,GA=DA>1;if(Se.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${O.version} remoteVersion:${z}`),O.versionO.ID===p)||null,B)break;if(!B){const G=Array.from(this._sparseMessagesByConversation.values());for(const O of G)if(B=O.get(p)||null,B)break}return B}deleteConversationMessageList(p){this._messagesByConversation.has(p)&&(this._messagesByConversation.delete(p),this._latestMessageSentByMeMap.delete(p),this._latestMessageSentByPeerMap.delete(p)),this._sparseMessagesByConversation.has(p)&&this._sparseMessagesByConversation.delete(p)}revokeMessage({conversationID:p,sequence:B,random:v,revoker:G}){const O=this._messagesByConversation.get(p);let z=null;if(O){const X=Array.from(O.values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:B}),z){const rA=this._getUniqueIdOfMessage(z);return Gl.updateMessage(p,[rA],{isRevoked:!0,revoker:G,operation:Yr.revoke}),z}}if(this._sparseMessagesByConversation.has(p)){const X=Array.from(this._sparseMessagesByConversation.get(p).values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:B}),z)return z.isRevoked=!0,z.revoker=G,z}}_findMessageBySequenceAndRandom({messageList:p,sequence:B,random:v}){for(let G=0;G0){const X=new Map([...O,...z.entries()]);this._messagesByConversation.set(v,X),this._updateLatestMessageSentByMe(v),this._updateLatestMessageSentByPeer(v)}return G}storeSparseMessageList(p){if(p.length===0)return;const{conversationID:B}=p[0],v=p.length;this._sparseMessagesByConversation.has(B)||this._sparseMessagesByConversation.set(B,new Map);const G=this._sparseMessagesByConversation.get(B);for(let O=0;O=0;G--)if(v[G].flow==="out"){this._setLatestMsgSentByMe(p,v[G]);break}}}_updateLatestMessageSentByPeer(p){var B;const v=Array.from(((B=this._messagesByConversation.get(p))===null||B===void 0?void 0:B.values())||[]);if(v.length!==0&&p.startsWith("C2C")){for(let G=v.length-1;G>=0;G--)if(v[G].flow==="in"){this._setLatestMsgSentByPeer(p,v[G]);break}}}_getUniqueIdOfMessage(p){const{from:B,to:v,random:G,sequence:O,time:z}=p;return`${B}-${v}-${G}-${O}-${z}`}_setLatestMsgSentByPeer(p,B){this._latestMessageSentByPeerMap.set(p,B)}_setLatestMsgSentByMe(p,B){this._latestMessageSentByMeMap.set(p,B)}getLatestMsgSentByPeer(p){return this._latestMessageSentByPeerMap.get(p)}getLatestMsgSentByMe(p){return this._latestMessageSentByMeMap.get(p)}addRandomOfSentMessage(p){this._randomOfSentMessageList.add(p)}removeRandomOfSentMessage(p){this._randomOfSentMessageList.delete(p)}updateNickAndAvatarOfSentMessage(p){const{conversationID:B="",latestAvatar:v,latestNick:G,isSentByMe:O=!0}=p,z=this._messagesByConversation.get(B);if(!z)return;const X=Array.from(z.values()),rA=O?"out":"in";X.forEach(DA=>{const{nick:GA,avatar:JA,flow:ne}=DA;ne===rA&&(GA!==G&&(DA.nick=G),JA!==v&&(DA.avatar=v))})}isInMessageList(p){var B;const{conversationID:v}=p;if(!v||!this._messagesByConversation.has(v))return!1;const G=this._getUniqueIdOfMessage(p);return(B=this._messagesByConversation.get(v))===null||B===void 0?void 0:B.has(G)}isMessageSentByCurrentInstance(p){const{random:B}=p;return this._randomOfSentMessageList.has(B)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(p){const B=this._messagesByConversation.get(p);return B?[...B.values()]:[]}getSparseMessageList(p){const B=this._sparseMessagesByConversation.get(p);return B?[...B.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),Se.notificationCenter.unSubscribeInnerEvent(Ei.LOGOUT,this._reset,this),Se.notificationCenter.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this)}};function ga(p,B){const v=$g.getConversation(p);if(v?.lastMessage){const{lastMessage:G}=v,{lastTime:O,lastSequence:z,version:X}=G,{time:rA,sequence:DA,messageVersion:GA,elements:JA,cloudCustomData:ne}=B;O===rA&&z===DA&&X!==GA&&(G.type=JA[0].type,G.payload=JA[0].content,G.messageForShow=WI(G.type,G.payload),G.cloudCustomData=ne,G.version=GA,$g.updateConversation(p,{lastMessage:G}))}}class tc{init(){js.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(B){return mA(this,void 0,void 0,function*(){const{to:v,payload:G,sequence:O,conversationType:z,random:X,time:rA,from:DA,type:GA}=B;if(this._canModifyMessageElement(GA)){const JA=B?._elements||[];JA.length>=1&&(JA[0].type=GA,JA[0].content=G)}try{let JA=null,ne=null;if(z===Qr.CONV_C2C?JA=yield kr(B):z===Qr.CONV_GROUP&&(JA=yield rl(B)),JA){let he=`${z}${v}`;return v===jn()&&z===Qr.CONV_C2C&&(he=`${z}${DA}`),ne={conversationType:z,from:DA,to:v,time:rA,random:X,sequence:O,elements:JA?.elements,cloudCustomData:JA?.cloudCustomData,messageVersion:JA?.messageVersion,conversationID:he},this._handleModifyMessageSuccess(ne),{code:0,data:{message:B},successLog:{message:`to:${v}`}}}}catch(JA){const{errorCode:ne}=JA||{};throw new rs({functionName:"modifyMessage",code:ne,moreMessage:`to:${v}`})}})}_handleModifyMessageSuccess(B){const{conversationID:v}=B,{isUpdated:G,message:O}=Se.message.messageDataHandler.modifyConversationMessage(v,B);G===!0&&Se.notificationCenter.emitOuterEvent(Dn.MESSAGE_MODIFIED,{name:Dn.MESSAGE_MODIFIED,data:[O]}),Se.notificationCenter.emitInnerEvent(Ei.MESSAGE_MODIFIED,{conversationID:v,message:O}),ga(v,B)}_canModifyMessageElement(B){return[Xa.MSG_TEXT,Xa.MSG_CUSTOM,Xa.MSG_LOCATION,Xa.MSG_FACE].includes(B)}}class lg{init(){const{notificationCenter:B}=Se,{InnerEventSubType:v}=B;tn.getInstance().registerWorkflowStep(gr.RECEIVE_C2C_NEW_MESSAGE,Jt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),tn.getInstance().registerWorkflowStep(gr.RECEIVE_C2C_NEW_MESSAGE,Jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),tn.getInstance().registerWorkflowStep(gr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Jt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),B.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){tn.getInstance().executeWorkflow(gr.RECEIVE_C2C_NEW_MESSAGE,B)}_handleC2CMessagePush(B){const v=B.data||{},{messageDataHandler:G}=Se.message||{},O=[],z=new Map;return v.C2cMsgArray.forEach(X=>{const rA=this._generateC2CMessage(X);this._updateMessageProfile(rA);let DA=rA.isModified===1;G.isMessageSentByCurrentInstance(rA)?rA.isModified=DA:DA=!1,rA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(rA)||O.push(rA):sl(rA)&&(G.storeConversationMessage(rA)&&Gc({conversationUpdateFields:z,message:rA}),G.isMessageSentByCurrentInstance(rA)&&!DA||O.push(rA))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEventsAfterReceiveNewMessage(B){var v;const{messages:G=[]}=((v=B.result)===null||v===void 0?void 0:v[Jt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(G)}_emitMessageEventsAfterSyncUnreadMessage(B){var v;const{messages:G=[]}=((v=B.result)===null||v===void 0?void 0:v[Jt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(G)}_emitMessageEvents(B){const v=B?.filter(O=>O?.isModified===!0)||[];v.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:v});const G=B?.filter(O=>!O?.isModified);G.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:G})}_generateC2CMessage(B){const v=Qr.CONV_C2C,G=Nc(B),O=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:v,flow:go.IN})),{elements:z}=G;return O.setElement(z),O}_updateMessageProfile(B){var v;const{messageDataHandler:G}=Se.message||{},O=(v=Se.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA=""}=B;if(z!==O){const GA=G.getLatestMsgSentByPeer(DA);if(GA){const{nick:JA,avatar:ne}=GA;n(X)||n(rA)?(B.nick=c(JA)?JA:B.nick,B.avatar=c(ne)?ne:B.avatar):X===JA&&rA===ne||(G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:DA,nick:X,avatar:rA}))}}else{const GA=G.getLatestMsgSentByMe(DA);!GA||X===GA.nick&&rA===GA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!0})}}_updateConversationUserProfile(B){const{conversationID:v,nick:G,avatar:O}=B,z=$g.getConversation(v),{userProfile:X={}}=z||{};X.avatar===O&&X.nick===G||$g.updateConversation(v,{userProfile:Object.assign(Object.assign({},X),{nick:G,avatar:O})})}_updateMessageListDueToModify(B){const{conversationID:v}=B,{isUpdated:G,message:O}=Se.message.messageDataHandler.modifyConversationMessage(v,B);G===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),Se.notificationCenter.emitInnerEvent("ModifyMessageSuccess",B),ga(v,B)}_handleC2CMessageModify(B){B.C2cMsgModNotifys.forEach(v=>{var G;const O=Qr.CONV_C2C;let z=eu(v);const{to:X,from:rA}=z;let DA=`${O}${X}`;X===((G=Se.store.get("login"))===null||G===void 0?void 0:G.userId)&&(DA=`${O}${rA}`),z=Object.assign({conversationType:O,conversationID:DA},z),this._updateMessageListDueToModify(z)})}_dispose(){const{notificationCenter:B}=Se,{InnerEventSubType:v}=B;Se.notificationCenter.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),Se.notificationCenter.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),Se.notificationCenter.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this)}}class yI{init(){const{notificationCenter:B}=Se,{InnerEventSubType:v}=B;tn.getInstance().registerWorkflowStep(gr.RECEIVE_GROUP_NEW_MESSAGE,Jt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),tn.getInstance().registerWorkflowStep(gr.RECEIVE_GROUP_NEW_MESSAGE,Jt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,v.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,v.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),B.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(B){this._canExecuteReceiverNewMessageWorkFlow(B)&&tn.getInstance().executeWorkflow(gr.RECEIVE_GROUP_NEW_MESSAGE,B)}_handleGroupMessagePush(B){const v=B.data||{},{messageDataHandler:G}=Se.message,O=[],z=new Map,X=v?.GroupMsgArray;return X?.forEach(rA=>{if(rA.GroupInfo.NotVisible===1)return;const DA=this._generateGroupMessage(rA);this.updateMessageProfile(DA);let GA=DA.isModified===1;G.isMessageSentByCurrentInstance(DA)?DA.isModified=GA:GA=!1,DA._onlineOnlyFlag?G.isMessageSentByCurrentInstance(DA)||O.push(DA):sl(DA)&&G.storeConversationMessage(DA)&&(O.push(DA),Gc({conversationUpdateFields:z,message:DA}))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEvents(B){var v;const{messages:G}=((v=B.result)===null||v===void 0?void 0:v[Jt.HANDLE_GROUP_NEW_MESSAGE])||{},O=G?.filter(X=>X?.isModified===!0)||[];O.length>0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:O});const z=G?.filter(X=>!X?.isModified)||[];z.length>0&&Se.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:z})}_generateGroupMessage(B){const v=Qr.CONV_GROUP,G=Io(B),O=Se.message.messageFactory.createMessage(Object.assign(Object.assign({},G),{conversationType:v,flow:go.IN})),{elements:z}=G;return O.setElement(z),O}updateMessageProfile(B){var v;const{messageDataHandler:G}=Se.message||{},O=(v=Se.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA="",_elements:GA}=B;if(z===O){const JA=G.getLatestMsgSentByMe(DA);!JA||X===JA.nick&&rA===JA.avatar||G.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!0})}else if(z===Bs.CONV_SYSTEM){const{operationType:JA,memberInfoList:ne,operatorInfo:he}=GA;let Ze={};if(Rs(ne)?Rs(he)||(Ze=he):[na.JOINED,na.KICKED,na.ADMIN_SET,na.ADMIN_CANCELED].includes(JA)&&(Ze=Object.assign({},ne[0])),!Rs(Ze)){const{nick:st="",avatar:at=""}=Ze;B.nick=st,B.avatar=at}}}_updateMessageListDueToModify(B){const{conversationID:v}=B,{isUpdated:G,message:O}=Se.message.messageDataHandler.modifyConversationMessage(v,B);G===!0&&Se.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),ga(v,B)}_handleGroupMessageModify(B){B.GroupMsgModNotifys.forEach(v=>{const G=Qr.CONV_GROUP;let O=tu(v);const{topicID:z,groupID:X}=O,rA=z||X,DA=`${G}${rA}`;O=Object.assign({conversationType:G,conversationID:DA,to:rA},O),this._updateMessageListDueToModify(O)})}_dispose(){const{notificationCenter:B}=Se,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:v,GROUP_MESSAGE_MODIFIED:G}}=B;B.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,v,this._handleGroupMessagePush,this),B.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,G,this._handleGroupMessageModify,this),B.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(B){var v,G;const{GroupId:O,GroupType:z}=((G=(v=B?.GroupMsgArray)===null||v===void 0?void 0:v[0])===null||G===void 0?void 0:G.GroupInfo)||{},X=z===SE.GRP_AVCHATROOM;return!(!Za.getGroup(O)&&X)}}var OE=new class{constructor(){this.c2cMessageReceiver=new lg,this.groupMessageReceiver=new yI}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Ju={createCustomMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1},payload:{required:!0,rules:["object"],allowEmpty:!1},cloudCustomData:{required:!1,rules:["string"],allowEmpty:!1},priority:{required:!1,rules:["string"],allowEmpty:!1},customModerationConfigurationID:{required:!1,rules:["string"],allowEmpty:!1}},sendMessage:[{key:"message",required:!0,rules:["object"],allowEmpty:!1},{key:"options",required:!1,rules:["object"],allowEmpty:!1}],createTextMessage:{to:{required:!0,rules:["string"],allowEmpty:!1},conversationType:{required:!0,rules:["string"],allowEmpty:!1,customValidator:p=>!(!p.startsWith("C2C")&&!p.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:p=>function(B){var v;return typeof B?.text!="string"||typeof B.text=="string"&&((v=B?.text)===null||v===void 0?void 0:v.length)===0?"payload.text must be a string":!0}(p)}}},Hu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var DI=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){try{const{conversationID:B,count:v,direction:G,sequence:O,messageSequenceList:z,shouldMarkCompleted:X=!1,getType:rA}=p,DA=B.replace(_g.CONV_GROUP,""),GA=[];let JA=O;if(G===yc.BACKWARD){if(typeof O!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};JA=O+v-1}const ne=yield Fl({groupID:DA,count:v,messageSequence:JA,messageSequenceList:z,getType:rA});if(ne){const{RspMsgList:he=[],NextReqMsgSeq:Ze=0,IsFinished:st,InvisibleMsgSeq:at}=ne,Ft=`groupID:${DA} sequence:${O} reqSeq:${JA} direction:${G} complete:${st} nextSequence:${Ze} remoteMsgCount:${he.length} invisibleSequenceList:${at}`,Ht=[];for(let Xi=0;Xi=O),Pi&&X&&this.completedHistoryConversations.add(B);const co=mI(Ht);return Se.ssoLog.info("getGroupRoamingMessagesByAnchor",Ft),{messageList:co,invisibleSequenceList:at,nextReqMessageIDFromServer:Ze,hasNoMoreHistoryMessage:Pi,serverGroupTipList:GA}}}catch(B){const{errorCode:v,errorInfo:G}=B||{};throw new rs({code:v,message:G})}})}clearHistoryMessageListFetchAnchors(p){this._historyMessageListFetchAnchors.delete(p)}isHistoryMessageFetchCompleted(p){return this.completedHistoryConversations.has(p)}_parseMessage(p){var B;const v=_g.CONV_GROUP;p.Event===4&&(p.MsgBody.MsgType=Bs.MSG_GRP_TIP);const G=Io(p),O=QI.createMessage(Object.assign(Object.assign({},G),{conversationType:v,flow:"in"}));return wc(((B=G.elements)===null||B===void 0?void 0:B.content)||{},O),O.setElement(G.elements),O}getC2CRoamingMessagesByAnchor(p){return mA(this,void 0,void 0,function*(){var B;try{const{conversationID:v,count:G,messageID:O,time:z,direction:X,shouldMarkCompleted:rA=!1}=p;let DA=z,GA="";if(!z){const he=O?Se.message.messageDataHandler.findMessage(O):null;if(DA=he?.time||0,O&&this._historyMessageListFetchAnchors.has(v)){const Ze=this._historyMessageListFetchAnchors.get(v);DA=Ze.lastMessageTime,GA=Ze.messageKey}}const JA=v.replace(_g.CONV_C2C,""),ne=yield bc({count:G,lastMessageTime:DA,messageKey:GA,peerAccount:JA,direction:X});if(ne){const{MsgList:he=[],Complete:Ze,MsgKey:st,LastMsgTime:at}=ne;this._historyMessageListFetchAnchors.set(v,{messageKey:st,lastMessageTime:at});const Ft=[];for(let Xi=0;Xi{const{tag:O,value:z}=G;O&&O.indexOf(Ig)>-1?v.profileCustomField.push({key:O,value:z}):Ol.has(O)&&(v[Ol.get(O)]=z)}),Object.assign(Object.assign({},Ya),v)}parseProfileItem(p=[]){const B=[];return p.forEach(v=>{B.push({tag:v.Tag,value:v.Value})}),B}parseProfileList(p=[]){const B=[];return p.forEach(v=>{B.push({tag:v.Tag,value:v.ValueBytes})}),B}convertParamsToProfile(p){const B=[];return Object.keys(p).forEach(v=>{v!==lr&&B.push({tag:Ur[v.toUpperCase()],value:p[v]})}),p.profileCustomField&&C(p.profileCustomField)&&p.profileCustomField.forEach(v=>{B.push({tag:v.key,value:v.value})}),B}normalizeProfileFields(p){const B={},v=[];return p.forEach(G=>{const{tag:O,value:z}=G;if(O&&O.indexOf(Ig)>-1&&v.push({key:O,value:z}),Ol.has(O)&&z!==void 0){const X=Ol.get(O);B[X]=z}}),v.length>0&&(B.profileCustomField=v),B}};const{generateProtocolData:SI}=Se.common;function ou(p){return mA(this,void 0,void 0,function*(){const B="profile.portrait_get_all",v={From_Account:jn(),UserItem:[]};p.forEach(X=>{v.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:X})});const G=SI({servcmd:B,data:v}),O=`${G.head.seq}${B}`,z=yield Se.channel.sendPacket(G,{requestId:O});if(z)return function(X){const{ActionStatus:rA,ErrorCode:DA,ErrorDisplay:GA,ErrorInfo:JA,UserProfileItem:ne}=X,he=[];return ne.map(Ze=>{const{To_Account:st,CustomSequence:at,ResultCode:Ft,ResultInfo:Ht,StandardSequence:Pi,ProfileItem:co}=Ze,Xi=ha.parseProfileItem(co);he.push({userId:st,customSequence:at,resultCode:Ft,resultInfo:Ht,standardSequence:Pi,profileItem:Xi})}),{actionStatus:rA,errorCode:DA,errorDisplay:GA,errorInfo:JA,userProfile:he}}(z)})}function Ba(p){return ea.getFriendMap().has(p)}const{isEmpty:cl}=Se.utils;class PE{constructor(){this._strangerProfileMap=new Map}init(){js.getInstance().registerApi({apiName:"getMyProfile",context:this}),js.getInstance().registerApi({apiName:"getUserProfile",context:this}),js.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=ha.createProfile.bind(ha);const{notificationCenter:B}=Se;tn.getInstance().registerWorkflowStep(gr.SYNC_SERVER_INFO_AFTER_LOGIN,Jt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.subscribeInnerEvent(Ei.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}getMyProfile(){return mA(this,void 0,void 0,function*(){try{const B=jn(),v=yield ou([B]);if(v){const G=this._handleProfileFormResponse(v)[0];return ea.getUserProfileMap().set(B,G),{code:0,data:G}}}catch(B){const{errorCode:v,errorInfo:G}=B;throw new rs({functionName:"getMyProfile",code:v,message:G})}})}getUserProfile(B){return mA(this,void 0,void 0,function*(){try{let{userIDList:v}=B;const{userIdListToRequest:G,profileFromCache:O}=this._filterRequestAndCacheUsers(v);if(G.length===0)return{code:0,data:O,successLog:{message:`userIDList.length:${v.length}`}};G.length>Fg&&(Se.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),G.length=Fg);const{data:z,error:X}=yield this._batchFetchUserProfiles(G),rA=G.length,DA=z.length,GA=rA-DA;if(O.length===0&&rA===GA&&!cl(X))throw X;if(C(z))return z.forEach(ne=>{Ba(ne.userID)?ea.getUserProfileMap().set(ne.userID,ne):this._strangerProfileMap.set(ne.userID,ne)}),{code:0,data:z.concat(O),successLog:{message:`getUserProfile query:${rA} success:${DA} fail:${GA} from cache:${O.length}`}}}catch(v){throw new rs(v)}})}getMyProfileCacheThenServer(){return mA(this,void 0,void 0,function*(){const B=jn(),v=ea.getUserProfileMap().has(B);return v?{code:0,data:v}:this.getMyProfile()})}updateMyProfile(B){return mA(this,void 0,void 0,function*(){const v=jn(),G={};for(const z in B)B[z]!==void 0&&(G[z]=B[z]);const O=ha.convertParamsToProfile(G);try{yield function(GA){return mA(this,void 0,void 0,function*(){const JA="profile.portrait_set",ne=SI({servcmd:JA,data:GA}),he=`${ne.head.seq}${JA}`,Ze=yield Se.channel.sendPacket(ne,{requestId:he});if(Ze){const{ActionStatus:st,ErrorCode:at,ErrorDisplay:Ft,ErrorInfo:Ht}=Ze;return{actionStatus:st,errorCode:at,errorDisplay:Ft,errorInfo:Ht}}})}({From_Account:v,ProfileItem:O});const X=ea.getUserProfile(v);let rA;rA=X?Object.assign(Object.assign({},X),G):ha.createProfile(v,O);const DA=!vg(X,rA,["lastUpdatedTime"]);return rA.lastUpdatedTime=Date.now(),ea.getUserProfileMap().set(v,rA),DA&&this._emitProfileUpdated(rA),{code:0,data:rA,successLog:{message:`profileArray: ${Se.utils.safeStringify(O)}`}}}catch(z){const{errorCode:X,errorInfo:rA}=z;throw new rs({functionName:"updateMyProfile",code:X,message:rA,moreMessage:`params: ${Se.utils.safeStringify(B)}`})}})}updateMyNickAndAvatar(B){return mA(this,void 0,void 0,function*(){const v=jn(),G=Date.now(),O=ea.getUserProfile(v);let z={};z=O?Object.assign(O,B):ha.createProfile(v,B),z.lastUpdatedTime=G,ea.getUserProfileMap().set(v,z)})}_onProfileDataModify(B){const v=function(z){const{Profile_Account:X,PushType:rA,ProfileList:DA}=z;return{userId:X,pushType:rA,profileList:ha.parseProfileList(DA)}}(B.ProfileDataMod[0]);if(cl(v))return;const{isProfileUpdated:G,profile:O}=this._handleProfileModified(v);G&&this._emitProfileUpdated(O)}_emitProfileUpdated(B){Se.notificationCenter.emitInnerEvent(Ei.PROFILE_UPDATE,{name:Ei.PROFILE_UPDATE,data:[B]}),Se.notificationCenter.emitOuterEvent(Dn.PROFILE_UPDATED,{name:Dn.PROFILE_UPDATED,data:[B]}),$g.updateConversation(`C2C${B?.userID}`,{userProfile:B})}_dispose(){const{notificationCenter:B}=Se;B.unSubscribeInnerEvent(Ei.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,B.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),B.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(B){const{userId:v,profileList:G}=B,O=ea.getUserProfile(v);if(!(jn()===v||Ba(v)&&O))return{isProfileUpdated:!1,profile:null};const z=ha.normalizeProfileFields(G),X=Object.keys(z).some(JA=>JA===lr?this._isCustomFieldChanged(O.profileCustomField,z.profileCustomField):O[JA]!==z[JA]);if(!X)return{isProfileUpdated:!1,profile:O};const rA=Date.now(),DA=Object.prototype.hasOwnProperty.call(z,lr)?this._mergeProfileCustomField(O.profileCustomField,z.profileCustomField):O.profileCustomField,GA=Object.assign(Object.assign(Object.assign({},O),z),{profileCustomField:DA,lastUpdatedTime:rA});return ea.getUserProfileMap().set(v,GA),{isProfileUpdated:X,profile:GA}}_filterRequestAndCacheUsers(B){const v=[],G=[];return B.forEach(O=>{const z=ea.getUserProfileMap().has(O);Ba(O)&&z?G.push(ea.getUserProfile(O)):this._isStrangerAndProfileValid(O)?G.push(this._strangerProfileMap.get(O)):v.push(O)}),{userIdListToRequest:v,profileFromCache:G}}_handleProfileFormResponse(B){const{userProfile:v}=B;if(!Array.isArray(v))return[];const G=v.filter(z=>z.userId!=="@TLS#NOT_FOUND"&&z.userId!==""&&!cl(z.profileItem)),O=Date.now();return G.map(z=>{const X=ha.createProfile(z.userId,z.profileItem);return X.lastUpdatedTime=O,X})}_isStrangerAndProfileValid(B){var v;if(!Ba(B)){const{lastUpdatedTime:G=0}=this._strangerProfileMap.get(B)||{},O=((v=Se.store.get("cloudConfig"))===null||v===void 0?void 0:v.stranger_profile_expiration_time)||6e5;return Date.now()-G<=O}return!1}_chunkUserIDList(B,v){return Array.from({length:Math.ceil(B.length/v)},(G,O)=>B.slice(O*v,(O+1)*v))}_batchFetchUserProfiles(B){return mA(this,void 0,void 0,function*(){const v=[],G=[];let O={};return this._chunkUserIDList(B,100).forEach(z=>{v.push(ou(z))}),(yield Promise.allSettled(v)).forEach(z=>{if(z.status==="fulfilled"){const X=z.value,rA=this._handleProfileFormResponse(X);C(rA)&&G.push(...rA)}else if(z.status==="rejected"){const{code:X,message:rA}=z.reason||{};O={errorCode:X,message:rA}}}),{data:G,error:O}})}_isCustomFieldChanged(B=[],v=[]){if(!C(v)||v.length===0)return!1;if(!C(B)||B.length===0)return!0;const G=new Map(B.map(O=>[O.key,O.value]));return v.some(O=>G.get(O.key)!==O.value)}_mergeProfileCustomField(B=[],v=[]){const G=C(B)?B.map(O=>Object.assign({},O)):[];return C(v)&&v.length!==0&&v.forEach(({key:O,value:z})=>{const X=G.find(rA=>rA.key===O);X?X.value=z:G.push({key:O,value:z})}),G}_reset(){ea.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const su=new Map,xE=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let p=0,B=xE.length;p>(-2*z&6)):0)O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(O);try{return decodeURIComponent(escape(v))}catch(G){return console.warn(G),""}}const{isEmpty:nu}=Se.utils,{generateProtocolData:xt}=Se.common;function qu(p){return mA(this,void 0,void 0,function*(){const B="im_open_status.ws_get_user_status",v=xt({servcmd:B,data:{To_Account:p}}),G=`${v.head.seq}${B}`,O=yield Se.channel.sendPacket(v,{requestId:G});if(O)return function(z){const{ErrorCode:X,ErrorInfo:rA,ErrorList:DA=[],UserStatusList:GA=[]}=z,JA=GA.map(he=>{const{To_Account:Ze,Status:st,CustomStatus:at,Detail:Ft=[]}=he;return{userID:Ze,statusType:st,customStatus:Jr(at),onlineDevices:Ku(Ft)}}),ne=DA.map(he=>{const{To_Account:Ze,Invalid_Account:st,ErrorCode:at,ErrorInfo:Ft}=he;return{userID:nu(st)?Ze:st,code:at,message:Ft}});return{errorCode:X,errorInfo:rA,successUserList:JA,failureUserList:ne}}(O)})}function Ku(p){const B=[];return p?.forEach(v=>{const{Platform:G,Status:O}=v;O==="Online"&&B.push(G)}),B}class SC{constructor(){this._customStatus=""}init(){const{notificationCenter:B}=Se;js.getInstance().registerApi({apiName:"getUserStatus",context:this}),js.getInstance().registerApi({apiName:"setSelfStatus",context:this}),js.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),js.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),tn.getInstance().registerWorkflowStep(gr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Jt.USER_STATUS_UPDATE,this._onReOnline,this),B.subscribeInnerEvent(Ei.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.subscribeInnerEvent(Ei.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ei.DESTROY,this._dispose,this)}setSelfStatus(B){return mA(this,void 0,void 0,function*(){const v=jn(),{customStatus:G}=B;try{return yield function(O){return mA(this,void 0,void 0,function*(){const z="im_open_status.ws_set_custom_status",X=xt({servcmd:z,data:{CustomStatus:O}}),rA=`${X.head.seq}${z}`,DA=yield Se.channel.sendPacket(X,{requestId:rA});if(DA){const{ErrorCode:GA,ErrorInfo:JA}=DA;return{errorCode:GA,errorInfo:JA}}})}(G),this._customStatus=G,{code:0,data:{userID:v,statusType:ic,customStatus:G},successLog:{message:`customStatus: ${G}`}}}catch(O){const{errorCode:z,errorInfo:X}=O;throw new rs({functionName:"setSelfStatus",code:z,message:X})}})}getUserStatus(B){return mA(this,void 0,void 0,function*(){const{userIDList:v=[]}=B;if(this._isOnlyMeInArray(v))return this._getMyStatus();const G=yield this._getUserStatus(v);return Object.assign(Object.assign({},G),{successLog:{message:`userIDList length: ${v.length}`}})})}setCustomStatus(B){const v=Jr(B);this._customStatus=v}subscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{const{userIDList:v=[]}=B;this._checkBusinessCapabilityBits("subscribeUserStatus");const G=this._getMaxUserCount("subscribe"),O=this._sliceUserIDList(v,G),z=yield function(rA){return mA(this,void 0,void 0,function*(){const{channel:DA}=Se,GA="im_open_status.ws_status_subscribe",JA=xt({servcmd:GA,data:{To_Account:rA}}),ne=`${JA.head.seq}${GA}`;return yield DA.sendPacket(JA,{requestId:ne})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${v.length} failCount: ${X.length}`}}}catch(v){const{errorCode:G}=v;throw new rs({functionName:"subscribeUserStatus",code:G})}})}unsubscribeUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:v=[]}=B,G=this._getMaxUserCount("unsubscribe"),O=this._sliceUserIDList(v,G),z=yield function(rA){return mA(this,void 0,void 0,function*(){const{channel:DA}=Se,GA="im_open_status.ws_status_unsubscribe";let JA={};JA=rA.length===0?{UnsubscribeAll:1}:{To_Account:rA};const ne=xt({servcmd:GA,data:JA}),he=`${ne.head.seq}${GA}`;return yield DA.sendPacket(ne,{requestId:he})})}(O),X=this._parseResponse(z);return{code:0,data:{failureUserList:X},successLog:{message:`userID length:${v.length} failCount: ${X.length}`}}}catch(v){const{errorCode:G}=v;throw new rs({functionName:"unsubscribeUserStatus",code:G})}})}_onUserStatusUpdate(B){const{UserStatusList:v=[]}=B||{},G=v.map(O=>{const{To_Account:z,Status:X,CustomStatus:rA,Platform:DA}=O,GA={userID:z,statusType:X,customStatus:Jr(rA)};return DA&&(GA.onlineDevices=DA),GA});this._emitUserStatusUpdatedEvent(G)}_onReOnline(B){const v=Jr(B.data.customStatus);if(this._customStatus===v)return;this._customStatus=v;const G={userID:jn(),statusType:ic,customStatus:v};this._emitUserStatusUpdatedEvent(G)}_emitUserStatusUpdatedEvent(B){Se.notificationCenter.emitOuterEvent(Dn.USER_STATUS_UPDATED,{name:Dn.USER_STATUS_UPDATED,data:B})}_sliceUserIDList(B,v){return B.slice(0,v)}_parseResponse(B){const{ErrorList:v=[]}=B;return v.map(G=>{const{To_Account:O,Invalid_Account:z,ErrorCode:X,ErrorInfo:rA}=G;return{userID:Se.utils.isEmpty(z)?O:z,code:X,message:rA}})}_checkBusinessCapabilityBits(B){if(!Se.store.get("commercialConfig").get(_r))throw new rs({functionName:B,code:Uo.NO_USE,replacement1:B})}_getMaxUserCount(B){const v=Se.store.get("cloudConfig")||{},G={query:{key:"status_query_count",default:500},subscribe:{key:"status_sub_count",default:100},unsubscribe:{key:"status_unsub_count",default:100}},{key:O,default:z}=G[B],X=v[O]||z;return parseInt(X,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:jn(),statusType:ic,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(B){return mA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const v=this._getMaxUserCount("query"),G=this._sliceUserIDList(B,v),O=yield qu(G),{successUserList:z,failureUserList:X}=O||{};return{code:0,data:{successUserList:z,failureUserList:X}}}catch(v){const{errorCode:G}=v;throw new rs({functionName:"getUserStatus",code:G})}})}_isOnlyMeInArray(B){const v=jn();return B.length===1&&B.indexOf(v)>-1}_dispose(){const{notificationCenter:B}=Se;B.unSubscribeInnerEvent(Ei.MESSAGE_PUSH,B.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),B.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this),B.unSubscribeInnerEvent(Ei.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const K={getUserProfile:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},updateMyProfile:{nick:{required:!1,rules:["string"],allowEmpty:!0},avatar:{required:!1,rules:["string"],allowEmpty:!0},gender:{required:!1,rules:["string"],allowEmpty:!0},selfSignature:{required:!1,rules:["string"],allowEmpty:!0},allowType:{required:!1,rules:["string"],allowEmpty:!0},birthday:{required:!1,rules:["number"],allowEmpty:!1},language:{required:!1,rules:["string"],allowEmpty:!0},messageSettings:{required:!1,rules:["string"],allowEmpty:!0},adminForbidType:{required:!1,rules:["string"],allowEmpty:!0},level:{required:!1,rules:["number"],allowEmpty:!1},role:{required:!1,rules:["number"],allowEmpty:!0},profileCustomField:{required:!1,rules:["array"],allowEmpty:!0,customValidator:function(p){for(const B of p){if(typeof B!="object")return"Each item in profileCustomField must be an object";if(typeof B?.key!="string")return"Each item.key in profileCustomField must be a string";if(!B?.key.startsWith(Ig))return'Each item.key in profileCustomField must start with "Tag_Profile_Custom"'}return!0}}},setSelfStatus:{customStatus:{required:!0,rules:["string"],allowEmpty:!0}},getUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},subscribeUserStatus:{userIDList:{required:!0,rules:["array"],allowEmpty:!1}},unsubscribeUserStatus:{userIDList:{required:!1,rules:["array"],allowEmpty:!0}}},U={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class sA{constructor(){this.userProfile=new PE,this.userStatus=new SC,this.userProfile.init(),this.userStatus.init(),Mc({auth:U,params:K})}}function b(p){const B=[];if(!c(p))return B;const v=p.length;if(v===0)return B;for(let G=v-1;G>=0;G--)p[G]==="1"&&B.push(2**(v-G-1));return B}var x,iA,uA;(function(p){p.NOT_START="notStart",p.PENDING="pending",p.RESOLVED="resolved",p.REJECTED="rejected"})(x||(x={})),function(p){p[p.C2C=1]="C2C",p[p.GROUP=2]="GROUP"}(iA||(iA={})),function(p){p[p.C2C=8]="C2C",p[p.GROUP=2]="GROUP"}(uA||(uA={}));class _A{constructor(){this._name="SyncConversationHandler",this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:B}=Se;tn.getInstance().registerWorkflowStep(gr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Jt.CONVERSATION_RECOVER,this._syncConversationList,this),tn.getInstance().registerWorkflowStep(gr.SYNC_SERVER_INFO_AFTER_LOGIN,Jt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),B.subscribeInnerEvent(Ei.LOGOUT,this._reset,this),B.subscribeInnerEvent(Ei.DESTROY,this._dispose,this),Se.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===x.RESOLVED}_syncConversationListAfterLogin(){return mA(this,void 0,void 0,function*(){return this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0,this._syncConversationList()})}_syncConversationList(){return mA(this,void 0,void 0,function*(){const{ssoLog:B,utils:{safeStringify:v}}=Se;B.debug("_syncConversationList","start");try{const G=yield this._pagingGetConversationList(!0);this._pagingStatus=x.RESOLVED;const{conversationList:O=[]}=G||{};return B.info("_syncConversationList",`success count:${O.length}`),G}catch(G){const O=new rs(G);B.error("_syncConversationList",`fail ${v(G)}`,{error:O})}})}_pagingGetConversationList(B){return mA(this,void 0,void 0,function*(){try{const v=[];this._pagingStatus=x.PENDING;const G=yield function(ne){return mA(this,void 0,void 0,function*(){const{fromAccount:he,pagingTimeStamp:Ze,pagingStartIndex:st,pagingPinnedTimeStamp:at,pagingPinnedStartIndex:Ft}=ne;return Zg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:he,StartIndex:st,TimeStamp:Ze,TopStartIndex:Ft,TopTimeStamp:at}})})}({fromAccount:jn(),pagingTimeStamp:B?this._pagingTimeStamp:0,pagingStartIndex:B?this._pagingStartIndex:0,pagingPinnedTimeStamp:B?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:B?this._pagingPinnedStartIndex:0}),{CompleteFlag:O,SessionItem:z=[],TimeStamp:X,StartIndex:rA,TopTimeStamp:DA,TopStartIndex:GA}=G||{};let JA=[];if(O===1&&(this._pagingStatus=x.RESOLVED),z.length>0&&(JA=this._getConversationOptions(z),v.push(...JA)),Se.notificationCenter.emitInnerEvent(Ei.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:JA}),this._pagingTimeStamp=X,this._pagingStartIndex=rA,this._pagingPinnedTimeStamp=DA,this._pagingPinnedStartIndex=GA,O!==1){const{conversationList:ne}=yield this._pagingGetConversationList(B);v.push(...ne)}return{conversationList:v}}catch(v){throw v}})}_getConversationOptions(B){const{utils:{isUndefined:v}}=Se,G=this._convertConversationKey(B);return this._filterValidConversations(G).map(O=>(v(O.lastMsg)&&(O.lastMsg={elements:[]}),O.type===iA.C2C?this._assembleC2COption(O):this._assembleGroupOption(O)))}_filterValidConversations(B){return B.filter(({type:v,userID:G})=>v===iA.C2C&&!function(O){let z;return O.startsWith(Bs.CONV_C2C)&&(z=O.replace(Bs.CONV_C2C,"")),z==="@TLS#ERROR"||z==="@TLS#NOT_FOUND"}(G)||v===2)}_assembleC2COption(B){var v,G,O,z,X,rA,DA,GA;const JA=this._createUserprofile(B);return{conversationID:`${Bs.CONV_C2C}${B.userID}`,type:Bs.CONV_C2C,lastMessage:{lastTime:B.time,lastSequence:B.sequence,fromAccount:B.lastC2CMsgFromAccount,type:!((v=B.lastMsg)===null||v===void 0)&&v.elements[0]?(G=B.lastMsg)===null||G===void 0?void 0:G.elements[0].type:null,payload:!((O=B.lastMsg)===null||O===void 0)&&O.elements[0]?this._amendLayersOverLimitProp(B.lastMsg.elements[0].content):null,cloudCustomData:((rA=(X=(z=B.lastMsg)===null||z===void 0?void 0:z.elements)===null||X===void 0?void 0:X[0])===null||rA===void 0?void 0:rA.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(B),revoker:((GA=(DA=B.lastMsg)===null||DA===void 0?void 0:DA.revokerInfo)===null||GA===void 0?void 0:GA.revoker)||null},unreadCount:0,userProfile:JA,peerReadTime:B.peerReadTime,isPinned:B.isPinned===1,customData:B.customMark||"",markList:b(B.standardMark),conversationGroupList:[],remark:B.friendRemark||"",messageRemindType:this._transMsgRemindType(B.messageRemindType)}}_createUserprofile(B){var v;const{userID:G,nick:O,peerAvatar:z}=B,X=[{tag:"Tag_Profile_IM_Nick",value:O},{tag:"Tag_Profile_IM_Image",value:z}];return(v=Se.user.userProfile)===null||v===void 0?void 0:v.createProfile(G,X)}_computeIsPeerRead(B){const v=jn(),{lastC2CMsgFromAccount:G,time:O,c2cPeerReadTime:z}=B;return G===v&&O<=z}_assembleGroupOption(B){var v,G,O,z,X;return{conversationID:`${Bs.CONV_GROUP}${B.groupID}`,type:Bs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:B.time,lastSequence:B.sequence,fromAccount:B.msgGroupFromAccount},this._patchTypeAndPayload(B)),{cloudCustomData:((O=(G=(v=B.lastMsg)===null||v===void 0?void 0:v.elements)===null||G===void 0?void 0:G[0])===null||O===void 0?void 0:O.cloudCustomData)||"",isRevoked:B.lastMessageFlag===uA.GROUP,onlineOnlyFlag:!1,nick:B.msgGroupFromNickName||"",nameCard:B.msgGroupFromCardName||"",revoker:((X=(z=B.lastMsg)===null||z===void 0?void 0:z.revokerInfo)===null||X===void 0?void 0:X.revoker)||null}),groupProfile:{groupID:B.groupID,name:B.groupNick,avatar:B.groupImage,type:B.groupType,nextMessageSeq:B.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(B),peerReadTime:0,isPinned:B.isPinned===1,version:0,customData:B.customMark||"",markList:b(B.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(B.messageRemindType),subType:B.groupType}}_convertConversationKey(B){return B.map(v=>({type:v.Type,userID:v.To_Account,nick:v.C2cNick,peerAvatar:v.C2cImage,time:v.MsgTimeStamp,sequence:v.MsgSeq,lastC2CMsgFromAccount:v.LastC2cMsgFrom_Account,lastMsg:this._convertLastMsgKey(v.LastMsg),lastMessageFlag:v.LastMsgFlags,c2cPeerReadTime:v.C2cPeerReadTime,peerReadTime:v.C2cPeerReadTime,friendRemark:v.C2cRemark,isPinned:v.TopFlags,standardMark:v.StandardMark,customMark:v.CustomMark,messageRemindType:v.MsgRecvOption,groupID:v.ToAccount,groupNick:v.GroupNick,groupImage:v.GroupImage,groupType:v.GroupType,nextMessageSeq:v.GroupNextMsgSeq,msgGroupFromAccount:v.MsgGroupFrom_Account,msgGroupFromNickName:v.MsgGroupFromNickName,msgGroupFromCardName:v.MsgGroupFromCardName,unreadCount:v.UnreadMsgCount,noUnreadCount:v.GroupIgnoredUnreadSeqCount}))}_convertLastMsgKey(B){var v,G,O;const{utils:{isEmpty:z}}=Se;if(z(B))return null;let X="",rA=null;if(!z(B.GroupTips)){const{From_Account:DA,GroupName:GA}=((v=B.GroupTips)===null||v===void 0?void 0:v.GroupInfo)||{};X=Bs.MSG_GRP_TIP,rA=Object.assign(Object.assign({},this._parseContent(X,B.GroupTips.MsgBody)),{groupProfile:{from:DA,groupName:GA}})}return B.MsgBody&&(X=(G=B.MsgBody[0])===null||G===void 0?void 0:G.MsgType,rA=this._parseContent(X,B.MsgBody[0])),{event:B.Event,elements:[{type:X,content:rA,cloudCustomData:B.CloudCustomData}],revokerInfo:{revoker:(O=B.RevokerInfo)===null||O===void 0?void 0:O.Revoker_Account}}}_parseContent(B,v){var G;if(!v)return v;const O=Se.message.messageFactory.getElementClass(B);return O?(G=O.parseServerPushElement(v))===null||G===void 0?void 0:G.content:v}_amendLayersOverLimitProp(B){const{LayersOverLimit:v}=B;return So(B,["LayersOverLimit"]).layersOverLimit=v===1,B}_transMsgRemindType(B){let v="";return B===0?v=Bs.MSG_REMIND_ACPT_AND_NOTE:B===1?v=Bs.MSG_REMIND_DISCARD:B===2?v=Bs.MSG_REMIND_ACPT_NOT_NOTE:B===3&&(v=Bs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),v}_patchTypeAndPayload(B){var v;const{utils:{isUndefined:G}}=Se,{event:O,elements:z=[]}=B.lastMsg||{};return G(O)?{type:z[0]?z[0].type:null,payload:z[0]?this._amendLayersOverLimitProp(z[0].content):null}:{type:Bs.MSG_GRP_TIP,payload:((v=z?.[0])===null||v===void 0?void 0:v.content)||{}}}_computeGroupUnreadCount(B){const{unreadCount:v=0,noUnreadCount:G=0}=B,O=v-G;return O>0?O:0}_reset(){this._pagingStatus=x.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:B}=Se;B.unSubscribeInnerEvent(Ei.LOGOUT,this._reset,this),B.unSubscribeInnerEvent(Ei.DESTROY,this._dispose,this)}}class ee{constructor(){this.syncConversationHandler=new _A,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Xr}`);var fe={create:function(p){var B,v;const{SDKAppID:G,testEnv:O=!1,devMode:z=!1,unlimitedAVChatRoom:X=!1,scene:rA="",oversea:DA=!1,instance:GA,disableIndependentDomain:JA=!1,proxyServer:ne=""}=p;let he=G;if(!function(st){if(typeof st=="number")return!0;const at=Number(st);return!Number.isNaN(at)}(he))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(he=Number(he),ws.has(he))return ws.get(he);let Ze=null;if(GA)Ze=GA,Ze._workflowManager&&tn.setInstance(Ze._workflowManager),Ze._pluginManager&&Ze._pluginManager.installBuiltInPlugin(Br),GA.isReady()&&((v=(B=tn.getInstance()).executeWorkflow)===null||v===void 0||v.call(B,gr.SYNC_SERVER_INFO_AFTER_LOGIN));else{const st=function(){function Xi(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${Xi()+Xi()}${Xi()}${Xi()}${Xi()}${Xi()}${Xi()}${Xi()}`}();Se.init({sdkAppId:he,instanceId:st,testEnv:O,devMode:z,unlimitedAVChatRoom:X,disableIndependentDomain:JA,scene:rA,oversea:DA,sdkEdition:Pu,version:Xr,proxyServer:ne}),tn.getInstance().init(),Se.message=new gl,Se.user=new sA,Se.login=new Ac,Se.conversation=new ee,Po.getInstance().installBuiltInPlugin(Br),Ze=js.getInstance().exposeApiForClient(),Ze._workflowManager=tn.getInstance(),Ze._pluginManager=Po.getInstance();const{utils:{IS_WORKER_AVAILABLE:at,USER_AGENT:Ft,getPlatformType:Ht,isIOSWebView:Pi}}=Se,co=`instanceID:${st} SDKAppID:${G} platform:${VA} host:${Ht()} isIOSWebView:${Pi} workerAvailable:${at} UserAgent:${Ft}`;Se.ssoLog.info("sdkConstruct",co)}return ws.set(he,Ze),Ze},TSignaling:ro,EVENT:Dn,VERSION:Xr,TYPES:Bs};return fe})}(EY)),EY.exports}var UL={exports:{}},dY={exports:{}},caA=dY.exports,BZ;function laA(){return BZ||(BZ=1,function(t,i){(function(n,c){t.exports=c()})(caA,function(){function n(A,e){return e.forEach(function(o){o&&typeof o!="string"&&!Array.isArray(o)&&Object.keys(o).forEach(function(a){if(a!=="default"&&!(a in A)){var l=Object.getOwnPropertyDescriptor(o,a);Object.defineProperty(A,a,l.get?l:{enumerable:!0,get:function(){return o[a]}})}})}),Object.freeze(A)}var c=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof mg<"u"?mg:typeof self<"u"?self:{};function I(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var C=function(A){return A&&A.Math===Math&&A},f=C(typeof globalThis=="object"&&globalThis)||C(typeof window=="object"&&window)||C(typeof self=="object"&&self)||C(typeof c=="object"&&c)||C(typeof c=="object"&&c)||function(){return this}()||Function("return this")(),w={},_=function(A){try{return!!A()}catch{return!0}},N=!_(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),L=!_(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),q=L,lA=Function.prototype.call,tA=q?lA.bind(lA):function(){return lA.apply(lA,arguments)},BA={},IA={}.propertyIsEnumerable,gA=Object.getOwnPropertyDescriptor,RA=gA&&!IA.call({1:2},1);BA.f=RA?function(A){var e=gA(this,A);return!!e&&e.enumerable}:IA;var HA,ZA,KA=function(A,e){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:e}},me=L,ae=Function.prototype,gt=ae.call,dt=me&&ae.bind.bind(gt,gt),We=me?dt:function(A){return function(){return gt.apply(A,arguments)}},lt=We,wt=lt({}.toString),ct=lt("".slice),ce=function(A){return ct(wt(A),8,-1)},Ve=_,Dt=ce,ti=Object,Pt=We("".split),oi=Ve(function(){return!ti("z").propertyIsEnumerable(0)})?function(A){return Dt(A)==="String"?Pt(A,""):ti(A)}:ti,Ni=function(A){return A==null},Co=Ni,to=TypeError,so=function(A){if(Co(A))throw new to("Can't call method on "+A);return A},ks=oi,Gi=so,As=function(A){return ks(Gi(A))},Lo=typeof document=="object"&&document.all,$i=Lo===void 0&&Lo!==void 0?function(A){return typeof A=="function"||A===Lo}:function(A){return typeof A=="function"},zt=$i,Ao=function(A){return typeof A=="object"?A!==null:zt(A)},Ri=f,Es=$i,VA=function(A,e){return arguments.length<2?(o=Ri[A],Es(o)?o:void 0):Ri[A]&&Ri[A][e];var o},Ee=We({}.isPrototypeOf),Je=f.navigator,Ut=Je&&Je.userAgent,ot=Ut?String(Ut):"",ut=f,$t=ot,Zt=ut.process,Ge=ut.Deno,Xe=Zt&&Zt.versions||Ge&&Ge.version,se=Xe&&Xe.v8;se&&(ZA=(HA=se.split("."))[0]>0&&HA[0]<4?1:+(HA[0]+HA[1])),!ZA&&$t&&(!(HA=$t.match(/Edge\/(\d+)/))||HA[1]>=74)&&(HA=$t.match(/Chrome\/(\d+)/))&&(ZA=+HA[1]);var ve=ZA,pt=ve,mo=_,No=f.String,no=!!Object.getOwnPropertySymbols&&!mo(function(){var A=Symbol("symbol detection");return!No(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&pt&&pt<41}),Go=no&&!Symbol.sham&&typeof Symbol.iterator=="symbol",An=VA,rn=$i,ds=Ee,an=Object,So=Go?function(A){return typeof A=="symbol"}:function(A){var e=An("Symbol");return rn(e)&&ds(e.prototype,an(A))},mA=String,qn=function(A){try{return mA(A)}catch{return"Object"}},mr=$i,Cs=qn,Zr=TypeError,Yi=function(A){if(mr(A))return A;throw new Zr(Cs(A)+" is not a function")},Rs=Yi,rr=Ni,en=function(A,e){var o=A[e];return rr(o)?void 0:Rs(o)},wn=tA,jt=$i,yg=Ao,Pn=TypeError,bn={exports:{}},Js=f,fr=Object.defineProperty,xn=function(A,e){try{fr(Js,A,{value:e,configurable:!0,writable:!0})}catch{Js[A]=e}return e},yr=f,fo=xn,gn="__core-js_shared__",Ml=bn.exports=yr[gn]||fo(gn,{});(Ml.versions||(Ml.versions=[])).push({version:"3.47.0",mode:"global",copyright:"© 2014-2025 Denis Pushkarev (zloirock.ru), 2025 CoreJS Company (core-js.io)",license:"https://github.com/zloirock/core-js/blob/v3.47.0/LICENSE",source:"https://github.com/zloirock/core-js"});var cn=bn.exports,Dr=cn,Us=function(A,e){return Dr[A]||(Dr[A]=e||{})},Jc=so,fs=Object,as=function(A){return fs(Jc(A))},wu=as,Wa=We({}.hasOwnProperty),hs=Object.hasOwn||function(A,e){return Wa(wu(A),e)},sg=We,qI=0,es=Math.random(),eo=sg(1.1.toString),pc=function(A){return"Symbol("+(A===void 0?"":A)+")_"+eo(++qI+es,36)},ng=Us,Dg=hs,ua=pc,bo=no,Xr=Go,To=f.Symbol,Hc=ng("wks"),Kn=Xr?To.for||To:To&&To.withoutSetter||ua,Hs=function(A){return Dg(Hc,A)||(Hc[A]=bo&&Dg(To,A)?To[A]:Kn("Symbol."+A)),Hc[A]},Sg=tA,mc=Ao,fn=So,Ga=en,In=function(A,e){var o,a;if(e==="string"&&jt(o=A.toString)&&!yg(a=wn(o,A))||jt(o=A.valueOf)&&!yg(a=wn(o,A))||e!=="string"&&jt(o=A.toString)&&!yg(a=wn(o,A)))return a;throw new Pn("Can't convert object to primitive value")},ys=TypeError,Ea=Hs("toPrimitive"),yn=function(A,e){if(!mc(A)||fn(A))return A;var o,a=Ga(A,Ea);if(a){if(e===void 0&&(e="default"),o=Sg(a,A,e),!mc(o)||fn(o))return o;throw new ys("Can't convert object to primitive value")}return e===void 0&&(e="number"),In(A,e)},ba=yn,Sa=So,$=function(A){var e=ba(A,"string");return Sa(e)?e:e+""},j=Ao,vA=f.document,jA=j(vA)&&j(vA.createElement),oe=function(A){return jA?vA.createElement(A):{}},ye=oe,He=!N&&!_(function(){return Object.defineProperty(ye("div"),"a",{get:function(){return 7}}).a!==7}),Pe=N,rt=tA,ht=BA,_t=KA,Vt=As,ui=$,It=hs,Yt=He,qi=Object.getOwnPropertyDescriptor;w.f=Pe?qi:function(A,e){if(A=Vt(A),e=ui(e),Yt)try{return qi(A,e)}catch{}if(It(A,e))return _t(!rt(ht.f,A,e),A[e])};var Wi={},qs=N&&_(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),vi=Ao,zo=String,Mg=TypeError,ar=function(A){if(vi(A))return A;throw new Mg(zo(A)+" is not an object")},Sr=N,Yn=He,vl=qs,Ks=ar,gI=$,Wg=TypeError,fc=Object.defineProperty,_u=Object.getOwnPropertyDescriptor,Ma="enumerable",Rl="configurable",Se="writable";Wi.f=Sr?vl?function(A,e,o){if(Ks(A),e=gI(e),Ks(o),typeof A=="function"&&e==="prototype"&&"value"in o&&Se in o&&!o[Se]){var a=_u(A,e);a&&a[Se]&&(A[e]=o.value,o={configurable:Rl in o?o[Rl]:a[Rl],enumerable:Ma in o?o[Ma]:a[Ma],writable:!1})}return fc(A,e,o)}:fc:function(A,e,o){if(Ks(A),e=gI(e),Ks(o),Yn)try{return fc(A,e,o)}catch{}if("get"in o||"set"in o)throw new Wg("Accessors not supported");return"value"in o&&(A[e]=o.value),A};var De=Wi,vg=KA,rg=N?function(A,e,o){return De.f(A,e,vg(1,o))}:function(A,e,o){return A[e]=o,A},Rg={exports:{}},Dn=N,Mr=hs,Ei=Function.prototype,ro=Dn&&Object.getOwnPropertyDescriptor,qc=Mr(Ei,"name"),zg={PROPER:qc&&function(){}.name==="something",CONFIGURABLE:qc&&(!Dn||Dn&&ro(Ei,"name").configurable)},wg=$i,Yr=cn,yc=We(Function.toString);wg(Yr.inspectSource)||(Yr.inspectSource=function(A){return yc(A)});var Kc,ag,Tu,DE=Yr.inspectSource,_g=$i,ka=f.WeakMap,Dc=_g(ka)&&/native code/.test(String(ka)),SE=pc,La=Us("keys"),na=function(A){return La[A]||(La[A]=SE(A))},Tg={},cI=Dc,Bs=f,Uo=Ao,da=rg,gr=hs,Jt=cn,Wt=na,Ng=Tg,lI="Object already initialized",cr=Bs.TypeError,KI=Bs.WeakMap;if(cI||Jt.state){var za=Jt.state||(Jt.state=new KI);za.get=za.get,za.has=za.has,za.set=za.set,Kc=function(A,e){if(za.has(A))throw new cr(lI);return e.facade=A,za.set(A,e),e},ag=function(A){return za.get(A)||{}},Tu=function(A){return za.has(A)}}else{var ra=Wt("state");Ng[ra]=!0,Kc=function(A,e){if(gr(A,ra))throw new cr(lI);return e.facade=A,da(A,ra,e),e},ag=function(A){return gr(A,ra)?A[ra]:{}},Tu=function(A){return gr(A,ra)}}var un={set:Kc,get:ag,has:Tu,enforce:function(A){return Tu(A)?ag(A):Kc(A,{})},getterFor:function(A){return function(e){var o;if(!Uo(e)||(o=ag(e)).type!==A)throw new cr("Incompatible receiver, "+A+" required");return o}}},Sn=We,Nu=_,Gg=$i,Ua=hs,jc=N,jI=zg.CONFIGURABLE,ME=DE,II=un.enforce,Gu=un.get,wl=String,Sc=Object.defineProperty,bu=Sn("".slice),ku=Sn("".replace),_l=Sn([].join),rs=jc&&!Nu(function(){return Sc(function(){},"length",{value:8}).length!==8}),gs=String(String).split("String"),ud=Rg.exports=function(A,e,o){bu(wl(e),0,7)==="Symbol("&&(e="["+ku(wl(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(e="get "+e),o&&o.setter&&(e="set "+e),(!Ua(A,"name")||jI&&A.name!==e)&&(jc?Sc(A,"name",{value:e,configurable:!0}):A.name=e),rs&&o&&Ua(o,"arity")&&A.length!==o.arity&&Sc(A,"length",{value:o.arity});try{o&&Ua(o,"constructor")&&o.constructor?jc&&Sc(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var a=II(A);return Ua(a,"source")||(a.source=_l(gs,typeof e=="string"?e:"")),A};Function.prototype.toString=ud(function(){return Gg(this)&&Gu(this).source||ME(this)},"toString");var uI=Rg.exports,EI=$i,vE=Wi,Ed=uI,Tl=xn,vr=function(A,e,o,a){a||(a={});var l=a.enumerable,d=a.name!==void 0?a.name:e;if(EI(o)&&Ed(o,d,a),a.global)l?A[e]=o:Tl(e,o);else{try{a.unsafe?A[e]&&(l=!0):delete A[e]}catch{}l?A[e]=o:vE.f(A,e,{value:o,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return A},Mc={},Wc=Math.ceil,tn=Math.floor,ws=Math.trunc||function(A){var e=+A;return(e>0?tn:Wc)(e)},Ca=ws,$r=function(A){var e=+A;return e!=e||e===0?0:Ca(e)},zc=$r,dd=Math.max,Zg=Math.min,gg=function(A,e){var o=zc(A);return o<0?dd(o+e,0):Zg(o,e)},RE=$r,Xg=Math.min,jn=function(A){var e=RE(A);return e>0?Xg(e,9007199254740991):0},ir=jn,Fa=function(A){return ir(A.length)},Cd=As,EC=gg,Lu=Fa,WI=function(A){return function(e,o,a){var l=Cd(e),d=Lu(l);if(d===0)return!A&&-1;var h,y=EC(a,d);if(A&&o!=o){for(;d>y;)if((h=l[y++])!=h)return!0}else for(;d>y;y++)if((A||y in l)&&l[y]===o)return A||y||0;return!A&&-1}},Zc={includes:WI(!0),indexOf:WI(!1)},Xc=hs,zI=As,dI=Zc.indexOf,$c=Tg,Al=We([].push),va=function(A,e){var o,a=zI(A),l=0,d=[];for(o in a)!Xc($c,o)&&Xc(a,o)&&Al(d,o);for(;e.length>l;)Xc(a,o=e[l++])&&(~dI(d,o)||Al(d,o));return d},bg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ds=va,Wn=bg.concat("length","prototype");Mc.f=Object.getOwnPropertyNames||function(A){return Ds(A,Wn)};var vc={};vc.f=Object.getOwnPropertySymbols;var ZI=VA,XI=Mc,wE=vc,ch=ar,dC=We([].concat),lh=ZI("Reflect","ownKeys")||function(A){var e=XI.f(ch(A)),o=wE.f;return o?dC(e,o(A)):e},el=hs,kg=lh,ao=w,CC=Wi,_E=function(A,e,o){for(var a=kg(e),l=CC.f,d=ao.f,h=0;hh;)pI.f(A,o=l[h++],a[o]);return A};var Ug,ec=VA("document","documentElement"),md=ar,kE=bl,Nc=bg,eu=Tg,Io=ec,LE=oe,$a="prototype",tu="script",xu=na("IE_PROTO"),Gc=function(){},mI=function(A){return"<"+tu+">"+A+""},sl=function(A){A.write(mI("")),A.close();var e=A.parentWindow.Object;return A=null,e},nl=function(){try{Ug=new ActiveXObject("htmlfile")}catch{}nl=typeof document<"u"?document.domain&&Ug?sl(Ug):function(){var e,o=LE("iframe"),a="java"+tu+":";return o.style.display="none",Io.appendChild(o),o.src=String(a),(e=o.contentWindow.document).open(),e.write(mI("document.F=Object")),e.close(),e.F}():sl(Ug);for(var A=Nc.length;A--;)delete nl[$a][Nc[A]];return nl()};eu[xu]=!0;var xa=Object.create||function(A,e){var o;return A!==null?(Gc[$a]=md(A),o=new Gc,Gc[$a]=null,o[xu]=A):o=nl(),e===void 0?o:kE.f(o,e)},UE=Hs,aa=xa,Mn=Wi.f,kr=UE("unscopables"),rl=Array.prototype;rl[kr]===void 0&&Mn(rl,kr,{configurable:!0,value:aa(null)});var Fl=function(A){rl[kr][A]=!0},bc=Zc.includes,FE=Fl;_n({target:"Array",proto:!0,forced:_(function(){return!Array(1).includes()})},{includes:function(A){return bc(this,A,arguments.length>1?arguments[1]:void 0)}}),FE("includes");var kc,Yu,yC,iu={},Eh=!_(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),Vu=hs,fI=$i,al=as,DC=Eh,ga=na("IE_PROTO"),tc=Object,lg=tc.prototype,yI=DC?tc.getPrototypeOf:function(A){var e=al(A);if(Vu(e,ga))return e[ga];var o=e.constructor;return fI(o)&&e instanceof o?o.prototype:e instanceof tc?lg:null},OE=_,Ju=$i,Hu=Ao,DI=yI,gl=vr,Lr=Hs("iterator"),Ur=!1;[].keys&&("next"in(yC=[].keys())?(Yu=DI(DI(yC)))!==Object.prototype&&(kc=Yu):Ur=!0);var Ig=!Hu(kc)||OE(function(){var A={};return kc[Lr].call(A)!==A});Ig&&(kc={}),Ju(kc[Lr])||gl(kc,Lr,function(){return this});var lr={IteratorPrototype:kc,BUGGY_SAFARI_ITERATORS:Ur},_r=Wi.f,ic=hs,Fg=Hs("toStringTag"),Ya=function(A,e,o){A&&!o&&(A=A.prototype),A&&!ic(A,Fg)&&_r(A,Fg,{configurable:!0,value:e})},Ol=lr.IteratorPrototype,ha=xa,SI=KA,ou=Ya,Ba=iu,cl=function(){return this},PE=function(A,e,o,a){var l=e+" Iterator";return A.prototype=ha(Ol,{next:SI(+!a,o)}),ou(A,l,!1),Ba[l]=cl,A},su=We,xE=Yi,Jr=Ao,nu=function(A){return Jr(A)||A===null},xt=String,qu=TypeError,Ku=function(A,e,o){try{return su(xE(Object.getOwnPropertyDescriptor(A,e)[o]))}catch{}},SC=Ao,K=so,U=function(A){if(nu(A))return A;throw new qu("Can't set "+xt(A)+" as a prototype")},sA=Object.setPrototypeOf||("__proto__"in{}?function(){var A,e=!1,o={};try{(A=Ku(Object.prototype,"__proto__","set"))(o,[]),e=o instanceof Array}catch{}return function(a,l){return K(a),U(l),SC(a)&&(e?A(a,l):a.__proto__=l),a}}():void 0),b=_n,x=tA,iA=$i,uA=PE,_A=yI,ee=sA,fe=Ya,p=rg,B=vr,v=iu,G=zg.PROPER,O=zg.CONFIGURABLE,z=lr.IteratorPrototype,X=lr.BUGGY_SAFARI_ITERATORS,rA=Hs("iterator"),DA="keys",GA="values",JA="entries",ne=function(){return this},he=function(A,e,o,a,l,d,h){uA(o,e,a);var y,S,k,V=function(qe){if(qe===l&&ie)return ie;if(!X&&qe&&qe in CA)return CA[qe];switch(qe){case DA:case GA:case JA:return function(){return new o(this,qe)}}return function(){return new o(this)}},J=e+" Iterator",cA=!1,CA=A.prototype,MA=CA[rA]||CA["@@iterator"]||l&&CA[l],ie=!X&&MA||V(l),pe=e==="Array"&&CA.entries||MA;if(pe&&(y=_A(pe.call(new A)))!==Object.prototype&&y.next&&(_A(y)!==z&&(ee?ee(y,z):iA(y[rA])||B(y,rA,ne)),fe(y,J,!0)),G&&l===GA&&MA&&MA.name!==GA&&(O?p(CA,"name",GA):(cA=!0,ie=function(){return x(MA,this)})),l)if(S={values:V(GA),keys:d?ie:V(DA),entries:V(JA)},h)for(k in S)(X||cA||!(k in CA))&&B(CA,k,S[k]);else b({target:e,proto:!0,forced:X||cA},S);return CA[rA]!==ie&&B(CA,rA,ie,{name:l}),v[e]=ie,S},Ze=function(A,e){return{value:A,done:e}},st=As,at=Fl,Ft=iu,Ht=un,Pi=Wi.f,co=he,Xi=Ze,di=N,xo="Array Iterator",ts=Ht.set,mi=Ht.getterFor(xo),zi=co(Array,"Array",function(A,e){ts(this,{type:xo,target:st(A),index:0,kind:e})},function(){var A=mi(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,Xi(void 0,!0);switch(A.kind){case"keys":return Xi(o,!1);case"values":return Xi(e[o],!1)}return Xi([o,e[o]],!1)},"values"),Ws=Ft.Arguments=Ft.Array;if(at("keys"),at("values"),at("entries"),di&&Ws.name!=="values")try{Pi(Ws,"name",{value:"values"})}catch{}var Ne=Yi,Tt=as,FA=oi,Ai=Fa,En=TypeError,ii="Reduce of empty array with no initial value",us=function(A){return function(e,o,a,l){var d=Tt(e),h=FA(d),y=Ai(d);if(Ne(o),y===0&&a<2)throw new En(ii);var S=A?y-1:0,k=A?-1:1;if(a<2)for(;;){if(S in h){l=h[S],S+=k;break}if(S+=k,A?S<0:y<=S)throw new En(ii)}for(;A?S>=0:y>S;S+=k)S in h&&(l=o(l,h[S],S,d));return l}},wi={left:us(!1),right:us(!0)},Bo=_,Bt=function(A,e){var o=[][A];return!!o&&Bo(function(){o.call(null,e||function(){return 1},1)})},mt=f,ug=ot,Ls=ce,Zi=function(A){return ug.slice(0,A.length)===A},Hr=Zi("Bun/")?"BUN":Zi("Cloudflare-Workers")?"CLOUDFLARE":Zi("Deno/")?"DENO":Zi("Node.js/")?"NODE":mt.Bun&&typeof Bun.version=="string"?"BUN":mt.Deno&&typeof Deno.version=="object"?"DENO":Ls(mt.process)==="process"?"NODE":mt.window&&mt.document?"BROWSER":"REST",oc=Hr==="NODE",os=wi.left;_n({target:"Array",proto:!0,forced:!oc&&ve>79&&ve<83||!Bt("reduce")},{reduce:function(A){var e=arguments.length;return os(this,A,e,e>1?arguments[1]:void 0)}});var ca=wi.right;_n({target:"Array",proto:!0,forced:!oc&&ve>79&&ve<83||!Bt("reduceRight")},{reduceRight:function(A){return ca(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var Qa=ce,ta=Array.isArray||function(A){return Qa(A)==="Array"},H=_n,QA=ta,yA=We([].reverse),NA=[1,2];H({target:"Array",proto:!0,forced:String(NA)===String(NA.reverse())},{reverse:function(){return QA(this)&&(this.length=this.length),yA(this)}});var XA=qn,Te=TypeError,de=We([].slice),ke=de,ue=Math.floor,Oe=function(A,e){var o=A.length;if(o<8)for(var a,l,d=1;d0;)A[l]=A[--l];l!==d++&&(A[l]=a)}else for(var h=ue(o/2),y=Oe(ke(A,0,h),e),S=Oe(ke(A,h),e),k=y.length,V=S.length,J=0,cA=0;J3)){if(Dm)return!0;if(ri)return ri<603;var A,e,o,a,l="";for(A=65;A<76;A++){switch(e=String.fromCharCode(A),A){case 66:case 69:case 70:case 72:o=3;break;case 68:case 71:o=4;break;default:o=2}for(a=0;a<47;a++)Do.push({k:e+a,v:o})}for(Do.sort(function(d,h){return h.v-d.v}),a=0;aZn(S)?1:-1}}(A)),o=Zo(l),a=0;ao||S!=S?1/0*h:h*S},CD=Math.fround||function(A){return dD(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},Yv=Array,DT=Math.abs,yd=Math.pow,ST=Math.floor,hD=Math.log,MT=Math.LN2,BD={pack:function(A,e,o){var a,l,d,h=Yv(o),y=8*o-e-1,S=(1<>1,V=e===23?yd(2,-24)-yd(2,-77):0,J=A<0||A===0&&1/A<0?1:0,cA=0;for((A=DT(A))!=A||A===1/0?(l=A!=A?1:0,a=S):(a=ST(hD(A)/MT),A*(d=yd(2,-a))<1&&(a--,d*=2),(A+=a+k>=1?V/d:V*yd(2,1-k))*d>=2&&(a++,d/=2),a+k>=S?(l=0,a=S):a+k>=1?(l=(A*d-1)*yd(2,e),a+=k):(l=A*yd(2,k-1)*yd(2,e),a=0));e>=8;)h[cA++]=255&l,l/=256,e-=8;for(a=a<0;)h[cA++]=255&a,a/=256,y-=8;return h[cA-1]|=128*J,h},unpack:function(A,e){var o,a=A.length,l=8*a-e-1,d=(1<>1,y=l-7,S=a-1,k=A[S--],V=127&k;for(k>>=7;y>0;)V=256*V+A[S--],y-=8;for(o=V&(1<<-y)-1,V>>=-y,y+=e;y>0;)o=256*o+A[S--],y-=8;if(V===0)V=1-h;else{if(V===d)return o?NaN:k?-1/0:1/0;o+=yd(2,e),V-=h}return(k?-1:1)*o*yd(2,V-e)}},vT=as,Vv=gg,RT=Fa,Jv=function(A){for(var e=vT(this),o=RT(e),a=arguments.length,l=Vv(a>1?arguments[1]:void 0,o),d=a>2?arguments[2]:void 0,h=d===void 0?o:Vv(d,o);h>l;)e[l++]=A;return e},wT=$i,_T=Ao,QD=sA,pD=function(A,e,o){var a,l;return QD&&wT(a=e.constructor)&&a!==o&&_T(l=a.prototype)&&l!==o.prototype&&QD(A,l),A},bQ=f,wm=We,_m=N,Dd=Rr,TT=rg,NT=Lg,Tm=ru,mD=_,dh=vI,GT=$r,bT=jn,Nm=Mm,Hv=CD,fD=BD,Gm=yI,qv=sA,kT=Jv,LT=de,Kv=pD,Sd=_E,bm=Ya,Md=un,YE=zg.PROPER,km=zg.CONFIGURABLE,MC="ArrayBuffer",Ch="DataView",zu="prototype",Ji="Wrong index",Lm=Md.getterFor(MC),dn=Md.getterFor(Ch),jv=Md.set,Zu=bQ[MC],zs=Zu,hh=zs&&zs[zu],xl=bQ[Ch],nc=xl&&xl[zu],VE=Object.prototype,kQ=bQ.Array,uB=bQ.RangeError,UT=wm(kT),FT=wm([].reverse),LQ=fD.pack,UQ=fD.unpack,Wv=function(A){return[255&A]},zv=function(A){return[255&A,A>>8&255]},yD=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},vC=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},EB=function(A){return LQ(Hv(A),23,4)},DD=function(A){return LQ(A,52,8)},FQ=function(A,e,o){NT(A[zu],e,{configurable:!0,get:function(){return o(this)[e]}})},vd=function(A,e,o,a){var l=dn(A),d=Nm(o),h=!!a;if(d+e>l.byteLength)throw new uB(Ji);var y=l.bytes,S=d+l.byteOffset,k=LT(y,S,S+e);return h?k:FT(k)},Rd=function(A,e,o,a,l,d){var h=dn(A),y=Nm(o),S=a(+l),k=!!d;if(y+e>h.byteLength)throw new uB(Ji);for(var V=h.bytes,J=y+h.byteOffset,cA=0;cA>24)},setUint8:function(A,e){SD(this,A,e<<24>>24)}},{unsafe:!0})}else hh=(zs=function(A){dh(this,hh);var e=Nm(A);jv(this,{type:MC,bytes:UT(kQ(e),0),byteLength:e}),_m||(this.byteLength=e,this.detached=!1)})[zu],nc=(xl=function(A,e,o){dh(this,nc),dh(A,hh);var a=Lm(A),l=a.byteLength,d=GT(e);if(d<0||d>l)throw new uB("Wrong offset");if(d+(o=o===void 0?l-d:bT(o))>l)throw new uB("Wrong length");jv(this,{type:Ch,buffer:A,byteLength:o,byteOffset:d,bytes:a.bytes}),_m||(this.buffer=A,this.byteLength=o,this.byteOffset=d)})[zu],_m&&(FQ(zs,"byteLength",Lm),FQ(xl,"buffer",dn),FQ(xl,"byteLength",dn),FQ(xl,"byteOffset",dn)),Tm(nc,{getInt8:function(A){return vd(this,1,A)[0]<<24>>24},getUint8:function(A){return vd(this,1,A)[0]},getInt16:function(A){var e=vd(this,2,A,arguments.length>1&&arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(A){var e=vd(this,2,A,arguments.length>1&&arguments[1]);return e[1]<<8|e[0]},getInt32:function(A){return vC(vd(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return vC(vd(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return UQ(vd(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return UQ(vd(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,e){Rd(this,1,A,Wv,e)},setUint8:function(A,e){Rd(this,1,A,Wv,e)},setInt16:function(A,e){Rd(this,2,A,zv,e,arguments.length>2&&arguments[2])},setUint16:function(A,e){Rd(this,2,A,zv,e,arguments.length>2&&arguments[2])},setInt32:function(A,e){Rd(this,4,A,yD,e,arguments.length>2&&arguments[2])},setUint32:function(A,e){Rd(this,4,A,yD,e,arguments.length>2&&arguments[2])},setFloat32:function(A,e){Rd(this,4,A,EB,e,arguments.length>2&&arguments[2])},setFloat64:function(A,e){Rd(this,8,A,DD,e,arguments.length>2&&arguments[2])}});bm(zs,MC),bm(xl,Ch);var Um={ArrayBuffer:zs,DataView:xl},Xv=VA,OT=Lg,Fm=N,dB=Hs("species"),Om=function(A){var e=Xv(A);Fm&&e&&!e[dB]&&OT(e,dB,{configurable:!0,get:function(){return this}})},PT=Om,MD="ArrayBuffer",vD=Um[MD];_n({global:!0,constructor:!0,forced:f[MD]!==vD},{ArrayBuffer:vD}),PT(MD);var PQ=ce,JE=We,Xu=function(A){if(PQ(A)==="Function")return JE(A)},RD=_n,Bh=Xu,Pm=_,$v=ar,xQ=gg,AR=jn,wD=Um.ArrayBuffer,vn=Um.DataView,YQ=vn.prototype,wd=Bh(wD.prototype.slice),_D=Bh(YQ.getUint8),xT=Bh(YQ.setUint8);RD({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:Pm(function(){return!new wD(2).slice(1,void 0).byteLength})},{slice:function(A,e){if(wd&&e===void 0)return wd($v(this),A);for(var o=$v(this).byteLength,a=xQ(A,o),l=xQ(e===void 0?o:e,o),d=new wD(AR(l-a)),h=new vn(this),y=new vn(d),S=0;ad;d++)if((y=qe(A[d]))&&sS(Ld,y))return y;return new NC(!1)}a=aN(A,l)}for(S=cA?A.next:a.next;!(k=sN(S,a)).done;){try{y=qe(k.value)}catch(we){nS(a,"throw",we)}if(typeof y=="object"&&y&&sS(Ld,y))return y}return new NC(!1)},aS=Hs("iterator"),gS=!1;try{var s=0,r={next:function(){return{done:!!s++}},return:function(){gS=!0}};r[aS]=function(){return this},Array.from(r,function(){throw 2})}catch{}var g=function(A,e){try{if(!e&&!gS)return!1}catch{return!1}var o=!1;try{var a={};a[aS]=function(){return{next:function(){return{done:o=!0}}}},A(a)}catch{}return o},u=RB,E=Th.CONSTRUCTOR||!g(function(A){u.all(A).then(void 0,function(){})}),m=tA,D=Yi,M=Kr,T=vB,P=rS;_n({target:"Promise",stat:!0,forced:E},{all:function(A){var e=this,o=M.f(e),a=o.resolve,l=o.reject,d=T(function(){var h=D(e.resolve),y=[],S=0,k=1;P(A,function(V){var J=S++,cA=!1;k++,m(h,e,V).then(function(CA){cA||(cA=!0,y[J]=CA,--k||a(y))},l)}),--k||a(y)});return d.error&&l(d.value),o.promise}});var W=_n,oA=Th.CONSTRUCTOR,EA=RB,wA=VA,kA=$i,xA=vr,LA=EA&&EA.prototype;if(W({target:"Promise",proto:!0,forced:oA,real:!0},{catch:function(A){return this.then(void 0,A)}}),kA(EA)){var SA=wA("Promise").prototype.catch;LA.catch!==SA&&xA(LA,"catch",SA,{unsafe:!0})}var OA=tA,qA=Yi,Ie=Kr,le=vB,bi=rS;_n({target:"Promise",stat:!0,forced:E},{race:function(A){var e=this,o=Ie.f(e),a=o.reject,l=le(function(){var d=qA(e.resolve);bi(A,function(h){OA(d,e,h).then(o.resolve,a)})});return l.error&&a(l.value),o.promise}});var ki=Kr;_n({target:"Promise",stat:!0,forced:Th.CONSTRUCTOR},{reject:function(A){var e=ki.f(this);return(0,e.reject)(A),e.promise}});var Ot=ar,Li=Ao,cs=Kr,Re=function(A,e){if(Ot(A),Li(e)&&e.constructor===A)return e;var o=cs.f(A);return(0,o.resolve)(e),o.promise},St=_n,UA=Th.CONSTRUCTOR,ai=Re;VA("Promise"),St({target:"Promise",stat:!0,forced:UA},{resolve:function(A){return ai(this,A)}});var _s=_n,Ui=RB,Or=_,Vi=VA,Ir=$i,Nt=oR,Gt=Re,iE=vr,ln=Ui&&Ui.prototype;if(_s({target:"Promise",proto:!0,real:!0,forced:!!Ui&&Or(function(){ln.finally.call({then:function(){}},function(){})})},{finally:function(A){var e=Nt(this,Vi("Promise")),o=Ir(A);return this.then(o?function(a){return Gt(e,A()).then(function(){return a})}:A,o?function(a){return Gt(e,A()).then(function(){throw a})}:A)}}),Ir(Ui)){var Qo=Vi("Promise").prototype.finally;ln.finally!==Qo&&iE(ln,"finally",Qo,{unsafe:!0})}var Il=Ao,GC=ce,Tr=Hs("match"),xg=function(A){var e;return Il(A)&&((e=A[Tr])!==void 0?!!e:GC(A)==="RegExp")},_I=_,ac=f.RegExp,gf=!_I(function(){var A=!0;try{ac(".","d")}catch{A=!1}var e={},o="",a=A?"dgimsy":"gimsy",l=function(y,S){Object.defineProperty(e,y,{get:function(){return o+=S,!0}})},d={dotAll:"s",global:"g",ignoreCase:"i",multiline:"m",sticky:"y"};for(var h in A&&(d.hasIndices="d"),d)l(h,d[h]);return Object.getOwnPropertyDescriptor(ac.prototype,"flags").get.call(e)!==a||o!==a}),lp=ar,Va=function(){var A=lp(this),e="";return A.hasIndices&&(e+="d"),A.global&&(e+="g"),A.ignoreCase&&(e+="i"),A.multiline&&(e+="m"),A.dotAll&&(e+="s"),A.unicode&&(e+="u"),A.unicodeSets&&(e+="v"),A.sticky&&(e+="y"),e},Vl=tA,TI=hs,oE=Ee,Yg={correct:gf},dg=Va,cS=RegExp.prototype,OR=Yg.correct?function(A){return A.flags}:function(A){return Yg.correct||!oE(cS,A)||TI(A,"flags")?A.flags:Vl(dg,A)},PR=_,xR=f.RegExp,cN=PR(function(){var A=xR("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),KV=cN||PR(function(){return!xR("a","y").sticky}),gF=cN||PR(function(){var A=xR("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),Ip={BROKEN_CARET:gF,MISSED_STICKY:KV,UNSUPPORTED_Y:cN},lN=Wi.f,IN=_,uN=f.RegExp,EN=IN(function(){var A=uN(".","s");return!(A.dotAll&&A.test(` +`)&&A.flags==="s")}),cF=_,jV=f.RegExp,lF=cF(function(){var A=jV("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),cf=N,dN=f,lf=We,CN=wr,WV=pD,zV=rg,ZV=xa,XV=Mc.f,YR=Ee,IF=xg,hN=Br,uF=OR,lS=Ip,BN=function(A,e,o){o in A||lN(A,o,{configurable:!0,get:function(){return e[o]},set:function(a){e[o]=a}})},VR=vr,JR=_,$V=hs,QN=un.enforce,HR=Om,EF=EN,If=lF,AJ=Hs("match"),bB=dN.RegExp,uf=bB.prototype,eJ=dN.SyntaxError,dF=lf(uf.exec),Ef=lf("".charAt),CF=lf("".replace),pN=lf("".indexOf),mN=lf("".slice),tJ=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,sE=/a/g,kB=/a/g,hF=new bB(sE)!==sE,BF=lS.MISSED_STICKY,iJ=lS.UNSUPPORTED_Y,fN=cf&&(!hF||BF||EF||If||JR(function(){return kB[AJ]=!1,bB(sE)!==sE||bB(kB)===kB||String(bB(sE,"i"))!=="/a/i"}));if(CN("RegExp",fN)){for(var LB=function(A,e){var o,a,l,d,h,y,S=YR(uf,this),k=IF(A),V=e===void 0,J=[],cA=A;if(!S&&k&&V&&A.constructor===LB)return A;if((k||YR(uf,A))&&(A=A.source,V&&(e=uF(cA))),A=A===void 0?"":hN(A),e=e===void 0?"":hN(e),cA=A,EF&&"dotAll"in sE&&(a=!!e&&pN(e,"s")>-1)&&(e=CF(e,/s/g,"")),o=e,BF&&"sticky"in sE&&(l=!!e&&pN(e,"y")>-1)&&iJ&&(e=CF(e,/y/g,"")),If&&(d=function(CA){for(var MA,ie=CA.length,pe=0,qe="",we=[],Di=ZV(null),Le=!1,Qt=!1,Bi=0,Si="";pe<=ie;pe++){if((MA=Ef(CA,pe))==="\\")MA+=Ef(CA,++pe);else if(MA==="]")Le=!1;else if(!Le)switch(!0){case MA==="[":Le=!0;break;case MA==="(":if(qe+=MA,mN(CA,pe+1,pe+3)==="?:")continue;dF(tJ,mN(CA,pe+1))&&(pe+=2,Qt=!0),Bi++;continue;case(MA===">"&&Qt):if(Si===""||$V(Di,Si))throw new eJ("Invalid capture group name");Di[Si]=!0,we[we.length]=[Si,Bi],Qt=!1,Si="";continue}Qt?Si+=MA:qe+=MA}return[qe,we]}(A),A=d[0],J=d[1]),h=WV(bB(A,e),S?this:uf,LB),(a||l||J.length)&&(y=QN(h),a&&(y.dotAll=!0,y.raw=LB(function(CA){for(var MA,ie=CA.length,pe=0,qe="",we=!1;pe<=ie;pe++)(MA=Ef(CA,pe))!=="\\"?we||MA!=="."?(MA==="["?we=!0:MA==="]"&&(we=!1),qe+=MA):qe+="[\\s\\S]":qe+=MA+Ef(CA,++pe);return qe}(A),o)),l&&(y.sticky=!0),J.length&&(y.groups=J)),A!==cA)try{zV(h,"source",cA===""?"(?:)":cA)}catch{}return h},yN=XV(bB),DN=0;yN.length>DN;)BN(LB,bB,yN[DN++]);uf.constructor=LB,LB.prototype=uf,VR(dN,"RegExp",LB,{constructor:!0})}HR("RegExp");var df=tA,up=We,UB=Br,oJ=Va,Cf=Ip,QF=xa,pF=un.get,sJ=EN,nJ=lF,rJ=Us("native-string-replace",String.prototype.replace),Ep=RegExp.prototype.exec,SN=Ep,aJ=up("".charAt),gJ=up("".indexOf),mF=up("".replace),IS=up("".slice),MN=function(){var A=/a/,e=/b*/g;return df(Ep,A,"a"),df(Ep,e,"a"),A.lastIndex!==0||e.lastIndex!==0}(),fF=Cf.BROKEN_CARET,vN=/()??/.exec("")[1]!==void 0;(MN||vN||fF||sJ||nJ)&&(SN=function(A){var e,o,a,l,d,h,y,S=this,k=pF(S),V=UB(A),J=k.raw;if(J)return J.lastIndex=S.lastIndex,e=df(SN,J,V),S.lastIndex=J.lastIndex,e;var cA=k.groups,CA=fF&&S.sticky,MA=df(oJ,S),ie=S.source,pe=0,qe=V;if(CA&&(MA=mF(MA,"y",""),gJ(MA,"g")===-1&&(MA+="g"),qe=IS(V,S.lastIndex),S.lastIndex>0&&(!S.multiline||S.multiline&&aJ(V,S.lastIndex-1)!==` +`)&&(ie="(?: "+ie+")",qe=" "+qe,pe++),o=new RegExp("^(?:"+ie+")",MA)),vN&&(o=new RegExp("^"+ie+"$(?!\\s)",MA)),MN&&(a=S.lastIndex),l=df(Ep,CA?o:S,qe),CA?l?(l.input=IS(l.input,pe),l[0]=IS(l[0],pe),l.index=S.lastIndex,S.lastIndex+=l[0].length):S.lastIndex=0:MN&&l&&(S.lastIndex=S.global?l.index+l[0].length:a),vN&&l&&l.length>1&&df(rJ,l[0],o,function(){for(d=1;d0;(a>>>=1)&&(e+=e))1&a&&(o+=e);return o},hf=so,Bf=SF(lJ),WR=SF("".slice),MF=Math.ceil,RN=function(A){return function(e,o,a){var l,d,h=jR(hf(e)),y=cJ(o),S=h.length,k=a===void 0?" ":jR(a);return y<=S||k===""?h:((d=Bf(k,MF((l=y-S)/k.length))).length>l&&(d=WR(d,0,l)),A?h+d:d+h)}},wN={start:RN(!1)},_N=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(ot),IJ=wN.start;_n({target:"String",proto:!0,forced:_N},{padStart:function(A){return IJ(this,A,arguments.length>1?arguments[1]:void 0)}});var vF=tA,TN=vr,RF=uS,NN=_,GN=Hs,uJ=GN("species"),wF=RegExp.prototype,zR=We,EJ=$r,Qf=Br,pf=so,bN=zR("".charAt),_F=zR("".charCodeAt),dJ=zR("".slice),TF=function(A){return function(e,o){var a,l,d=Qf(pf(e)),h=EJ(o),y=d.length;return h<0||h>=y?A?"":void 0:(a=_F(d,h))<55296||a>56319||h+1===y||(l=_F(d,h+1))<56320||l>57343?A?bN(d,h):a:A?dJ(d,h,h+2):l-56320+(a-55296<<10)+65536}},ZR={codeAt:TF(!1),charAt:TF(!0)},CJ=ZR.charAt,XR=We,hJ=as,BJ=Math.floor,kN=XR("".charAt),LN=XR("".replace),UN=XR("".slice),QJ=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,pJ=/\$([$&'`]|\d{1,2})/g,NF=function(A,e,o,a,l,d){var h=o+A.length,y=a.length,S=pJ;return l!==void 0&&(l=hJ(l),S=QJ),LN(d,S,function(k,V){var J;switch(kN(V,0)){case"$":return"$";case"&":return A;case"`":return UN(e,0,o);case"'":return UN(e,h);case"<":J=l[UN(V,1,-1)];break;default:var cA=+V;if(cA===0)return k;if(cA>y){var CA=BJ(cA/10);return CA===0?k:CA<=y?a[CA-1]===void 0?kN(V,1):a[CA-1]+kN(V,1):k}J=a[cA-1]}return J===void 0?"":J})},GF=tA,mJ=ar,bF=$i,fJ=ce,kF=uS,yJ=TypeError,DJ=_d,LF=tA,$R=We,SJ=function(A,e,o,a){var l=GN(A),d=!NN(function(){var k={};return k[l]=function(){return 7},""[A](k)!==7}),h=d&&!NN(function(){var k=!1,V=/a/,J;return V.exec=function(){return k=!0,null},V[l](""),!k});if(!d||!h||o){var y=/./[l],S=e(l,""[A],function(k,V,J,cA,CA){var MA=V.exec;return MA===RF||MA===wF.exec?d&&!CA?{done:!0,value:vF(y,V,J,cA)}:{done:!0,value:vF(k,J,V,cA)}:{done:!1}});TN(String.prototype,A,S[0]),TN(wF,l,S[1])}},MJ=_,vJ=ar,UF=$i,RJ=Ao,wJ=$r,FF=jn,dp=Br,Aw=so,OF=function(A,e,o){return e+(o?CJ(A,e).length:1)},ew=en,PF=NF,xF=OR,_J=function(A,e){var o=A.exec;if(bF(o)){var a=GF(o,A,e);return a!==null&&mJ(a),a}if(fJ(A)==="RegExp")return GF(kF,A,e);throw new yJ("RegExp#exec called on incompatible receiver")},tw=Hs("replace"),FN=Math.max,TJ=Math.min,YF=$R([].concat),ON=$R([].push),iw=$R("".indexOf),VF=$R("".slice),NJ=function(A){return A===void 0?A:String(A)},GJ="a".replace(/./,"$0")==="$0",JF=!!/./[tw]&&/./[tw]("a","$0")==="",bJ=!MJ(function(){var A=/./;return A.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(A,"$")!=="7"});SJ("replace",function(A,e,o){var a=JF?"$":"$0";return[function(l,d){var h=Aw(this),y=RJ(l)?ew(l,tw):void 0;return y?LF(y,l,h,d):LF(e,dp(h),l,d)},function(l,d){var h=vJ(this),y=dp(l);if(typeof d=="string"&&iw(d,a)===-1&&iw(d,"$<")===-1){var S=o(e,h,y,d);if(S.done)return S.value}var k=UF(d);k||(d=dp(d));var V,J=dp(xF(h)),cA=iw(J,"g")!==-1;cA&&(V=iw(J,"u")!==-1,h.lastIndex=0);for(var CA,MA=[];(CA=_J(h,y))!==null&&(ON(MA,CA),cA);)dp(CA[0])===""&&(h.lastIndex=OF(y,FF(h.lastIndex),V));for(var ie="",pe=0,qe=0;qe=pe&&(ie+=VF(y,pe,Le)+we,pe=Le+Di.length)}return ie+VF(y,pe)}]},!bJ||!GJ||JF);var ow=` +\v\f\r                 \u2028\u2029\uFEFF`,kJ=so,LJ=Br,PN=ow,xN=We("".replace),HF=RegExp("^["+PN+"]+"),UJ=RegExp("(^|[^"+PN+"])["+PN+"]+$"),FJ=function(A){return function(e){var o=LJ(kJ(e));return 1&A&&(o=xN(o,HF,"")),2&A&&(o=xN(o,UJ,"$1")),o}},OJ={trim:FJ(3)},PJ=zg.PROPER,xJ=_,qF=ow,YJ=OJ.trim;_n({target:"String",proto:!0,forced:function(A){return xJ(function(){return!!qF[A]()||"​…᠎"[A]()!=="​…᠎"||PJ&&qF[A].name!==A})}("trim")},{trim:function(){return YJ(this)}});var lu,mf,sw,YN={exports:{}},VJ=Rr,VN=N,NI=f,KF=$i,jF=Ao,ff=hs,nw=hr,JN=qn,HN=rg,qN=vr,WF=Lg,JJ=Ee,KN=yI,Cp=sA,HJ=Hs,qJ=pc,jN=un.enforce,Fh=NI.Int8Array,yf=Fh&&Fh.prototype,zF=NI.Uint8ClampedArray,ZF=zF&&zF.prototype,bC=Fh&&KN(Fh),Ud=yf&&KN(yf),KJ=Object.prototype,WN=NI.TypeError,XF=HJ("toStringTag"),zN=qJ("TYPED_ARRAY_TAG"),ES="TypedArrayConstructor",Fd=VJ&&!!Cp&&nw(NI.opera)!=="Opera",$F=!1,FB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},AO={BigInt64Array:8,BigUint64Array:8},rw=function(A){if(!jF(A))return!1;var e=nw(A);return ff(FB,e)||ff(AO,e)};for(lu in FB)(sw=(mf=NI[lu])&&mf.prototype)?jN(sw)[ES]=mf:Fd=!1;for(lu in AO)(sw=(mf=NI[lu])&&mf.prototype)&&(jN(sw)[ES]=mf);if((!Fd||!KF(bC)||bC===Function.prototype)&&(bC=function(){throw new WN("Incorrect invocation")},Fd))for(lu in FB)NI[lu]&&Cp(NI[lu],bC);if((!Fd||!Ud||Ud===KJ)&&(Ud=bC.prototype,Fd))for(lu in FB)NI[lu]&&Cp(NI[lu].prototype,Ud);if(Fd&&KN(ZF)!==Ud&&Cp(ZF,Ud),VN&&!ff(Ud,XF))for(lu in $F=!0,WF(Ud,XF,{configurable:!0,get:function(){return jF(this)?this[zN]:void 0}}),FB)NI[lu]&&HN(NI[lu],zN,lu);var Od={NATIVE_ARRAY_BUFFER_VIEWS:Fd,TYPED_ARRAY_TAG:$F&&zN,aTypedArray:function(A){if(rw(A))return A;throw new WN("Target is not a typed array")},aTypedArrayConstructor:function(A){if(KF(A)&&(!Cp||JJ(bC,A)))return A;throw new WN(JN(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,e,o,a){if(VN){if(o)for(var l in FB){var d=NI[l];if(d&&ff(d.prototype,A))try{delete d.prototype[A]}catch{try{d.prototype[A]=e}catch{}}}Ud[A]&&!o||qN(Ud,A,o?e:Fd&&yf[A]||e,a)}},exportTypedArrayStaticMethod:function(A,e,o){var a,l;if(VN){if(Cp){if(o){for(a in FB)if((l=NI[a])&&ff(l,A))try{delete l[A]}catch{}}if(bC[A]&&!o)return;try{return qN(bC,A,o?e:Fd&&bC[A]||e)}catch{}}for(a in FB)!(l=NI[a])||l[A]&&!o||qN(l,A,e)}},isTypedArray:rw,TypedArray:bC,TypedArrayPrototype:Ud},ZN=f,dS=_,aw=g,jJ=Od.NATIVE_ARRAY_BUFFER_VIEWS,eO=ZN.ArrayBuffer,hp=ZN.Int8Array,tO=!jJ||!dS(function(){hp(1)})||!dS(function(){new hp(-1)})||!aw(function(A){new hp,new hp(null),new hp(1.5),new hp(A)},!0)||dS(function(){return new hp(new eO(2),1,void 0).length!==1}),WJ=Ao,zJ=Math.floor,iO=Number.isInteger||function(A){return!WJ(A)&&isFinite(A)&&zJ(A)===A},ZJ=$r,XJ=RangeError,gw=function(A){var e=ZJ(A);if(e<0)throw new XJ("The argument can't be less than 0");return e},$J=RangeError,oO=function(A,e){var o=gw(A);if(o%e)throw new $J("Wrong offset");return o},AH=Math.round,sO=hr,eH=yn,tH=TypeError,cw=function(A){var e=eH(A,"number");if(typeof e=="number")throw new tH("Can't convert number to bigint");return BigInt(e)},nO=Ag,rO=tA,iH=fh,oH=as,aO=Fa,gO=jE,sH=Uh,cO=AS,lO=function(A){var e=sO(A);return e==="BigInt64Array"||e==="BigUint64Array"},nH=Od.aTypedArrayConstructor,rH=cw,lw=function(A){var e,o,a,l,d,h,y,S,k=iH(this),V=oH(A),J=arguments.length,cA=J>1?arguments[1]:void 0,CA=cA!==void 0,MA=sH(V);if(MA&&!cO(MA))for(S=(y=gO(V,MA)).next,V=[];!(h=rO(S,y)).done;)V.push(h.value);for(CA&&J>2&&(cA=nO(cA,arguments[2])),o=aO(V),a=new(nH(k))(o),l=lO(a),e=0;o>e;e++)d=CA?cA(V[e],e):V[e],a[e]=l?rH(d):+d;return a},XN=ta,$N=GD,aH=Ao,gH=Hs("species"),IO=Array,cH=function(A){var e;return XN(A)&&(e=A.constructor,($N(e)&&(e===IO||XN(e.prototype))||aH(e)&&(e=e[gH])===null)&&(e=void 0)),e===void 0?IO:e},uO=Ag,lH=oi,IH=as,EO=Fa,uH=function(A,e){return new(cH(A))(e===0?0:e)},AG=We([].push),dO=function(A){var e=A===1,o=A===2,a=A===3,l=A===4,d=A===6,h=A===7,y=A===5||d;return function(S,k,V,J){for(var cA,CA,MA=IH(S),ie=lH(MA),pe=EO(ie),qe=uO(k,V),we=0,Di=J||uH,Le=e?Di(S,pe):o||h?Di(S,0):void 0;pe>we;we++)if((y||we in ie)&&(CA=qe(cA=ie[we],we,MA),A))if(e)Le[we]=CA;else if(CA)switch(A){case 3:return!0;case 5:return cA;case 6:return we;case 2:AG(Le,cA)}else switch(A){case 4:return!1;case 7:AG(Le,cA)}return d?-1:a||l?l:Le}},CO={forEach:dO(0)},EH=Fa,hO=_n,BO=f,QO=tA,pO=N,dH=tO,CS=Od,mO=Um,fO=vI,CH=KA,OB=rg,hH=iO,BH=jn,yO=Mm,eG=oO,DO=function(A){var e=AH(A);return e<0?0:e>255?255:255&e},tG=$,Bp=hs,QH=hr,iG=Ao,oG=So,pH=xa,sG=Ee,Iw=sA,mH=Mc.f,SO=lw,MO=CO.forEach,uw=Om,fH=Lg,vO=Wi,RO=w,wO=function(A,e,o){for(var a=0,l=arguments.length>2?o:EH(e),d=new A(l);l>a;)d[a]=e[a++];return d},yH=pD,nG=un.get,DH=un.set,Qp=un.enforce,_O=vO.f,SH=RO.f,rG=BO.RangeError,TO=mO.ArrayBuffer,MH=TO.prototype,vH=mO.DataView,Df=CS.NATIVE_ARRAY_BUFFER_VIEWS,NO=CS.TYPED_ARRAY_TAG,GO=CS.TypedArray,hS=CS.TypedArrayPrototype,BS=CS.isTypedArray,pp="BYTES_PER_ELEMENT",Ew="Wrong length",dw=function(A,e){fH(A,e,{configurable:!0,get:function(){return nG(this)[e]}})},bO=function(A){var e;return sG(MH,A)||(e=QH(A))==="ArrayBuffer"||e==="SharedArrayBuffer"},aG=function(A,e){return BS(A)&&!oG(e)&&e in A&&hH(+e)&&e>=0},Cw=function(A,e){return e=tG(e),aG(A,e)?CH(2,A[e]):SH(A,e)},kO=function(A,e,o){return e=tG(e),!(aG(A,e)&&iG(o)&&Bp(o,"value"))||Bp(o,"get")||Bp(o,"set")||o.configurable||Bp(o,"writable")&&!o.writable||Bp(o,"enumerable")&&!o.enumerable?_O(A,e,o):(A[e]=o.value,A)};pO?(Df||(RO.f=Cw,vO.f=kO,dw(hS,"buffer"),dw(hS,"byteOffset"),dw(hS,"byteLength"),dw(hS,"length")),hO({target:"Object",stat:!0,forced:!Df},{getOwnPropertyDescriptor:Cw,defineProperty:kO}),YN.exports=function(A,e,o){var a=A.match(/\d+/)[0]/8,l=A+(o?"Clamped":"")+"Array",d="get"+A,h="set"+A,y=BO[l],S=y,k=S&&S.prototype,V={},J=function(CA,MA){_O(CA,MA,{get:function(){return function(ie,pe){var qe=nG(ie);return qe.view[d](pe*a+qe.byteOffset,!0)}(this,MA)},set:function(ie){return function(pe,qe,we){var Di=nG(pe);Di.view[h](qe*a+Di.byteOffset,o?DO(we):we,!0)}(this,MA,ie)},enumerable:!0})};Df?dH&&(S=e(function(CA,MA,ie,pe){return fO(CA,k),yH(iG(MA)?bO(MA)?pe!==void 0?new y(MA,eG(ie,a),pe):ie!==void 0?new y(MA,eG(ie,a)):new y(MA):BS(MA)?wO(S,MA):QO(SO,S,MA):new y(yO(MA)),CA,S)}),Iw&&Iw(S,GO),MO(mH(y),function(CA){CA in S||OB(S,CA,y[CA])}),S.prototype=k):(S=e(function(CA,MA,ie,pe){fO(CA,k);var qe,we,Di,Le=0,Qt=0;if(iG(MA)){if(!bO(MA))return BS(MA)?wO(S,MA):QO(SO,S,MA);qe=MA,Qt=eG(ie,a);var Bi=MA.byteLength;if(pe===void 0){if(Bi%a)throw new rG(Ew);if((we=Bi-Qt)<0)throw new rG(Ew)}else if((we=BH(pe)*a)+Qt>Bi)throw new rG(Ew);Di=we/a}else Di=yO(MA),qe=new TO(we=Di*a);for(DH(CA,{buffer:qe,byteOffset:Qt,byteLength:we,length:Di,view:new vH(qe)});Le1?arguments[1]:void 0,e>2?arguments[2]:void 0)},gG(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,Od.exportTypedArrayStaticMethod)("from",lw,tO);var FO=f,OO=tA,lG=Od,PO=Fa,GH=oO,bH=as,xO=_,kH=FO.RangeError,IG=FO.Int8Array,uG=IG&&IG.prototype,EG=uG&&uG.set,dG=lG.aTypedArray,YO=lG.exportTypedArrayMethod,hw=!xO(function(){var A=new Uint8ClampedArray(2);return OO(EG,A,{length:1,0:3},1),A[1]!==3}),VO=hw&&lG.NATIVE_ARRAY_BUFFER_VIEWS&&xO(function(){var A=new IG(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});YO("set",function(A){dG(this);var e=GH(arguments.length>1?arguments[1]:void 0,1),o=bH(A);if(hw)return OO(EG,this,o,e);var a=this.length,l=PO(o),d=0;if(l+e>a)throw new kH("Wrong length");for(;d0&&1/a<0?1:-1:o>a}}(A))},!Bw||fG);var HO=_n,yG=tA,pS=We,DG=so,SG=$i,FH=Ao,qO=xg,mS=Br,OH=en,fS=OR,KO=NF,PH=Hs("replace"),jO=TypeError,Pd=pS("".indexOf);pS("".replace);var yS=pS("".slice),xH=Math.max;HO({target:"String",proto:!0},{replaceAll:function(A,e){var o,a,l,d,h,y,S,k,V,J=DG(this),cA=0,CA="";if(FH(A)){if(qO(A)&&(o=mS(DG(fS(A))),!~Pd(o,"g")))throw new jO("`.replaceAll` does not allow non-global regexes");if(a=OH(A,PH))return yG(a,A,J,e)}for(l=mS(J),d=mS(A),(h=SG(e))||(e=mS(e)),y=d.length,S=xH(1,y),k=Pd(l,d);k!==-1;)V=h?mS(e(d,k,l)):KO(d,l,k,[],void 0,e),CA+=yS(l,cA,k)+V,cA=k+y,k=k+S>l.length?-1:Pd(l,d,k+S);return cA1?arguments[1]:void 0)},zO=f,ZO=MG,JH=vG,pw=VH,HH=rg,XO=function(A){if(A&&A.forEach!==pw)try{HH(A,"forEach",pw)}catch{A.forEach=pw}};for(var RG in ZO)ZO[RG]&&XO(zO[RG]&&zO[RG].prototype);XO(JH);var mw=f,$O=MG,qH=vG,DS=zi,SS=rg,KH=Ya,wG=Hs("iterator"),_G=DS.values,AP=function(A,e){if(A){if(A[wG]!==_G)try{SS(A,wG,_G)}catch{A[wG]=_G}if(KH(A,e,!0),$O[e]){for(var o in DS)if(A[o]!==DS[o])try{SS(A,o,DS[o])}catch{A[o]=DS[o]}}}};for(var TG in $O)AP(mw[TG]&&mw[TG].prototype,TG);AP(qH,"DOMTokenList");var NG=wC.clear;_n({global:!0,bind:!0,enumerable:!0,forced:f.clearImmediate!==NG},{clearImmediate:NG});var MS=f,jH=_d,WH=$i,zH=Hr,ZH=ot,XH=de,$H=QB,GG=MS.Function,Aq=/MSIE .\./.test(ZH)||zH==="BUN"&&function(){var A=MS.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),eP=_n,tP=f,fw=wC.set,eq=function(A,e){var o=1;return Aq?function(a,l){var d=$H(arguments.length,1)>o,h=WH(a)?a:GG(a),y=d?XH(arguments,o):[],S=d?function(){jH(h,this,y)}:h;return A(S)}:A},bG=tP.setImmediate?eq(fw):fw;eP({global:!0,bind:!0,enumerable:!0,forced:tP.setImmediate!==bG},{setImmediate:bG});var Oh=ZR.charAt,tq=Br,yw=un,iq=he,iP=Ze,oP="String Iterator",oq=yw.set,sP=yw.getterFor(oP);iq(String,"String",function(A){oq(this,{type:oP,string:tq(A),index:0})},function(){var A,e=sP(this),o=e.string,a=e.index;return a>=o.length?iP(void 0,!0):(A=Oh(o,a),e.index+=A.length,iP(A,!1))});var sq=_,nq=N,rq=Hs("iterator"),nP=!sq(function(){var A=new URL("b?a=1&b=2&c=3","https://a"),e=A.searchParams,o=new URLSearchParams("a=1&a=2&b=3"),a="";return A.pathname="c%20d",e.forEach(function(l,d){e.delete("b"),a+=d+l}),o.delete("a",2),o.delete("b",void 0),!e.size&&!nq||!e.sort||A.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[rq]||new URL("https://a@b").username!=="a"||new URLSearchParams(new URLSearchParams("a=b")).get("a")!=="b"||new URL("https://тест").host!=="xn--e1aybc"||new URL("https://a#б").hash!=="#%D0%B1"||a!=="a1c3"||new URL("https://x",void 0).host!=="x"}),rP=N,aq=We,kG=tA,LG=_,UG=kl,gq=vc,cq=BA,lq=as,aP=oi,mp=Object.assign,gP=Object.defineProperty,cP=aq([].concat),Iq=!mp||LG(function(){if(rP&&mp({b:1},mp(gP({},"a",{enumerable:!0,get:function(){gP(this,"b",{value:3,enumerable:!1})}}),{b:2})).b!==1)return!0;var A={},e={},o=Symbol("assign detection"),a="abcdefghijklmnopqrst";return A[o]=7,a.split("").forEach(function(l){e[l]=l}),mp({},A)[o]!==7||UG(mp({},e)).join("")!==a})?function(A,e){for(var o=lq(A),a=arguments.length,l=1,d=gq.f,h=cq.f;a>l;)for(var y,S=aP(arguments[l++]),k=d?cP(UG(S),d(S)):UG(S),V=k.length,J=0;V>J;)y=k[J++],rP&&!kG(h,S,y)||(o[y]=S[y]);return o}:mp,uq=ar,Eq=oS,dq=N,Cq=Wi,lP=KA,hq=Ag,vS=tA,IP=as,uP=function(A,e,o,a){try{return a?e(uq(o)[0],o[1]):e(o)}catch(l){Eq(A,"throw",l)}},FG=AS,Bq=GD,Qq=Fa,RS=function(A,e,o){dq?Cq.f(A,e,lP(0,o)):A[e]=o},OG=jE,pq=Uh,EP=Array,PB=We,PG=2147483647,dP=/[^\0-\u007E]/,xG=/[.\u3002\uFF0E\uFF61]/g,CP="Overflow: input needs wider integers to process",hP=RangeError,mq=PB(xG.exec),xB=Math.floor,Dw=String.fromCharCode,Sw=PB("".charCodeAt),nE=PB([].join),YB=PB([].push),pa=PB("".replace),BP=PB("".split),fq=PB("".toLowerCase),QP=function(A){return A+22+75*(A<26)},YG=function(A,e,o){var a=0;for(A=o?xB(A/700):A>>1,A+=xB(A/e);A>455;)A=xB(A/35),a+=36;return xB(a+36*A/(A+38))},yq=function(A){var e=[];A=function(qe){for(var we=[],Di=0,Le=qe.length;Di=55296&&Qt<=56319&&Di=d&&axB((PG-h)/J))throw new hP(CP);for(h+=(V-d)*J,d=V,o=0;oPG)throw new hP(CP);if(a===d){for(var cA=h,CA=36;;){var MA=CA<=y?1:CA>=y+26?26:CA-y;if(cAl;){if(e=+arguments[l++],Dq(e,1114111)!==e)throw new Sq(e+" is not a valid code point");o[l]=e<65536?Ph(e):Ph(55296+((e-=65536)>>10),e%1024+56320)}return _S(o,"")}});var fp=_n,vf=f,yp=uR,VG=VA,Os=tA,rE=We,Rf=N,JG=nP,mP=vr,Mq=Lg,vq=ru,Rq=Ya,wq=PE,TS=un,fP=vI,HG=$i,_q=hs,Tq=Ag,Nq=hr,Gq=ar,yP=Ao,Jl=Br,bq=xa,DP=KA,SP=jE,kq=Uh,Mw=Ze,wf=QB,Lq=Rt,Uq=Hs("iterator"),Dp="URLSearchParams",qG=Dp+"Iterator",MP=TS.set,ul=TS.getterFor(Dp),xh=TS.getterFor(qG),vP=yp("fetch"),_f=yp("Request"),NS=yp("Headers"),KG=_f&&_f.prototype,RP=NS&&NS.prototype,wP=vf.TypeError,Fq=vf.encodeURIComponent,Oq=String.fromCharCode,Pq=VG("String","fromCodePoint"),xq=parseInt,vw=rE("".charAt),Rw=rE([].join),Yh=rE([].push),_P=rE("".replace),Yq=rE([].shift),TP=rE([].splice),NP=rE("".split),GP=rE("".slice),jG=rE(/./.exec),bP=/\+/g,Vq=/^[0-9a-f]+$/i,kP=function(A,e){var o=GP(A,e,e+2);return jG(Vq,o)?xq(o,16):NaN},Jq=function(A){for(var e=0,o=128;o>0&&A&o;o>>=1)e++;return e},Hq=function(A){var e=null;switch(A.length){case 1:e=A[0];break;case 2:e=(31&A[0])<<6|63&A[1];break;case 3:e=(15&A[0])<<12|(63&A[1])<<6|63&A[2];break;case 4:e=(7&A[0])<<18|(63&A[1])<<12|(63&A[2])<<6|63&A[3]}return e>1114111?null:e},LP=function(A){for(var e=(A=_P(A,bP," ")).length,o="",a=0;ae){o+="%",a++;continue}var d=kP(A,a+1);if(d!=d){o+=l,a++;continue}a+=2;var h=Jq(d);if(h===0)l=Oq(d);else{if(h===1||h>4){o+="�",a++;continue}for(var y=[d],S=1;Se||vw(A,a)!=="%");){var k=kP(A,a+1);if(k!=k){a+=3;break}if(k>191||k<128)break;Yh(y,k),a+=2,S++}if(y.length!==h){o+="�";continue}var V=Hq(y);V===null?o+="�":l=Pq(V)}}o+=l,a++}return o},Kq=/[!'()~]|%20/g,jq={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},Wq=function(A){return jq[A]},UP=function(A){return _P(Fq(A),Kq,Wq)},WG=wq(function(A,e){MP(this,{type:qG,target:ul(A).entries,index:0,kind:e})},Dp,function(){var A=xh(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,Mw(void 0,!0);var a=e[o];switch(A.kind){case"keys":return Mw(a.key,!1);case"values":return Mw(a.value,!1)}return Mw([a.key,a.value],!1)},!0),FP=function(A){this.entries=[],this.url=null,A!==void 0&&(yP(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?vw(A,0)==="?"?GP(A,1):A:Jl(A)))};FP.prototype={type:Dp,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var e,o,a,l,d,h,y,S=this.entries,k=kq(A);if(k)for(o=(e=SP(A,k)).next;!(a=Os(o,e)).done;){if(d=(l=SP(Gq(a.value))).next,(h=Os(d,l)).done||(y=Os(d,l)).done||!Os(d,l).done)throw new wP("Expected sequence with length 2");Yh(S,{key:Jl(h.value),value:Jl(y.value)})}else for(var V in A)_q(A,V)&&Yh(S,{key:V,value:Jl(A[V])})},parseQuery:function(A){if(A)for(var e,o,a=this.entries,l=NP(A,"&"),d=0;d0?arguments[0]:void 0));Rf||(this.size=A.entries.length)},Sp=Tf.prototype;if(vq(Sp,{append:function(A,e){var o=ul(this);wf(arguments.length,2),Yh(o.entries,{key:Jl(A),value:Jl(e)}),Rf||this.size++,o.updateURL()},delete:function(A){for(var e=ul(this),o=wf(arguments.length,1),a=e.entries,l=Jl(A),d=o<2?void 0:arguments[1],h=d===void 0?d:Jl(d),y=0;yo.key?1:-1}),A.updateURL()},forEach:function(A){for(var e,o=ul(this).entries,a=Tq(A,arguments.length>1?arguments[1]:void 0),l=0;l1?OP(arguments[1]):{})}}),HG(_f)){var ZG=function(A){return fP(this,KG),new _f(A,arguments.length>1?OP(arguments[1]):{})};KG.constructor=ZG,ZG.prototype=KG,fp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:ZG})}}var aE,Zq=_n,XG=N,PP=nP,$G=f,xP=Ag,WE=We,ww=vr,zE=Lg,Xq=vI,Ab=hs,eb=Iq,VB=function(A){var e=IP(A),o=Bq(this),a=arguments.length,l=a>1?arguments[1]:void 0,d=l!==void 0;d&&(l=hq(l,a>2?arguments[2]:void 0));var h,y,S,k,V,J,cA=pq(e),CA=0;if(!cA||this===EP&&FG(cA))for(h=Qq(e),y=o?new this(h):EP(h);h>CA;CA++)J=d?l(e[CA],CA):e[CA],RS(y,CA,J);else for(y=o?new this:[],V=(k=OG(e,cA)).next;!(S=vS(V,k)).done;CA++)J=d?uP(k,l,[S.value,CA],!0):S.value,RS(y,CA,J);return y.length=CA,y},xd=de,tb=ZR.codeAt,$q=function(A){var e,o,a=[],l=BP(pa(fq(A),xG,"."),".");for(e=0;e?@[\\\]^|]/,aK=/[\0\t\n\r #/:<>?@[\\\]^|]/,gK=/^[\u0000-\u0020]+/,cK=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,lK=/[\t\n\r]/g,bf=function(A){var e,o,a,l;if(typeof A=="number"){for(e=[],o=0;o<4;o++)sK(e,A%256),A=Jh(A/256);return GS(e,".")}if(typeof A=="object"){for(e="",a=function(d){for(var h=null,y=1,S=null,k=0,V=0;V<8;V++)d[V]!==0?(k>y&&(h=S,y=k),S=null,k=0):(S===null&&(S=V),++k);return k>y?S:h}(A),o=0;o<8;o++)l&&A[o]===0||(l&&(l=!1),a===o?(e+=o?":":"::",l=!0):(e+=oK(A[o],16),o<7&&(e+=":")));return"["+e+"]"}return A},kf={},WP=eb({},kf,{" ":1,'"':1,"<":1,">":1,"`":1}),ab=eb({},WP,{"#":1,"?":1,"{":1,"}":1}),HB=eb({},ab,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Vd=function(A,e){var o=tb(A,0);return o>32&&o<127&&!Ab(e,A)?A:encodeURIComponent(A)},Hh={ftp:21,file:null,http:80,https:443,ws:80,wss:443},Lf=function(A,e){var o;return A.length===2&&Yd(bS,ZE(A,0))&&((o=ZE(A,1))===":"||!e&&o==="|")},gb=function(A){var e;return A.length>1&&Lf(Mp(A,0,2))&&(A.length===2||(e=ZE(A,2))==="/"||e==="\\"||e==="?"||e==="#")},kS=function(A){return A==="."||bw(A)==="%2e"},zP=function(A){return(A=bw(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},gE={},Iu={},qB={},kC={},KB={},Uw={},ZP={},LS={},Fw={},Ow={},Pw={},xw={},Yw={},Vw={},cb={},Jw={},Uf={},LC={},US={},uu={},Hl={},Hw=function(A,e,o){var a,l,d,h=Vh(A);if(e){if(l=this.parse(h))throw new ob(l);this.searchParams=null}else{if(o!==void 0&&(a=new Hw(o,!0)),l=this.parse(h,null,a))throw new ob(l);(d=iK(new tK)).bindURL(this),this.searchParams=d}};Hw.prototype={type:"URL",parse:function(A,e,o){var a,l,d,h,y=this,S=e||gE,k=0,V="",J=!1,cA=!1,CA=!1;for(A=Vh(A),e||(y.scheme="",y.username="",y.password="",y.host=null,y.port=null,y.path=[],y.query=null,y.fragment=null,y.cannotBeABaseURL=!1,A=Nw(A,gK,""),A=Nw(A,cK,"$1")),A=Nw(A,lK,""),a=VB(A);k<=a.length;){switch(l=a[k],S){case gE:if(!l||!Yd(bS,l)){if(e)return nb;S=qB;continue}V+=bw(l),S=Iu;break;case Iu:if(l&&(Yd(nK,l)||l==="+"||l==="-"||l==="."))V+=bw(l);else{if(l!==":"){if(e)return nb;V="",S=qB,k=0;continue}if(e&&(y.isSpecial()!==Ab(Hh,V)||V==="file"&&(y.includesCredentials()||y.port!==null)||y.scheme==="file"&&!y.host))return;if(y.scheme=V,e)return void(y.isSpecial()&&Hh[y.scheme]===y.port&&(y.port=null));V="",y.scheme==="file"?S=Vw:y.isSpecial()&&o&&o.scheme===y.scheme?S=kC:y.isSpecial()?S=LS:a[k+1]==="/"?(S=KB,k++):(y.cannotBeABaseURL=!0,Gf(y.path,""),S=US)}break;case qB:if(!o||o.cannotBeABaseURL&&l!=="#")return nb;if(o.cannotBeABaseURL&&l==="#"){y.scheme=o.scheme,y.path=xd(o.path),y.query=o.query,y.fragment="",y.cannotBeABaseURL=!0,S=Hl;break}S=o.scheme==="file"?Vw:Uw;continue;case kC:if(l!=="/"||a[k+1]!=="/"){S=Uw;continue}S=Fw,k++;break;case KB:if(l==="/"){S=Ow;break}S=LC;continue;case Uw:if(y.scheme=o.scheme,l===aE)y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query=o.query;else if(l==="/"||l==="\\"&&y.isSpecial())S=ZP;else if(l==="?")y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query="",S=uu;else{if(l!=="#"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.path.length--,S=LC;continue}y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,y.path=xd(o.path),y.query=o.query,y.fragment="",S=Hl}break;case ZP:if(!y.isSpecial()||l!=="/"&&l!=="\\"){if(l!=="/"){y.username=o.username,y.password=o.password,y.host=o.host,y.port=o.port,S=LC;continue}S=Ow}else S=Fw;break;case LS:if(S=Fw,l!=="/"||ZE(V,k+1)!=="/")continue;k++;break;case Fw:if(l!=="/"&&l!=="\\"){S=Ow;continue}break;case Ow:if(l==="@"){J&&(V="%40"+V),J=!0,d=VB(V);for(var MA=0;MA65535)return kw;y.port=y.isSpecial()&&qe===Hh[y.scheme]?null:qe,V=""}if(e)return;S=Uf;continue}return kw}V+=l;break;case Vw:if(y.scheme="file",l==="/"||l==="\\")S=cb;else{if(!o||o.scheme!=="file"){S=LC;continue}switch(l){case aE:y.host=o.host,y.path=xd(o.path),y.query=o.query;break;case"?":y.host=o.host,y.path=xd(o.path),y.query="",S=uu;break;case"#":y.host=o.host,y.path=xd(o.path),y.query=o.query,y.fragment="",S=Hl;break;default:gb(GS(xd(a,k),""))||(y.host=o.host,y.path=xd(o.path),y.shortenPath()),S=LC;continue}}break;case cb:if(l==="/"||l==="\\"){S=Jw;break}o&&o.scheme==="file"&&!gb(GS(xd(a,k),""))&&(Lf(o.path[0],!0)?Gf(y.path,o.path[0]):y.host=o.host),S=LC;continue;case Jw:if(l===aE||l==="/"||l==="\\"||l==="?"||l==="#"){if(!e&&Lf(V))S=LC;else if(V===""){if(y.host="",e)return;S=Uf}else{if(h=y.parseHost(V))return h;if(y.host==="localhost"&&(y.host=""),e)return;V="",S=Uf}continue}V+=l;break;case Uf:if(y.isSpecial()){if(S=LC,l!=="/"&&l!=="\\")continue}else if(e||l!=="?")if(e||l!=="#"){if(l!==aE&&(S=LC,l!=="/"))continue}else y.fragment="",S=Hl;else y.query="",S=uu;break;case LC:if(l===aE||l==="/"||l==="\\"&&y.isSpecial()||!e&&(l==="?"||l==="#")){if(zP(V)?(y.shortenPath(),l==="/"||l==="\\"&&y.isSpecial()||Gf(y.path,"")):kS(V)?l==="/"||l==="\\"&&y.isSpecial()||Gf(y.path,""):(y.scheme==="file"&&!y.path.length&&Lf(V)&&(y.host&&(y.host=""),V=ZE(V,0)+":"),Gf(y.path,V)),V="",y.scheme==="file"&&(l===aE||l==="?"||l==="#"))for(;y.path.length>1&&y.path[0]==="";)Gw(y.path);l==="?"?(y.query="",S=uu):l==="#"&&(y.fragment="",S=Hl)}else V+=Vd(l,ab);break;case US:l==="?"?(y.query="",S=uu):l==="#"?(y.fragment="",S=Hl):l!==aE&&(y.path[0]+=Vd(l,kf));break;case uu:e||l!=="#"?l!==aE&&(l==="'"&&y.isSpecial()?y.query+="%27":y.query+=l==="#"?"%23":Vd(l,kf)):(y.fragment="",S=Hl);break;case Hl:l!==aE&&(y.fragment+=Vd(l,WP))}k++}},parseHost:function(A){var e,o,a;if(ZE(A,0)==="["){if(ZE(A,A.length-1)!=="]"||(e=function(l){var d,h,y,S,k,V,J,cA=[0,0,0,0,0,0,0,0],CA=0,MA=null,ie=0,pe=function(){return ZE(l,ie)};if(pe()===":"){if(ZE(l,1)!==":")return;ie+=2,MA=++CA}for(;pe();){if(CA===8)return;if(pe()!==":"){for(d=h=0;h<4&&Yd(KP,pe());)d=16*d+Tw(pe(),16),ie++,h++;if(pe()==="."){if(h===0||(ie-=h,CA>6))return;for(y=0;pe();){if(S=null,y>0){if(!(pe()==="."&&y<4))return;ie++}if(!Yd(rb,pe()))return;for(;Yd(rb,pe());){if(k=Tw(pe(),10),S===null)S=k;else{if(S===0)return;S=10*S+k}if(S>255)return;ie++}cA[CA]=256*cA[CA]+S,++y!==2&&y!==4||CA++}if(y!==4)return;break}if(pe()===":"){if(ie++,!pe())return}else if(pe())return;cA[CA++]=d}else{if(MA!==null)return;ie++,MA=++CA}}if(MA!==null)for(V=CA-MA,CA=7;CA!==0&&V>0;)J=cA[CA],cA[CA--]=cA[MA+V-1],cA[MA+--V]=J;else if(CA!==8)return;return cA}(Mp(A,1,-1)),!e))return JB;this.host=e}else if(this.isSpecial()){if(A=$q(A),Yd(jP,A)||(e=function(l){var d,h,y,S,k,V,J,cA=sb(l,".");if(cA.length&&cA[cA.length-1]===""&&cA.length--,(d=cA.length)>4)return l;for(h=[],y=0;y1&&ZE(S,0)==="0"&&(k=Yd(Lw,S)?16:8,S=Mp(S,k===8?1:2)),S==="")V=0;else{if(!Yd(k===10?qP:k===8?rK:KP,S))return l;V=Tw(S,k)}Gf(h,V)}for(y=0;y=JP(256,5-d))return null}else if(V>255)return null;for(J=HP(h),y=0;y1?arguments[1]:void 0,a=eK(e,new Hw(A,!1,o));XG||(e.href=a.serialize(),e.origin=a.getOrigin(),e.protocol=a.getProtocol(),e.username=a.getUsername(),e.password=a.getPassword(),e.host=a.getHost(),e.hostname=a.getHostname(),e.port=a.getPort(),e.pathname=a.getPathname(),e.search=a.getSearch(),e.searchParams=a.getSearchParams(),e.hash=a.getHash())},ql=qh.prototype,Kl=function(A,e){return{get:function(){return _w(this)[A]()},set:e&&function(o){return _w(this)[e](o)},configurable:!0,enumerable:!0}};if(XG&&(zE(ql,"href",Kl("serialize","setHref")),zE(ql,"origin",Kl("getOrigin")),zE(ql,"protocol",Kl("getProtocol","setProtocol")),zE(ql,"username",Kl("getUsername","setUsername")),zE(ql,"password",Kl("getPassword","setPassword")),zE(ql,"host",Kl("getHost","setHost")),zE(ql,"hostname",Kl("getHostname","setHostname")),zE(ql,"port",Kl("getPort","setPort")),zE(ql,"pathname",Kl("getPathname","setPathname")),zE(ql,"search",Kl("getSearch","setSearch")),zE(ql,"searchParams",Kl("getSearchParams")),zE(ql,"hash",Kl("getHash","setHash"))),ww(ql,"toJSON",function(){return _w(this).serialize()},{enumerable:!0}),ww(ql,"toString",function(){return _w(this).serialize()},{enumerable:!0}),Nf){var XP=Nf.createObjectURL,qw=Nf.revokeObjectURL;XP&&ww(qh,"createObjectURL",xP(XP,Nf)),qw&&ww(qh,"revokeObjectURL",xP(qw,Nf))}AK(qh,"URL"),Zq({global:!0,constructor:!0,forced:!PP,sham:!XG},{URL:qh});var $P=tA;_n({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return $P(URL.prototype.toString,this)}});let Ax=!0,Kw=!0;function FS(A,e,o){const a=A.match(e);return a&&a.length>=o&&parseFloat(a[o],10)}function jB(A,e,o){if(!A.RTCPeerConnection)return;const a=A.RTCPeerConnection.prototype,l=a.addEventListener;a.addEventListener=function(h,y){if(h!==e)return l.apply(this,arguments);const S=k=>{const V=o(k);V&&(y.handleEvent?y.handleEvent(V):y(V))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(y,S),l.apply(this,[h,S])};const d=a.removeEventListener;a.removeEventListener=function(h,y){if(h!==e||!this._eventMap||!this._eventMap[e])return d.apply(this,arguments);if(!this._eventMap[e].has(y))return d.apply(this,arguments);const S=this._eventMap[e].get(y);return this._eventMap[e].delete(y),this._eventMap[e].size===0&&delete this._eventMap[e],Object.keys(this._eventMap).length===0&&delete this._eventMap,d.apply(this,[h,S])},Object.defineProperty(a,"on"+e,{get(){return this["_on"+e]},set(h){this["_on"+e]&&(this.removeEventListener(e,this["_on"+e]),delete this["_on"+e]),h&&this.addEventListener(e,this["_on"+e]=h)},enumerable:!0,configurable:!0})}function ex(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(Ax=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function IK(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(Kw=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function jw(){if(typeof window=="object"){if(Ax)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function OS(A,e){Kw&&console.warn(A+" is deprecated, please use "+e+" instead.")}function lb(A){return Object.prototype.toString.call(A)==="[object Object]"}function Ib(A){return lb(A)?Object.keys(A).reduce(function(e,o){const a=lb(A[o]),l=a?Ib(A[o]):A[o],d=a&&!Object.keys(l).length;return l===void 0||d?e:Object.assign(e,{[o]:l})},{}):A}function ub(A,e,o){e&&!o.has(e.id)&&(o.set(e.id,e),Object.keys(e).forEach(a=>{a.endsWith("Id")?ub(A,A.get(e[a]),o):a.endsWith("Ids")&&e[a].forEach(l=>{ub(A,A.get(l),o)})}))}function tx(A,e,o){const a=o?"outbound-rtp":"inbound-rtp",l=new Map;if(e===null)return l;const d=[];return A.forEach(h=>{h.type==="track"&&h.trackIdentifier===e.id&&d.push(h)}),d.forEach(h=>{A.forEach(y=>{y.type===a&&y.trackId===h.id&&ub(A,y,l)})}),l}const Eb=jw;function ix(A,e){const o=A&&A.navigator;if(!o.mediaDevices)return;const a=function(h){if(typeof h!="object"||h.mandatory||h.optional)return h;const y={};return Object.keys(h).forEach(S=>{if(S==="require"||S==="advanced"||S==="mediaSource")return;const k=typeof h[S]=="object"?h[S]:{ideal:h[S]};k.exact!==void 0&&typeof k.exact=="number"&&(k.min=k.max=k.exact);const V=function(J,cA){return J?J+cA.charAt(0).toUpperCase()+cA.slice(1):cA==="deviceId"?"sourceId":cA};if(k.ideal!==void 0){y.optional=y.optional||[];let J={};typeof k.ideal=="number"?(J[V("min",S)]=k.ideal,y.optional.push(J),J={},J[V("max",S)]=k.ideal,y.optional.push(J)):(J[V("",S)]=k.ideal,y.optional.push(J))}k.exact!==void 0&&typeof k.exact!="number"?(y.mandatory=y.mandatory||{},y.mandatory[V("",S)]=k.exact):["min","max"].forEach(J=>{k[J]!==void 0&&(y.mandatory=y.mandatory||{},y.mandatory[V(J,S)]=k[J])})}),h.advanced&&(y.optional=(y.optional||[]).concat(h.advanced)),y},l=function(h,y){if(e.version>=61)return y(h);if((h=JSON.parse(JSON.stringify(h)))&&typeof h.audio=="object"){const S=function(k,V,J){V in k&&!(J in k)&&(k[J]=k[V],delete k[V])};S((h=JSON.parse(JSON.stringify(h))).audio,"autoGainControl","googAutoGainControl"),S(h.audio,"noiseSuppression","googNoiseSuppression"),h.audio=a(h.audio)}if(h&&typeof h.video=="object"){let S=h.video.facingMode;S=S&&(typeof S=="object"?S:{ideal:S});const k=e.version<66;if(S&&(S.exact==="user"||S.exact==="environment"||S.ideal==="user"||S.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||k)){let V;if(delete h.video.facingMode,S.exact==="environment"||S.ideal==="environment"?V=["back","rear"]:S.exact!=="user"&&S.ideal!=="user"||(V=["front"]),V)return o.mediaDevices.enumerateDevices().then(J=>{J=J.filter(CA=>CA.kind==="videoinput");let cA=J.find(CA=>V.some(MA=>CA.label.toLowerCase().includes(MA)));return!cA&&J.length&&V.includes("back")&&(cA=J[J.length-1]),cA&&(h.video.deviceId=S.exact?{exact:cA.deviceId}:{ideal:cA.deviceId}),h.video=a(h.video),Eb("chrome: "+JSON.stringify(h)),y(h)})}h.video=a(h.video)}return Eb("chrome: "+JSON.stringify(h)),y(h)},d=function(h){return e.version>=64?h:{name:{PermissionDeniedError:"NotAllowedError",PermissionDismissedError:"NotAllowedError",InvalidStateError:"NotAllowedError",DevicesNotFoundError:"NotFoundError",ConstraintNotSatisfiedError:"OverconstrainedError",TrackStartError:"NotReadableError",MediaDeviceFailedDueToShutdown:"NotAllowedError",MediaDeviceKillSwitchOn:"NotAllowedError",TabCaptureError:"AbortError",ScreenCaptureError:"AbortError",DeviceCaptureError:"AbortError"}[h.name]||h.name,message:h.message,constraint:h.constraint||h.constraintName,toString(){return this.name+(this.message&&": ")+this.message}}};if(o.getUserMedia=function(h,y,S){l(h,k=>{o.webkitGetUserMedia(k,y,V=>{S&&S(d(V))})})}.bind(o),o.mediaDevices.getUserMedia){const h=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(y){return l(y,S=>h(S).then(k=>{if(S.audio&&!k.getAudioTracks().length||S.video&&!k.getVideoTracks().length)throw k.getTracks().forEach(V=>{V.stop()}),new DOMException("","NotFoundError");return k},k=>Promise.reject(d(k))))}}}function ox(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function sx(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("ontrack"in A.RTCPeerConnection.prototype)){Object.defineProperty(A.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(o){this._ontrack&&this.removeEventListener("track",this._ontrack),this.addEventListener("track",this._ontrack=o)},enumerable:!0,configurable:!0});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=o=>{o.stream.addEventListener("addtrack",a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.track.id):{track:a.track};const d=new Event("track");d.track=a.track,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)}),o.stream.getTracks().forEach(a=>{let l;l=A.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(h=>h.track&&h.track.id===a.id):{track:a};const d=new Event("track");d.track=a,d.receiver=l,d.transceiver={receiver:l},d.streams=[o.stream],this.dispatchEvent(d)})},this.addEventListener("addstream",this._ontrackpoly)),e.apply(this,arguments)}}else jB(A,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function db(A){if(typeof A=="object"&&A.RTCPeerConnection&&!("getSenders"in A.RTCPeerConnection.prototype)&&"createDTMFSender"in A.RTCPeerConnection.prototype){const e=function(l,d){return{track:d,get dtmf(){return this._dtmf===void 0&&(d.kind==="audio"?this._dtmf=l.createDTMFSender(d):this._dtmf=null),this._dtmf},_pc:l}};if(!A.RTCPeerConnection.prototype.getSenders){A.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};const l=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(h,y){let S=l.apply(this,arguments);return S||(S=e(this,h),this._senders.push(S)),S};const d=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(h){d.apply(this,arguments);const y=this._senders.indexOf(h);y!==-1&&this._senders.splice(y,1)}}const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(l){this._senders=this._senders||[],o.apply(this,[l]),l.getTracks().forEach(d=>{this._senders.push(e(this,d))})};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(l){this._senders=this._senders||[],a.apply(this,[l]),l.getTracks().forEach(d=>{const h=this._senders.find(y=>y.track===d);h&&this._senders.splice(this._senders.indexOf(h),1)})}}else if(typeof A=="object"&&A.RTCPeerConnection&&"getSenders"in A.RTCPeerConnection.prototype&&"createDTMFSender"in A.RTCPeerConnection.prototype&&A.RTCRtpSender&&!("dtmf"in A.RTCRtpSender.prototype)){const e=A.RTCPeerConnection.prototype.getSenders;A.RTCPeerConnection.prototype.getSenders=function(){const o=e.apply(this,[]);return o.forEach(a=>a._pc=this),o},Object.defineProperty(A.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this.track.kind==="audio"?this._dtmf=this._pc.createDTMFSender(this.track):this._dtmf=null),this._dtmf}})}}function nx(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[o,a,l]=arguments;if(arguments.length>0&&typeof o=="function")return e.apply(this,arguments);if(e.length===0&&(arguments.length===0||typeof o!="function"))return e.apply(this,[]);const d=function(y){const S={};return y.result().forEach(k=>{const V={id:k.id,timestamp:k.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[k.type]||k.type};k.names().forEach(J=>{V[J]=k.stat(J)}),S[V.id]=V}),S},h=function(y){return new Map(Object.keys(y).map(S=>[S,y[S]]))};if(arguments.length>=2){const y=function(S){a(h(d(S)))};return e.apply(this,[y,o])}return new Promise((y,S)=>{e.apply(this,[function(k){y(h(d(k)))},S])}).then(a,l)}}function Cb(A){if(!(typeof A=="object"&&A.RTCPeerConnection&&A.RTCRtpSender&&A.RTCRtpReceiver))return;if(!("getStats"in A.RTCRtpSender.prototype)){const o=A.RTCPeerConnection.prototype.getSenders;o&&(A.RTCPeerConnection.prototype.getSenders=function(){const l=o.apply(this,[]);return l.forEach(d=>d._pc=this),l});const a=A.RTCPeerConnection.prototype.addTrack;a&&(A.RTCPeerConnection.prototype.addTrack=function(){const l=a.apply(this,arguments);return l._pc=this,l}),A.RTCRtpSender.prototype.getStats=function(){const l=this;return this._pc.getStats().then(d=>tx(d,l.track,!0))}}if(!("getStats"in A.RTCRtpReceiver.prototype)){const o=A.RTCPeerConnection.prototype.getReceivers;o&&(A.RTCPeerConnection.prototype.getReceivers=function(){const a=o.apply(this,[]);return a.forEach(l=>l._pc=this),a}),jB(A,"track",a=>(a.receiver._pc=a.srcElement,a)),A.RTCRtpReceiver.prototype.getStats=function(){const a=this;return this._pc.getStats().then(l=>tx(l,a.track,!1))}}if(!("getStats"in A.RTCRtpSender.prototype)||!("getStats"in A.RTCRtpReceiver.prototype))return;const e=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof A.MediaStreamTrack){const o=arguments[0];let a,l,d;return this.getSenders().forEach(h=>{h.track===o&&(a?d=!0:a=h)}),this.getReceivers().forEach(h=>(h.track===o&&(l?d=!0:l=h),h.track===o)),d||a&&l?Promise.reject(new DOMException("There are more than one sender or receiver for the track.","InvalidAccessError")):a?a.getStats():l?l.getStats():Promise.reject(new DOMException("There is no sender or receiver for the track.","InvalidAccessError"))}return e.apply(this,arguments)}}function rx(A){A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(d=>this._shimmedLocalStreams[d][0])};const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addTrack=function(d,h){if(!h)return e.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};const y=e.apply(this,arguments);return this._shimmedLocalStreams[h.id]?this._shimmedLocalStreams[h.id].indexOf(y)===-1&&this._shimmedLocalStreams[h.id].push(y):this._shimmedLocalStreams[h.id]=[h,y],y};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(S=>{if(this.getSenders().find(k=>k.track===S))throw new DOMException("Track already exists.","InvalidAccessError")});const h=this.getSenders();o.apply(this,arguments);const y=this.getSenders().filter(S=>h.indexOf(S)===-1);this._shimmedLocalStreams[d.id]=[d].concat(y)};const a=A.RTCPeerConnection.prototype.removeStream;A.RTCPeerConnection.prototype.removeStream=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[d.id],a.apply(this,arguments)};const l=A.RTCPeerConnection.prototype.removeTrack;A.RTCPeerConnection.prototype.removeTrack=function(d){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},d&&Object.keys(this._shimmedLocalStreams).forEach(h=>{const y=this._shimmedLocalStreams[h].indexOf(d);y!==-1&&this._shimmedLocalStreams[h].splice(y,1),this._shimmedLocalStreams[h].length===1&&delete this._shimmedLocalStreams[h]}),l.apply(this,arguments)}}function ax(A,e){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&e.version>=65)return rx(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const S=o.apply(this);return this._reverseStreams=this._reverseStreams||{},S.map(k=>this._reverseStreams[k.id])};const a=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(S){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},S.getTracks().forEach(k=>{if(this.getSenders().find(V=>V.track===k))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){const k=new A.MediaStream(S.getTracks());this._streams[S.id]=k,this._reverseStreams[k.id]=S,S=k}a.apply(this,[S])};const l=A.RTCPeerConnection.prototype.removeStream;function d(S,k){let V=k.sdp;return Object.keys(S._reverseStreams||[]).forEach(J=>{const cA=S._reverseStreams[J],CA=S._streams[cA.id];V=V.replace(new RegExp(CA.id,"g"),cA.id)}),new RTCSessionDescription({type:k.type,sdp:V})}A.RTCPeerConnection.prototype.removeStream=function(S){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},l.apply(this,[this._streams[S.id]||S]),delete this._reverseStreams[this._streams[S.id]?this._streams[S.id].id:S.id],delete this._streams[S.id]},A.RTCPeerConnection.prototype.addTrack=function(S,k){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");const V=[].slice.call(arguments,1);if(V.length!==1||!V[0].getTracks().find(cA=>cA===S))throw new DOMException("The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.","NotSupportedError");if(this.getSenders().find(cA=>cA.track===S))throw new DOMException("Track already exists.","InvalidAccessError");this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};const J=this._streams[k.id];if(J)J.addTrack(S),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const cA=new A.MediaStream([S]);this._streams[k.id]=cA,this._reverseStreams[cA.id]=k,this.addStream(cA)}return this.getSenders().find(cA=>cA.track===S)},["createOffer","createAnswer"].forEach(function(S){const k=A.RTCPeerConnection.prototype[S],V={[S](){const J=arguments;return arguments.length&&typeof arguments[0]=="function"?k.apply(this,[cA=>{const CA=d(this,cA);J[0].apply(null,[CA])},cA=>{J[1]&&J[1].apply(null,cA)},arguments[2]]):k.apply(this,arguments).then(cA=>d(this,cA))}};A.RTCPeerConnection.prototype[S]=V[S]});const h=A.RTCPeerConnection.prototype.setLocalDescription;A.RTCPeerConnection.prototype.setLocalDescription=function(){return arguments.length&&arguments[0].type?(arguments[0]=function(S,k){let V=k.sdp;return Object.keys(S._reverseStreams||[]).forEach(J=>{const cA=S._reverseStreams[J],CA=S._streams[cA.id];V=V.replace(new RegExp(cA.id,"g"),CA.id)}),new RTCSessionDescription({type:k.type,sdp:V})}(this,arguments[0]),h.apply(this,arguments)):h.apply(this,arguments)};const y=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const S=y.get.apply(this);return S.type===""?S:d(this,S)}}),A.RTCPeerConnection.prototype.removeTrack=function(S){if(this.signalingState==="closed")throw new DOMException("The RTCPeerConnection's signalingState is 'closed'.","InvalidStateError");if(!S._pc)throw new DOMException("Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.","TypeError");if(S._pc!==this)throw new DOMException("Sender was not created by this connection.","InvalidAccessError");let k;this._streams=this._streams||{},Object.keys(this._streams).forEach(V=>{this._streams[V].getTracks().find(J=>S.track===J)&&(k=this._streams[V])}),k&&(k.getTracks().length===1?this.removeStream(this._reverseStreams[k.id]):k.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function PS(A,e){!A.RTCPeerConnection&&A.webkitRTCPeerConnection&&(A.RTCPeerConnection=A.webkitRTCPeerConnection),A.RTCPeerConnection&&e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(o){const a=A.RTCPeerConnection.prototype[o],l={[o](){return arguments[0]=new(o==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),a.apply(this,arguments)}};A.RTCPeerConnection.prototype[o]=l[o]})}function gx(A,e){jB(A,"negotiationneeded",o=>{const a=o.target;if(!(e.version<72||a.getConfiguration&&a.getConfiguration().sdpSemantics==="plan-b")||a.signalingState==="stable")return o})}var hb=Object.freeze({__proto__:null,shimMediaStream:ox,shimOnTrack:sx,shimGetSendersWithDtmf:db,shimGetStats:nx,shimSenderReceiverGetStats:Cb,shimAddTrackRemoveTrackWithNative:rx,shimAddTrackRemoveTrack:ax,shimPeerConnection:PS,fixNegotiationNeeded:gx,shimGetUserMedia:ix,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(typeof e=="function"?A.navigator.mediaDevices.getDisplayMedia=function(o){return e(o).then(a=>{const l=o.video&&o.video.width,d=o.video&&o.video.height,h=o.video&&o.video.frameRate;return o.video={mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:a,maxFrameRate:h||3}},l&&(o.video.mandatory.maxWidth=l),d&&(o.video.mandatory.maxHeight=d),A.navigator.mediaDevices.getUserMedia(o)})}:console.error("shimGetDisplayMedia: getSourceId argument is not a function"))}});function cx(A,e){const o=A&&A.navigator,a=A&&A.MediaStreamTrack;if(o.getUserMedia=function(l,d,h){OS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(l).then(d,h)},!(e.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const l=function(h,y,S){y in h&&!(S in h)&&(h[S]=h[y],delete h[y])},d=o.mediaDevices.getUserMedia.bind(o.mediaDevices);if(o.mediaDevices.getUserMedia=function(h){return typeof h=="object"&&typeof h.audio=="object"&&(h=JSON.parse(JSON.stringify(h)),l(h.audio,"autoGainControl","mozAutoGainControl"),l(h.audio,"noiseSuppression","mozNoiseSuppression")),d(h)},a&&a.prototype.getSettings){const h=a.prototype.getSettings;a.prototype.getSettings=function(){const y=h.apply(this,arguments);return l(y,"mozAutoGainControl","autoGainControl"),l(y,"mozNoiseSuppression","noiseSuppression"),y}}if(a&&a.prototype.applyConstraints){const h=a.prototype.applyConstraints;a.prototype.applyConstraints=function(y){return this.kind==="audio"&&typeof y=="object"&&(y=JSON.parse(JSON.stringify(y)),l(y,"autoGainControl","mozAutoGainControl"),l(y,"noiseSuppression","mozNoiseSuppression")),h.apply(this,[y])}}}}function lx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function Ww(A,e){if(typeof A!="object"||!A.RTCPeerConnection&&!A.mozRTCPeerConnection)return;!A.RTCPeerConnection&&A.mozRTCPeerConnection&&(A.RTCPeerConnection=A.mozRTCPeerConnection),e.version<53&&["setLocalDescription","setRemoteDescription","addIceCandidate"].forEach(function(l){const d=A.RTCPeerConnection.prototype[l],h={[l](){return arguments[0]=new(l==="addIceCandidate"?A.RTCIceCandidate:A.RTCSessionDescription)(arguments[0]),d.apply(this,arguments)}};A.RTCPeerConnection.prototype[l]=h[l]});const o={inboundrtp:"inbound-rtp",outboundrtp:"outbound-rtp",candidatepair:"candidate-pair",localcandidate:"local-candidate",remotecandidate:"remote-candidate"},a=A.RTCPeerConnection.prototype.getStats;A.RTCPeerConnection.prototype.getStats=function(){const[l,d,h]=arguments;return a.apply(this,[l||null]).then(y=>{if(e.version<53&&!d)try{y.forEach(S=>{S.type=o[S.type]||S.type})}catch(S){if(S.name!=="TypeError")throw S;y.forEach((k,V)=>{y.set(V,Object.assign({},k,{type:o[k.type]||k.type}))})}return y}).then(d,h)}}function Ix(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpSender.prototype)return;const e=A.RTCPeerConnection.prototype.getSenders;e&&(A.RTCPeerConnection.prototype.getSenders=function(){const a=e.apply(this,[]);return a.forEach(l=>l._pc=this),a});const o=A.RTCPeerConnection.prototype.addTrack;o&&(A.RTCPeerConnection.prototype.addTrack=function(){const a=o.apply(this,arguments);return a._pc=this,a}),A.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function Bb(A){if(typeof A!="object"||!A.RTCPeerConnection||!A.RTCRtpSender||A.RTCRtpSender&&"getStats"in A.RTCRtpReceiver.prototype)return;const e=A.RTCPeerConnection.prototype.getReceivers;e&&(A.RTCPeerConnection.prototype.getReceivers=function(){const o=e.apply(this,[]);return o.forEach(a=>a._pc=this),o}),jB(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function ux(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(e){OS("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function Qb(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function Ex(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.addTransceiver;e&&(A.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let o=arguments[1]&&arguments[1].sendEncodings;o===void 0&&(o=[]),o=[...o];const a=o.length>0;a&&o.forEach(d=>{if("rid"in d&&!/^[a-z0-9]{0,16}$/i.test(d.rid))throw new TypeError("Invalid RID value provided.");if("scaleResolutionDownBy"in d&&!(parseFloat(d.scaleResolutionDownBy)>=1))throw new RangeError("scale_resolution_down_by must be >= 1.0");if("maxFramerate"in d&&!(parseFloat(d.maxFramerate)>=0))throw new RangeError("max_framerate must be >= 0.0")});const l=e.apply(this,arguments);if(a){const{sender:d}=l,h=d.getParameters();(!("encodings"in h)||h.encodings.length===1&&Object.keys(h.encodings[0]).length===0)&&(h.encodings=o,d.sendEncodings=o,this.setParametersPromises.push(d.setParameters(h).then(()=>{delete d.sendEncodings}).catch(()=>{delete d.sendEncodings})))}return l})}function dx(A){if(typeof A!="object"||!A.RTCRtpSender)return;const e=A.RTCRtpSender.prototype.getParameters;e&&(A.RTCRtpSender.prototype.getParameters=function(){const o=e.apply(this,arguments);return"encodings"in o||(o.encodings=[].concat(this.sendEncodings||[{}])),o})}function Cx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}function hx(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype.createAnswer;A.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>e.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):e.apply(this,arguments)}}var Bx=Object.freeze({__proto__:null,shimOnTrack:lx,shimPeerConnection:Ww,shimSenderGetStats:Ix,shimReceiverGetStats:Bb,shimRemoveStream:ux,shimRTCDataChannel:Qb,shimAddTransceiver:Ex,shimGetParameters:dx,shimCreateOffer:Cx,shimCreateAnswer:hx,shimGetUserMedia:cx,shimGetDisplayMedia:function(A,e){A.navigator.mediaDevices&&"getDisplayMedia"in A.navigator.mediaDevices||A.navigator.mediaDevices&&(A.navigator.mediaDevices.getDisplayMedia=function(o){if(!o||!o.video){const a=new DOMException("getDisplayMedia without video constraints is undefined");return a.name="NotFoundError",a.code=8,Promise.reject(a)}return o.video===!0?o.video={mediaSource:e}:o.video.mediaSource=e,A.navigator.mediaDevices.getUserMedia(o)})}});function Qx(A){if(typeof A=="object"&&A.RTCPeerConnection){if("getLocalStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||(this._localStreams=[]),this._localStreams}),!("addStream"in A.RTCPeerConnection.prototype)){const e=A.RTCPeerConnection.prototype.addTrack;A.RTCPeerConnection.prototype.addStream=function(o){this._localStreams||(this._localStreams=[]),this._localStreams.includes(o)||this._localStreams.push(o),o.getAudioTracks().forEach(a=>e.call(this,a,o)),o.getVideoTracks().forEach(a=>e.call(this,a,o))},A.RTCPeerConnection.prototype.addTrack=function(o,...a){return a&&a.forEach(l=>{this._localStreams?this._localStreams.includes(l)||this._localStreams.push(l):this._localStreams=[l]}),e.apply(this,arguments)}}"removeStream"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||(this._localStreams=[]);const o=this._localStreams.indexOf(e);if(o===-1)return;this._localStreams.splice(o,1);const a=e.getTracks();this.getSenders().forEach(l=>{a.includes(l.track)&&this.removeTrack(l)})})}}function px(A){if(typeof A=="object"&&A.RTCPeerConnection&&("getRemoteStreams"in A.RTCPeerConnection.prototype||(A.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!("onaddstream"in A.RTCPeerConnection.prototype))){Object.defineProperty(A.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(o){this._onaddstream&&(this.removeEventListener("addstream",this._onaddstream),this.removeEventListener("track",this._onaddstreampoly)),this.addEventListener("addstream",this._onaddstream=o),this.addEventListener("track",this._onaddstreampoly=a=>{a.streams.forEach(l=>{if(this._remoteStreams||(this._remoteStreams=[]),this._remoteStreams.includes(l))return;this._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,this.dispatchEvent(d)})})}});const e=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){const o=this;return this._onaddstreampoly||this.addEventListener("track",this._onaddstreampoly=function(a){a.streams.forEach(l=>{if(o._remoteStreams||(o._remoteStreams=[]),o._remoteStreams.indexOf(l)>=0)return;o._remoteStreams.push(l);const d=new Event("addstream");d.stream=l,o.dispatchEvent(d)})}),e.apply(o,arguments)}}}function pb(A){if(typeof A!="object"||!A.RTCPeerConnection)return;const e=A.RTCPeerConnection.prototype,o=e.createOffer,a=e.createAnswer,l=e.setLocalDescription,d=e.setRemoteDescription,h=e.addIceCandidate;e.createOffer=function(S,k){const V=arguments.length>=2?arguments[2]:arguments[0],J=o.apply(this,[V]);return k?(J.then(S,k),Promise.resolve()):J},e.createAnswer=function(S,k){const V=arguments.length>=2?arguments[2]:arguments[0],J=a.apply(this,[V]);return k?(J.then(S,k),Promise.resolve()):J};let y=function(S,k,V){const J=l.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J};e.setLocalDescription=y,y=function(S,k,V){const J=d.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J},e.setRemoteDescription=y,y=function(S,k,V){const J=h.apply(this,[S]);return V?(J.then(k,V),Promise.resolve()):J},e.addIceCandidate=y}function mb(A){const e=A&&A.navigator;if(e.mediaDevices&&e.mediaDevices.getUserMedia){const o=e.mediaDevices,a=o.getUserMedia.bind(o);e.mediaDevices.getUserMedia=l=>a(mx(l))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(o,a,l){e.mediaDevices.getUserMedia(o).then(a,l)}.bind(e))}function mx(A){return A&&A.video!==void 0?Object.assign({},A,{video:Ib(A.video)}):A}function fx(A){if(!A.RTCPeerConnection)return;const e=A.RTCPeerConnection;A.RTCPeerConnection=function(o,a){if(o&&o.iceServers){const l=[];for(let d=0;de.generateCertificate})}function yx(A){typeof A=="object"&&A.RTCTrackEvent&&"receiver"in A.RTCTrackEvent.prototype&&!("transceiver"in A.RTCTrackEvent.prototype)&&Object.defineProperty(A.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function zw(A){const e=A.RTCPeerConnection.prototype.createOffer;A.RTCPeerConnection.prototype.createOffer=function(o){if(o){o.offerToReceiveAudio!==void 0&&(o.offerToReceiveAudio=!!o.offerToReceiveAudio);const a=this.getTransceivers().find(d=>d.receiver.track.kind==="audio");o.offerToReceiveAudio===!1&&a?a.direction==="sendrecv"?a.setDirection?a.setDirection("sendonly"):a.direction="sendonly":a.direction==="recvonly"&&(a.setDirection?a.setDirection("inactive"):a.direction="inactive"):o.offerToReceiveAudio!==!0||a||this.addTransceiver("audio",{direction:"recvonly"}),o.offerToReceiveVideo!==void 0&&(o.offerToReceiveVideo=!!o.offerToReceiveVideo);const l=this.getTransceivers().find(d=>d.receiver.track.kind==="video");o.offerToReceiveVideo===!1&&l?l.direction==="sendrecv"?l.setDirection?l.setDirection("sendonly"):l.direction="sendonly":l.direction==="recvonly"&&(l.setDirection?l.setDirection("inactive"):l.direction="inactive"):o.offerToReceiveVideo!==!0||l||this.addTransceiver("video",{direction:"recvonly"})}return e.apply(this,arguments)}}function Dx(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var Sx=Object.freeze({__proto__:null,shimLocalStreamsAPI:Qx,shimRemoteStreamsAPI:px,shimCallbacksAPI:pb,shimGetUserMedia:mb,shimConstraints:mx,shimRTCIceServerUrls:fx,shimTrackEventTransceiver:yx,shimCreateOfferLegacy:zw,shimAudioContext:Dx}),Mx={exports:{}};(function(A){const e={generateIdentifier:function(){return Math.random().toString(36).substring(2,12)}};e.localCName=e.generateIdentifier(),e.splitLines=function(o){return o.trim().split(` `).map(a=>a.trim())},e.splitSections=function(o){return o.split(` -m=`).map((a,c)=>(c>0?"m="+a:a).trim()+`\r -`)},e.getDescription=function(o){const a=e.splitSections(o);return a&&a[0]},e.getMediaSections=function(o){const a=e.splitSections(o);return a.shift(),a},e.matchPrefix=function(o,a){return e.splitLines(o).filter(c=>c.indexOf(a)===0)},e.parseCandidate=function(o){let a;a=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" ");const c={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let d=8;d(l>0?"m="+a:a).trim()+`\r +`)},e.getDescription=function(o){const a=e.splitSections(o);return a&&a[0]},e.getMediaSections=function(o){const a=e.splitSections(o);return a.shift(),a},e.matchPrefix=function(o,a){return e.splitLines(o).filter(l=>l.indexOf(a)===0)},e.parseCandidate=function(o){let a;a=o.indexOf("a=candidate:")===0?o.substring(12).split(" "):o.substring(10).split(" ");const l={foundation:a[0],component:{1:"rtp",2:"rtcp"}[a[1]]||a[1],protocol:a[2].toLowerCase(),priority:parseInt(a[3],10),ip:a[4],address:a[4],port:parseInt(a[5],10),type:a[7]};for(let d=8;d0?a[0].split("/")[1]:"sendrecv",uri:a[1],attributes:a.slice(2).join(" ")}},e.writeExtmap=function(o){return"a=extmap:"+(o.id||o.preferredId)+(o.direction&&o.direction!=="sendrecv"?"/"+o.direction:"")+" "+o.uri+(o.attributes?" "+o.attributes:"")+`\r -`},e.parseFmtp=function(o){const a={};let c;const d=o.substring(o.indexOf(" ")+1).split(";");for(let C=0;C{o.parameters[C]!==void 0?d.push(C+"="+o.parameters[C]):d.push(C)}),a+="a=fmtp:"+c+" "+d.join(";")+`\r -`}return a},e.parseRtcpFb=function(o){const a=o.substring(o.indexOf(" ")+1).split(" ");return{type:a.shift(),parameter:a.join(" ")}},e.writeRtcpFb=function(o){let a="",c=o.payloadType;return o.preferredPayloadType!==void 0&&(c=o.preferredPayloadType),o.rtcpFeedback&&o.rtcpFeedback.length&&o.rtcpFeedback.forEach(d=>{a+="a=rtcp-fb:"+c+" "+d.type+(d.parameter&&d.parameter.length?" "+d.parameter:"")+`\r -`}),a},e.parseSsrcMedia=function(o){const a=o.indexOf(" "),c={ssrc:parseInt(o.substring(7,a),10)},d=o.indexOf(":",a);return d>-1?(c.attribute=o.substring(a+1,d),c.value=o.substring(d+1)):c.attribute=o.substring(a+1),c},e.parseSsrcGroup=function(o){const a=o.substring(13).split(" ");return{semantics:a.shift(),ssrcs:a.map(c=>parseInt(c,10))}},e.getMid=function(o){const a=e.matchPrefix(o,"a=mid:")[0];if(a)return a.substring(6)},e.parseFingerprint=function(o){const a=o.substring(14).split(" ");return{algorithm:a[0].toLowerCase(),value:a[1].toUpperCase()}},e.getDtlsParameters=function(o,a){return{role:"auto",fingerprints:e.matchPrefix(o+a,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(o,a){let c="a=setup:"+a+`\r -`;return o.fingerprints.forEach(d=>{c+="a=fingerprint:"+d.algorithm+" "+d.value+`\r -`}),c},e.parseCryptoLine=function(o){const a=o.substring(9).split(" ");return{tag:parseInt(a[0],10),cryptoSuite:a[1],keyParams:a[2],sessionParams:a.slice(3)}},e.writeCryptoLine=function(o){return"a=crypto:"+o.tag+" "+o.cryptoSuite+" "+(typeof o.keyParams=="object"?e.writeCryptoKeyParams(o.keyParams):o.keyParams)+(o.sessionParams?" "+o.sessionParams.join(" "):"")+`\r -`},e.parseCryptoKeyParams=function(o){if(o.indexOf("inline:")!==0)return null;const a=o.substring(7).split("|");return{keyMethod:"inline",keySalt:a[0],lifeTime:a[1],mkiValue:a[2]?a[2].split(":")[0]:void 0,mkiLength:a[2]?a[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(o){return o.keyMethod+":"+o.keySalt+(o.lifeTime?"|"+o.lifeTime:"")+(o.mkiValue&&o.mkiLength?"|"+o.mkiValue+":"+o.mkiLength:"")},e.getCryptoParameters=function(o,a){return e.matchPrefix(o+a,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(o,a){const c=e.matchPrefix(o+a,"a=ice-ufrag:")[0],d=e.matchPrefix(o+a,"a=ice-pwd:")[0];return c&&d?{usernameFragment:c.substring(12),password:d.substring(10)}:null},e.writeIceParameters=function(o){let a="a=ice-ufrag:"+o.usernameFragment+`\r +`},e.parseFmtp=function(o){const a={};let l;const d=o.substring(o.indexOf(" ")+1).split(";");for(let h=0;h{o.parameters[h]!==void 0?d.push(h+"="+o.parameters[h]):d.push(h)}),a+="a=fmtp:"+l+" "+d.join(";")+`\r +`}return a},e.parseRtcpFb=function(o){const a=o.substring(o.indexOf(" ")+1).split(" ");return{type:a.shift(),parameter:a.join(" ")}},e.writeRtcpFb=function(o){let a="",l=o.payloadType;return o.preferredPayloadType!==void 0&&(l=o.preferredPayloadType),o.rtcpFeedback&&o.rtcpFeedback.length&&o.rtcpFeedback.forEach(d=>{a+="a=rtcp-fb:"+l+" "+d.type+(d.parameter&&d.parameter.length?" "+d.parameter:"")+`\r +`}),a},e.parseSsrcMedia=function(o){const a=o.indexOf(" "),l={ssrc:parseInt(o.substring(7,a),10)},d=o.indexOf(":",a);return d>-1?(l.attribute=o.substring(a+1,d),l.value=o.substring(d+1)):l.attribute=o.substring(a+1),l},e.parseSsrcGroup=function(o){const a=o.substring(13).split(" ");return{semantics:a.shift(),ssrcs:a.map(l=>parseInt(l,10))}},e.getMid=function(o){const a=e.matchPrefix(o,"a=mid:")[0];if(a)return a.substring(6)},e.parseFingerprint=function(o){const a=o.substring(14).split(" ");return{algorithm:a[0].toLowerCase(),value:a[1].toUpperCase()}},e.getDtlsParameters=function(o,a){return{role:"auto",fingerprints:e.matchPrefix(o+a,"a=fingerprint:").map(e.parseFingerprint)}},e.writeDtlsParameters=function(o,a){let l="a=setup:"+a+`\r +`;return o.fingerprints.forEach(d=>{l+="a=fingerprint:"+d.algorithm+" "+d.value+`\r +`}),l},e.parseCryptoLine=function(o){const a=o.substring(9).split(" ");return{tag:parseInt(a[0],10),cryptoSuite:a[1],keyParams:a[2],sessionParams:a.slice(3)}},e.writeCryptoLine=function(o){return"a=crypto:"+o.tag+" "+o.cryptoSuite+" "+(typeof o.keyParams=="object"?e.writeCryptoKeyParams(o.keyParams):o.keyParams)+(o.sessionParams?" "+o.sessionParams.join(" "):"")+`\r +`},e.parseCryptoKeyParams=function(o){if(o.indexOf("inline:")!==0)return null;const a=o.substring(7).split("|");return{keyMethod:"inline",keySalt:a[0],lifeTime:a[1],mkiValue:a[2]?a[2].split(":")[0]:void 0,mkiLength:a[2]?a[2].split(":")[1]:void 0}},e.writeCryptoKeyParams=function(o){return o.keyMethod+":"+o.keySalt+(o.lifeTime?"|"+o.lifeTime:"")+(o.mkiValue&&o.mkiLength?"|"+o.mkiValue+":"+o.mkiLength:"")},e.getCryptoParameters=function(o,a){return e.matchPrefix(o+a,"a=crypto:").map(e.parseCryptoLine)},e.getIceParameters=function(o,a){const l=e.matchPrefix(o+a,"a=ice-ufrag:")[0],d=e.matchPrefix(o+a,"a=ice-pwd:")[0];return l&&d?{usernameFragment:l.substring(12),password:d.substring(10)}:null},e.writeIceParameters=function(o){let a="a=ice-ufrag:"+o.usernameFragment+`\r a=ice-pwd:`+o.password+`\r `;return o.iceLite&&(a+=`a=ice-lite\r -`),a},e.parseRtpParameters=function(o){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},c=e.splitLines(o)[0].split(" ");a.profile=c[2];for(let C=3;C{a.headerExtensions.push(e.parseExtmap(C))});const d=e.matchPrefix(o,"a=rtcp-fb:* ").map(e.parseRtcpFb);return a.codecs.forEach(C=>{d.forEach(y=>{C.rtcpFeedback.find(S=>S.type===y.type&&S.parameter===y.parameter)||C.rtcpFeedback.push(y)})}),a},e.writeRtpDescription=function(o,a){let c="";c+="m="+o+" ",c+=a.codecs.length>0?"9":"0",c+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",c+=a.codecs.map(C=>C.preferredPayloadType!==void 0?C.preferredPayloadType:C.payloadType).join(" ")+`\r -`,c+=`c=IN IP4 0.0.0.0\r -`,c+=`a=rtcp:9 IN IP4 0.0.0.0\r -`,a.codecs.forEach(C=>{c+=e.writeRtpMap(C),c+=e.writeFmtp(C),c+=e.writeRtcpFb(C)});let d=0;return a.codecs.forEach(C=>{C.maxptime>d&&(d=C.maxptime)}),d>0&&(c+="a=maxptime:"+d+`\r -`),a.headerExtensions&&a.headerExtensions.forEach(C=>{c+=e.writeExtmap(C)}),c},e.parseRtpEncodingParameters=function(o){const a=[],c=e.parseRtpParameters(o),d=c.fecMechanisms.indexOf("RED")!==-1,C=c.fecMechanisms.indexOf("ULPFEC")!==-1,y=e.matchPrefix(o,"a=ssrc:").map(gA=>e.parseSsrcMedia(gA)).filter(gA=>gA.attribute==="cname"),S=y.length>0&&y[0].ssrc;let k;const V=e.matchPrefix(o,"a=ssrc-group:FID").map(gA=>gA.substring(17).split(" ").map(CA=>parseInt(CA,10)));V.length>0&&V[0].length>1&&V[0][0]===S&&(k=V[0][1]),c.codecs.forEach(gA=>{if(gA.name.toUpperCase()==="RTX"&&gA.parameters.apt){let CA={ssrc:S,codecPayloadType:parseInt(gA.parameters.apt,10)};S&&k&&(CA.rtx={ssrc:k}),a.push(CA),d&&(CA=JSON.parse(JSON.stringify(CA)),CA.fec={ssrc:S,mechanism:C?"red+ulpfec":"red"},a.push(CA))}}),a.length===0&&S&&a.push({ssrc:S});let J=e.matchPrefix(o,"b=");return J.length&&(J=J[0].indexOf("b=TIAS:")===0?parseInt(J[0].substring(7),10):J[0].indexOf("b=AS:")===0?1e3*parseInt(J[0].substring(5),10)*.95-16e3:void 0,a.forEach(gA=>{gA.maxBitrate=J})),a},e.parseRtcpParameters=function(o){const a={},c=e.matchPrefix(o,"a=ssrc:").map(y=>e.parseSsrcMedia(y)).filter(y=>y.attribute==="cname")[0];c&&(a.cname=c.value,a.ssrc=c.ssrc);const d=e.matchPrefix(o,"a=rtcp-rsize");a.reducedSize=d.length>0,a.compound=d.length===0;const C=e.matchPrefix(o,"a=rtcp-mux");return a.mux=C.length>0,a},e.writeRtcpParameters=function(o){let a="";return o.reducedSize&&(a+=`a=rtcp-rsize\r +`),a},e.parseRtpParameters=function(o){const a={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},l=e.splitLines(o)[0].split(" ");a.profile=l[2];for(let h=3;h{a.headerExtensions.push(e.parseExtmap(h))});const d=e.matchPrefix(o,"a=rtcp-fb:* ").map(e.parseRtcpFb);return a.codecs.forEach(h=>{d.forEach(y=>{h.rtcpFeedback.find(S=>S.type===y.type&&S.parameter===y.parameter)||h.rtcpFeedback.push(y)})}),a},e.writeRtpDescription=function(o,a){let l="";l+="m="+o+" ",l+=a.codecs.length>0?"9":"0",l+=" "+(a.profile||"UDP/TLS/RTP/SAVPF")+" ",l+=a.codecs.map(h=>h.preferredPayloadType!==void 0?h.preferredPayloadType:h.payloadType).join(" ")+`\r +`,l+=`c=IN IP4 0.0.0.0\r +`,l+=`a=rtcp:9 IN IP4 0.0.0.0\r +`,a.codecs.forEach(h=>{l+=e.writeRtpMap(h),l+=e.writeFmtp(h),l+=e.writeRtcpFb(h)});let d=0;return a.codecs.forEach(h=>{h.maxptime>d&&(d=h.maxptime)}),d>0&&(l+="a=maxptime:"+d+`\r +`),a.headerExtensions&&a.headerExtensions.forEach(h=>{l+=e.writeExtmap(h)}),l},e.parseRtpEncodingParameters=function(o){const a=[],l=e.parseRtpParameters(o),d=l.fecMechanisms.indexOf("RED")!==-1,h=l.fecMechanisms.indexOf("ULPFEC")!==-1,y=e.matchPrefix(o,"a=ssrc:").map(cA=>e.parseSsrcMedia(cA)).filter(cA=>cA.attribute==="cname"),S=y.length>0&&y[0].ssrc;let k;const V=e.matchPrefix(o,"a=ssrc-group:FID").map(cA=>cA.substring(17).split(" ").map(CA=>parseInt(CA,10)));V.length>0&&V[0].length>1&&V[0][0]===S&&(k=V[0][1]),l.codecs.forEach(cA=>{if(cA.name.toUpperCase()==="RTX"&&cA.parameters.apt){let CA={ssrc:S,codecPayloadType:parseInt(cA.parameters.apt,10)};S&&k&&(CA.rtx={ssrc:k}),a.push(CA),d&&(CA=JSON.parse(JSON.stringify(CA)),CA.fec={ssrc:S,mechanism:h?"red+ulpfec":"red"},a.push(CA))}}),a.length===0&&S&&a.push({ssrc:S});let J=e.matchPrefix(o,"b=");return J.length&&(J=J[0].indexOf("b=TIAS:")===0?parseInt(J[0].substring(7),10):J[0].indexOf("b=AS:")===0?1e3*parseInt(J[0].substring(5),10)*.95-16e3:void 0,a.forEach(cA=>{cA.maxBitrate=J})),a},e.parseRtcpParameters=function(o){const a={},l=e.matchPrefix(o,"a=ssrc:").map(y=>e.parseSsrcMedia(y)).filter(y=>y.attribute==="cname")[0];l&&(a.cname=l.value,a.ssrc=l.ssrc);const d=e.matchPrefix(o,"a=rtcp-rsize");a.reducedSize=d.length>0,a.compound=d.length===0;const h=e.matchPrefix(o,"a=rtcp-mux");return a.mux=h.length>0,a},e.writeRtcpParameters=function(o){let a="";return o.reducedSize&&(a+=`a=rtcp-rsize\r `),o.mux&&(a+=`a=rtcp-mux\r `),o.ssrc!==void 0&&o.cname&&(a+="a=ssrc:"+o.ssrc+" cname:"+o.cname+`\r -`),a},e.parseMsid=function(o){let a;const c=e.matchPrefix(o,"a=msid:");if(c.length===1)return a=c[0].substring(7).split(" "),{stream:a[0],track:a[1]};const d=e.matchPrefix(o,"a=ssrc:").map(C=>e.parseSsrcMedia(C)).filter(C=>C.attribute==="msid");return d.length>0?(a=d[0].value.split(" "),{stream:a[0],track:a[1]}):void 0},e.parseSctpDescription=function(o){const a=e.parseMLine(o),c=e.matchPrefix(o,"a=max-message-size:");let d;c.length>0&&(d=parseInt(c[0].substring(19),10)),isNaN(d)&&(d=65536);const C=e.matchPrefix(o,"a=sctp-port:");if(C.length>0)return{port:parseInt(C[0].substring(12),10),protocol:a.fmt,maxMessageSize:d};const y=e.matchPrefix(o,"a=sctpmap:");if(y.length>0){const S=y[0].substring(10).split(" ");return{port:parseInt(S[0],10),protocol:S[1],maxMessageSize:d}}},e.writeSctpDescription=function(o,a){let c=[];return c=o.protocol!=="DTLS/SCTP"?["m="+o.kind+" 9 "+o.protocol+" "+a.protocol+`\r +`),a},e.parseMsid=function(o){let a;const l=e.matchPrefix(o,"a=msid:");if(l.length===1)return a=l[0].substring(7).split(" "),{stream:a[0],track:a[1]};const d=e.matchPrefix(o,"a=ssrc:").map(h=>e.parseSsrcMedia(h)).filter(h=>h.attribute==="msid");return d.length>0?(a=d[0].value.split(" "),{stream:a[0],track:a[1]}):void 0},e.parseSctpDescription=function(o){const a=e.parseMLine(o),l=e.matchPrefix(o,"a=max-message-size:");let d;l.length>0&&(d=parseInt(l[0].substring(19),10)),isNaN(d)&&(d=65536);const h=e.matchPrefix(o,"a=sctp-port:");if(h.length>0)return{port:parseInt(h[0].substring(12),10),protocol:a.fmt,maxMessageSize:d};const y=e.matchPrefix(o,"a=sctpmap:");if(y.length>0){const S=y[0].substring(10).split(" ");return{port:parseInt(S[0],10),protocol:S[1],maxMessageSize:d}}},e.writeSctpDescription=function(o,a){let l=[];return l=o.protocol!=="DTLS/SCTP"?["m="+o.kind+" 9 "+o.protocol+" "+a.protocol+`\r `,`c=IN IP4 0.0.0.0\r `,"a=sctp-port:"+a.port+`\r `]:["m="+o.kind+" 9 "+o.protocol+" "+a.port+`\r `,`c=IN IP4 0.0.0.0\r `,"a=sctpmap:"+a.port+" "+a.protocol+` 65535\r -`],a.maxMessageSize!==void 0&&c.push("a=max-message-size:"+a.maxMessageSize+`\r -`),c.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(o,a,c){let d;const C=a!==void 0?a:2;return d=o||e.generateSessionId(),`v=0\r -o=`+(c||"thisisadapterortc")+" "+d+" "+C+` IN IP4 127.0.0.1\r +`],a.maxMessageSize!==void 0&&l.push("a=max-message-size:"+a.maxMessageSize+`\r +`),l.join("")},e.generateSessionId=function(){return Math.random().toString().substr(2,22)},e.writeSessionBoilerplate=function(o,a,l){let d;const h=a!==void 0?a:2;return d=o||e.generateSessionId(),`v=0\r +o=`+(l||"thisisadapterortc")+" "+d+" "+h+` IN IP4 127.0.0.1\r s=-\r t=0 0\r -`},e.getDirection=function(o,a){const c=e.splitLines(o);for(let d=0;d(o.candidate&&Object.defineProperty(o,"candidate",{value:new A.RTCIceCandidate(o.candidate),writable:"false"}),o))}function Cb(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||HB(A,"icecandidate",e=>{if(e.candidate){const o=Jd.parseCandidate(e.candidate.candidate);o.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return e})}function FS(A,e){if(!A.RTCPeerConnection)return;"sctp"in A.RTCPeerConnection.prototype||Object.defineProperty(A.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(a){if(!a||!a.sdp)return!1;const c=Jd.splitSections(a.sdp);return c.shift(),c.some(d=>{const C=Jd.parseMLine(d);return C&&C.kind==="application"&&C.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const a=function(S){const k=S.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(k===null||k.length<2)return-1;const V=parseInt(k[1],10);return V!=V?-1:V}(arguments[0]),c=function(S){let k=65536;return e.browser==="firefox"&&(k=e.version<57?S===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),k}(a),d=function(S,k){let V=65536;e.browser==="firefox"&&e.version===57&&(V=65535);const J=Jd.matchPrefix(S.sdp,"a=max-message-size:");return J.length>0?V=parseInt(J[0].substring(19),10):e.browser==="firefox"&&k!==-1&&(V=2147483637),V}(arguments[0],a);let C;C=c===0&&d===0?Number.POSITIVE_INFINITY:c===0||d===0?Math.max(c,d):Math.min(c,d);const y={};Object.defineProperty(y,"maxMessageSize",{get:()=>C}),this._sctp=y}return o.apply(this,arguments)}}function Ww(A){if(!A.RTCPeerConnection||!("createDataChannel"in A.RTCPeerConnection.prototype))return;function e(a,c){const d=a.send;a.send=function(){const C=arguments[0],y=C.length||C.size||C.byteLength;if(a.readyState==="open"&&c.sctp&&y>c.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+c.sctp.maxMessageSize+" bytes)");return d.apply(a,arguments)}}const o=A.RTCPeerConnection.prototype.createDataChannel;A.RTCPeerConnection.prototype.createDataChannel=function(){const a=o.apply(this,arguments);return e(a,this),a},HB(A,"datachannel",a=>(e(a.channel,a.target),a))}function hb(A){if(!A.RTCPeerConnection||"connectionState"in A.RTCPeerConnection.prototype)return;const e=A.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(o){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),o&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=o)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(o=>{const a=e[o];e[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=c=>{const d=c.target;if(d._lastConnectionState!==d.connectionState){d._lastConnectionState=d.connectionState;const C=new Event("connectionstatechange",c);d.dispatchEvent(C)}return c},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),a.apply(this,arguments)}})}function zw(A,e){if(!A.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(a){if(a&&a.sdp&&a.sdp.indexOf(` -a=extmap-allow-mixed`)!==-1){const c=a.sdp.split(` +`},e.getDirection=function(o,a){const l=e.splitLines(o);for(let d=0;d(o.candidate&&Object.defineProperty(o,"candidate",{value:new A.RTCIceCandidate(o.candidate),writable:"false"}),o))}function fb(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||jB(A,"icecandidate",e=>{if(e.candidate){const o=Jd.parseCandidate(e.candidate.candidate);o.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return e})}function xS(A,e){if(!A.RTCPeerConnection)return;"sctp"in A.RTCPeerConnection.prototype||Object.defineProperty(A.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,e.browser==="chrome"&&e.version>=76){const{sdpSemantics:a}=this.getConfiguration();a==="plan-b"&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0})}if(function(a){if(!a||!a.sdp)return!1;const l=Jd.splitSections(a.sdp);return l.shift(),l.some(d=>{const h=Jd.parseMLine(d);return h&&h.kind==="application"&&h.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const a=function(S){const k=S.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(k===null||k.length<2)return-1;const V=parseInt(k[1],10);return V!=V?-1:V}(arguments[0]),l=function(S){let k=65536;return e.browser==="firefox"&&(k=e.version<57?S===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),k}(a),d=function(S,k){let V=65536;e.browser==="firefox"&&e.version===57&&(V=65535);const J=Jd.matchPrefix(S.sdp,"a=max-message-size:");return J.length>0?V=parseInt(J[0].substring(19),10):e.browser==="firefox"&&k!==-1&&(V=2147483637),V}(arguments[0],a);let h;h=l===0&&d===0?Number.POSITIVE_INFINITY:l===0||d===0?Math.max(l,d):Math.min(l,d);const y={};Object.defineProperty(y,"maxMessageSize",{get:()=>h}),this._sctp=y}return o.apply(this,arguments)}}function Xw(A){if(!A.RTCPeerConnection||!("createDataChannel"in A.RTCPeerConnection.prototype))return;function e(a,l){const d=a.send;a.send=function(){const h=arguments[0],y=h.length||h.size||h.byteLength;if(a.readyState==="open"&&l.sctp&&y>l.sctp.maxMessageSize)throw new TypeError("Message too large (can send a maximum of "+l.sctp.maxMessageSize+" bytes)");return d.apply(a,arguments)}}const o=A.RTCPeerConnection.prototype.createDataChannel;A.RTCPeerConnection.prototype.createDataChannel=function(){const a=o.apply(this,arguments);return e(a,this),a},jB(A,"datachannel",a=>(e(a.channel,a.target),a))}function yb(A){if(!A.RTCPeerConnection||"connectionState"in A.RTCPeerConnection.prototype)return;const e=A.RTCPeerConnection.prototype;Object.defineProperty(e,"connectionState",{get(){return{completed:"connected",checking:"connecting"}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(e,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(o){this._onconnectionstatechange&&(this.removeEventListener("connectionstatechange",this._onconnectionstatechange),delete this._onconnectionstatechange),o&&this.addEventListener("connectionstatechange",this._onconnectionstatechange=o)},enumerable:!0,configurable:!0}),["setLocalDescription","setRemoteDescription"].forEach(o=>{const a=e[o];e[o]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=l=>{const d=l.target;if(d._lastConnectionState!==d.connectionState){d._lastConnectionState=d.connectionState;const h=new Event("connectionstatechange",l);d.dispatchEvent(h)}return l},this.addEventListener("iceconnectionstatechange",this._connectionstatechangepoly)),a.apply(this,arguments)}})}function $w(A,e){if(!A.RTCPeerConnection||e.browser==="chrome"&&e.version>=71||e.browser==="safari"&&e._safariVersion>=13.1)return;const o=A.RTCPeerConnection.prototype.setRemoteDescription;A.RTCPeerConnection.prototype.setRemoteDescription=function(a){if(a&&a.sdp&&a.sdp.indexOf(` +a=extmap-allow-mixed`)!==-1){const l=a.sdp.split(` `).filter(d=>d.trim()!=="a=extmap-allow-mixed").join(` -`);A.RTCSessionDescription&&a instanceof A.RTCSessionDescription?arguments[0]=new A.RTCSessionDescription({type:a.type,sdp:c}):a.sdp=c}return o.apply(this,arguments)}}function Zw(A,e){if(!A.RTCPeerConnection||!A.RTCPeerConnection.prototype)return;const o=A.RTCPeerConnection.prototype.addIceCandidate;o&&o.length!==0&&(A.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(e.browser==="chrome"&&e.version<78||e.browser==="firefox"&&e.version<68||e.browser==="safari")&&arguments[0]&&arguments[0].candidate===""?Promise.resolve():o.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function Xw(A,e){if(!A.RTCPeerConnection||!A.RTCPeerConnection.prototype)return;const o=A.RTCPeerConnection.prototype.setLocalDescription;o&&o.length!==0&&(A.RTCPeerConnection.prototype.setLocalDescription=function(){let a=arguments[0]||{};if(typeof a!="object"||a.type&&a.sdp)return o.apply(this,arguments);if(a={type:a.type,sdp:a.sdp},!a.type)switch(this.signalingState){case"stable":case"have-local-offer":case"have-remote-pranswer":a.type="offer";break;default:a.type="answer"}return a.sdp||a.type!=="offer"&&a.type!=="answer"?o.apply(this,[a]):(a.type==="offer"?this.createOffer:this.createAnswer).apply(this).then(c=>o.apply(this,[c]))})}var Xq=Object.freeze({__proto__:null,shimRTCIceCandidate:jw,shimRTCIceCandidateRelayProtocol:Cb,shimMaxMessageSize:FS,shimSendThrowTypeError:Ww,shimConnectionState:hb,removeExtmapAllowMixed:zw,shimAddIceCandidateNullOrEmpty:Zw,shimParameterlessSetLocalDescription:Xw});(function({window:A}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=Hw,a=function(d){const C={browser:null,version:null};if(d===void 0||!d.navigator||!d.navigator.userAgent)return C.browser="Not a browser.",C;const{navigator:y}=d;if(y.mozGetUserMedia)C.browser="firefox",C.version=parseInt(kS(y.userAgent,/Firefox\/(\d+)\./,1));else if(y.webkitGetUserMedia||d.isSecureContext===!1&&d.webkitRTCPeerConnection)C.browser="chrome",C.version=parseInt(kS(y.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!d.RTCPeerConnection||!y.userAgent.match(/AppleWebKit\/(\d+)\./))return C.browser="Not a supported browser.",C;C.browser="safari",C.version=parseInt(kS(y.userAgent,/AppleWebKit\/(\d+)\./,1)),C.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype,C._safariVersion=kS(y.userAgent,/Version\/(\d+(\.?\d+))/,1)}return C}(A),c={browserDetails:a,commonShim:Xq,extractVersion:kS,disableLog:HP,disableWarnings:Zq,sdp:Bx};switch(a.browser){case"chrome":if(!lb||!US||!e.shimChrome)return o("Chrome shim is not included in this adapter release."),c;if(a.version===null)return o("Chrome shim can not determine version, not shimming."),c;o("adapter.js shimming chrome."),c.browserShim=lb,Zw(A,a),Xw(A),KP(A,a),jP(A),US(A,a),WP(A),XP(A,a),gb(A),zP(A),cb(A),$P(A,a),jw(A),Cb(A),hb(A),FS(A,a),Ww(A),zw(A,a);break;case"firefox":if(!ax||!qw||!e.shimFirefox)return o("Firefox shim is not included in this adapter release."),c;o("adapter.js shimming firefox."),c.browserShim=ax,Zw(A,a),Xw(A),Ax(A,a),qw(A,a),ex(A),ix(A),tx(A),Ib(A),ub(A),ox(A),sx(A),nx(A),rx(A),jw(A),hb(A),FS(A,a),Ww(A);break;case"safari":if(!dx||!e.shimSafari)return o("Safari shim is not included in this adapter release."),c;o("adapter.js shimming safari."),c.browserShim=dx,Zw(A,a),Xw(A),Ix(A),Kw(A),Eb(A),gx(A),cx(A),ux(A),db(A),Ex(A),jw(A),Cb(A),FS(A,a),Ww(A),zw(A,a);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var co,Qx=Object.create,OS=Object.defineProperty,$q=Object.defineProperties,$w=Object.getOwnPropertyDescriptor,PS=Object.getOwnPropertyDescriptors,AK=Object.getOwnPropertyNames,A0=Object.getOwnPropertySymbols,px=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty,mx=Object.prototype.propertyIsEnumerable,fx=Reflect.get,xS=Math.pow,e0=(A,e,o)=>e in A?OS(A,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[e]=o,mi=(A,e)=>{for(var o in e||(e={}))Bb.call(e,o)&&e0(A,o,e[o]);if(A0)for(var o of A0(e))mx.call(e,o)&&e0(A,o,e[o]);return A},Qo=(A,e)=>$q(A,PS(e)),yx=(A,e)=>{var o={};for(var a in A)Bb.call(A,a)&&e.indexOf(a)<0&&(o[a]=A[a]);if(A!=null&&A0)for(var a of A0(A))e.indexOf(a)<0&&mx.call(A,a)&&(o[a]=A[a]);return o},Jh=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports),Hh=(A,e)=>{for(var o in e)OS(A,o,{get:e[o],enumerable:!0})},gc=(A,e,o)=>(o=A!=null?Qx(px(A)):{},((a,c,d,C)=>{if(c&&typeof c=="object"||typeof c=="function")for(let y of AK(c))!Bb.call(a,y)&&y!==d&&OS(a,y,{get:()=>c[y],enumerable:!(C=$w(c,y))||C.enumerable});return a})(!e&&A&&A.__esModule?o:OS(o,"default",{value:A,enumerable:!0}),A)),Ci=(A,e,o,a)=>{for(var c,d=$w(e,o),C=A.length-1;C>=0;C--)(c=A[C])&&(d=c(e,o,d)||d);return d&&OS(e,o,d),d},Y=(A,e,o)=>e0(A,typeof e!="symbol"?e+"":e,o),NI=(A,e,o)=>fx(px(A),o,e),KA=(A,e,o)=>new Promise((a,c)=>{var d=S=>{try{y(o.next(S))}catch(k){c(k)}},C=S=>{try{y(o.throw(S))}catch(k){c(k)}},y=S=>S.done?a(S.value):Promise.resolve(S.value).then(d,C);y((o=o.apply(A,e)).next())}),Kl=Jh((A,e)=>{var o=Object.prototype.hasOwnProperty,a="~";function c(){}function d(k,V,J){this.fn=k,this.context=V,this.once=J||!1}function C(k,V,J,gA,CA){if(typeof J!="function")throw new TypeError("The listener must be a function");var MA=new d(J,gA||k,CA),$A=a?a+V:V;return k._events[$A]?k._events[$A].fn?k._events[$A]=[k._events[$A],MA]:k._events[$A].push(MA):(k._events[$A]=MA,k._eventsCount++),k}function y(k,V){--k._eventsCount===0?k._events=new c:delete k._events[V]}function S(){this._events=new c,this._eventsCount=0}Object.create&&(c.prototype=Object.create(null),new c().__proto__||(a=!1)),S.prototype.eventNames=function(){var k,V,J=[];if(this._eventsCount===0)return J;for(V in k=this._events)o.call(k,V)&&J.push(a?V.slice(1):V);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(k)):J},S.prototype.listeners=function(k){var V=a?a+k:k,J=this._events[V];if(!J)return[];if(J.fn)return[J.fn];for(var gA=0,CA=J.length,MA=new Array(CA);gA{var o=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var c="candidate:%s %d %s %d %s %d typ %s";return c+=a.raddr!=null?" raddr %s rport %d":"%v%v",c+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(c+=" generation %d"),c+=a["network-id"]!=null?" network-id %d":"%v",c+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var c="ssrc:%d";return a.attribute!=null&&(c+=" %s",a.value!=null&&(c+=":%s")),c}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var c="mediaclk:";return c+=a.id!=null?"id=%s %s":"%v%s",c+=a.mediaClockValue!=null?"=%s":"",c+=a.rateNumerator!=null?" rate=%s":"",c+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(c){c.reg||(c.reg=/(.*)/),c.format||(c.format="%s")})})}),kf=Jh(A=>{var e=function(C){return String(Number(C))===C?Number(C):C},o=function(C,y,S){var k=C.name&&C.names;C.push&&!y[C.push]?y[C.push]=[]:k&&!y[C.name]&&(y[C.name]={});var V=C.push?{}:k?y[C.name]:y;(function(J,gA,CA,MA){if(MA&&!CA)gA[MA]=e(J[1]);else for(var $A=0;$A1&&(C[S[0]]=void 0),C};A.parseParams=function(C){return C.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(C){return C.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(C){for(var y=[],S=C.split(" ").map(e),k=0;k{var o=bC(),a=/%[sdv%]/g,c=function(S){var k=1,V=arguments,J=V.length;return S.replace(a,function(gA){if(k>=J)return gA;var CA=V[k];switch(k+=1,gA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,k,V){var J=[S+"="+(k.format instanceof Function?k.format(k.push?V:V[k.name]):k.format)];if(k.names)for(var gA=0;gAo.apply(this,[l]))})}var uK=Object.freeze({__proto__:null,shimRTCIceCandidate:Zw,shimRTCIceCandidateRelayProtocol:fb,shimMaxMessageSize:xS,shimSendThrowTypeError:Xw,shimConnectionState:yb,removeExtmapAllowMixed:$w,shimAddIceCandidateNullOrEmpty:A0,shimParameterlessSetLocalDescription:e0});(function({window:A}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=jw,a=function(d){const h={browser:null,version:null};if(d===void 0||!d.navigator||!d.navigator.userAgent)return h.browser="Not a browser.",h;const{navigator:y}=d;if(y.mozGetUserMedia)h.browser="firefox",h.version=parseInt(FS(y.userAgent,/Firefox\/(\d+)\./,1));else if(y.webkitGetUserMedia||d.isSecureContext===!1&&d.webkitRTCPeerConnection)h.browser="chrome",h.version=parseInt(FS(y.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!d.RTCPeerConnection||!y.userAgent.match(/AppleWebKit\/(\d+)\./))return h.browser="Not a supported browser.",h;h.browser="safari",h.version=parseInt(FS(y.userAgent,/AppleWebKit\/(\d+)\./,1)),h.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype,h._safariVersion=FS(y.userAgent,/Version\/(\d+(\.?\d+))/,1)}return h}(A),l={browserDetails:a,commonShim:uK,extractVersion:FS,disableLog:ex,disableWarnings:IK,sdp:Rx};switch(a.browser){case"chrome":if(!hb||!PS||!e.shimChrome)return o("Chrome shim is not included in this adapter release."),l;if(a.version===null)return o("Chrome shim can not determine version, not shimming."),l;o("adapter.js shimming chrome."),l.browserShim=hb,A0(A,a),e0(A),ix(A,a),ox(A),PS(A,a),sx(A),ax(A,a),db(A),nx(A),Cb(A),gx(A,a),Zw(A),fb(A),yb(A),xS(A,a),Xw(A),$w(A,a);break;case"firefox":if(!Bx||!Ww||!e.shimFirefox)return o("Firefox shim is not included in this adapter release."),l;o("adapter.js shimming firefox."),l.browserShim=Bx,A0(A,a),e0(A),cx(A,a),Ww(A,a),lx(A),ux(A),Ix(A),Bb(A),Qb(A),Ex(A),dx(A),Cx(A),hx(A),Zw(A),yb(A),xS(A,a),Xw(A);break;case"safari":if(!Sx||!e.shimSafari)return o("Safari shim is not included in this adapter release."),l;o("adapter.js shimming safari."),l.browserShim=Sx,A0(A,a),e0(A),fx(A),zw(A),pb(A),Qx(A),px(A),yx(A),mb(A),Dx(A),Zw(A),fb(A),xS(A,a),Xw(A),$w(A,a);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var lo,_x=Object.create,YS=Object.defineProperty,EK=Object.defineProperties,t0=Object.getOwnPropertyDescriptor,VS=Object.getOwnPropertyDescriptors,dK=Object.getOwnPropertyNames,i0=Object.getOwnPropertySymbols,Tx=Object.getPrototypeOf,Db=Object.prototype.hasOwnProperty,Nx=Object.prototype.propertyIsEnumerable,Gx=Reflect.get,JS=Math.pow,o0=(A,e,o)=>e in A?YS(A,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[e]=o,fi=(A,e)=>{for(var o in e||(e={}))Db.call(e,o)&&o0(A,o,e[o]);if(i0)for(var o of i0(e))Nx.call(e,o)&&o0(A,o,e[o]);return A},po=(A,e)=>EK(A,VS(e)),bx=(A,e)=>{var o={};for(var a in A)Db.call(A,a)&&e.indexOf(a)<0&&(o[a]=A[a]);if(A!=null&&i0)for(var a of i0(A))e.indexOf(a)<0&&Nx.call(A,a)&&(o[a]=A[a]);return o},Kh=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports),jh=(A,e)=>{for(var o in e)YS(A,o,{get:e[o],enumerable:!0})},gc=(A,e,o)=>(o=A!=null?_x(Tx(A)):{},((a,l,d,h)=>{if(l&&typeof l=="object"||typeof l=="function")for(let y of dK(l))!Db.call(a,y)&&y!==d&&YS(a,y,{get:()=>l[y],enumerable:!(h=t0(l,y))||h.enumerable});return a})(!e&&A&&A.__esModule?o:YS(o,"default",{value:A,enumerable:!0}),A)),hi=(A,e,o,a)=>{for(var l,d=t0(e,o),h=A.length-1;h>=0;h--)(l=A[h])&&(d=l(e,o,d)||d);return d&&YS(e,o,d),d},Y=(A,e,o)=>o0(A,typeof e!="symbol"?e+"":e,o),GI=(A,e,o)=>Gx(Tx(A),o,e),WA=(A,e,o)=>new Promise((a,l)=>{var d=S=>{try{y(o.next(S))}catch(k){l(k)}},h=S=>{try{y(o.throw(S))}catch(k){l(k)}},y=S=>S.done?a(S.value):Promise.resolve(S.value).then(d,h);y((o=o.apply(A,e)).next())}),jl=Kh((A,e)=>{var o=Object.prototype.hasOwnProperty,a="~";function l(){}function d(k,V,J){this.fn=k,this.context=V,this.once=J||!1}function h(k,V,J,cA,CA){if(typeof J!="function")throw new TypeError("The listener must be a function");var MA=new d(J,cA||k,CA),ie=a?a+V:V;return k._events[ie]?k._events[ie].fn?k._events[ie]=[k._events[ie],MA]:k._events[ie].push(MA):(k._events[ie]=MA,k._eventsCount++),k}function y(k,V){--k._eventsCount===0?k._events=new l:delete k._events[V]}function S(){this._events=new l,this._eventsCount=0}Object.create&&(l.prototype=Object.create(null),new l().__proto__||(a=!1)),S.prototype.eventNames=function(){var k,V,J=[];if(this._eventsCount===0)return J;for(V in k=this._events)o.call(k,V)&&J.push(a?V.slice(1):V);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(k)):J},S.prototype.listeners=function(k){var V=a?a+k:k,J=this._events[V];if(!J)return[];if(J.fn)return[J.fn];for(var cA=0,CA=J.length,MA=new Array(CA);cA{var o=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var l="candidate:%s %d %s %d %s %d typ %s";return l+=a.raddr!=null?" raddr %s rport %d":"%v%v",l+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(l+=" generation %d"),l+=a["network-id"]!=null?" network-id %d":"%v",l+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var l="ssrc:%d";return a.attribute!=null&&(l+=" %s",a.value!=null&&(l+=":%s")),l}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var l="mediaclk:";return l+=a.id!=null?"id=%s %s":"%v%s",l+=a.mediaClockValue!=null?"=%s":"",l+=a.rateNumerator!=null?" rate=%s":"",l+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(l){l.reg||(l.reg=/(.*)/),l.format||(l.format="%s")})})}),Ff=Kh(A=>{var e=function(h){return String(Number(h))===h?Number(h):h},o=function(h,y,S){var k=h.name&&h.names;h.push&&!y[h.push]?y[h.push]=[]:k&&!y[h.name]&&(y[h.name]={});var V=h.push?{}:k?y[h.name]:y;(function(J,cA,CA,MA){if(MA&&!CA)cA[MA]=e(J[1]);else for(var ie=0;ie1&&(h[S[0]]=void 0),h};A.parseParams=function(h){return h.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(h){return h.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(h){for(var y=[],S=h.split(" ").map(e),k=0;k{var o=UC(),a=/%[sdv%]/g,l=function(S){var k=1,V=arguments,J=V.length;return S.replace(a,function(cA){if(k>=J)return cA;var CA=V[k];switch(k+=1,cA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,k,V){var J=[S+"="+(k.format instanceof Function?k.format(k.push?V:V[k.name]):k.format)];if(k.names)for(var cA=0;cA{var e=kf(),o=eK(),a=bC();A.grammar=a,A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),YS=Jh((A,e)=>{var o=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var c="candidate:%s %d %s %d %s %d typ %s";return c+=a.raddr!=null?" raddr %s rport %d":"%v%v",c+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(c+=" generation %d"),c+=a["network-id"]!=null?" network-id %d":"%v",c+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var c="ssrc:%d";return a.attribute!=null&&(c+=" %s",a.value!=null&&(c+=":%s")),c}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var c="mediaclk:";return c+=a.id!=null?"id=%s %s":"%v%s",c+=a.mediaClockValue!=null?"=%s":"",c+=a.rateNumerator!=null?" rate=%s":"",c+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(c){c.reg||(c.reg=/(.*)/),c.format||(c.format="%s")})})}),Dx=Jh(A=>{var e=function(C){return String(Number(C))===C?Number(C):C},o=function(C,y,S){var k=C.name&&C.names;C.push&&!y[C.push]?y[C.push]=[]:k&&!y[C.name]&&(y[C.name]={});var V=C.push?{}:k?y[C.name]:y;(function(J,gA,CA,MA){if(MA&&!CA)gA[MA]=e(J[1]);else for(var $A=0;$A1&&(C[S[0]]=void 0),C};A.parseParams=function(C){return C.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(C){return C.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(C){for(var y=[],S=C.split(" ").map(e),k=0;k{var o=YS(),a=/%[sdv%]/g,c=function(S){var k=1,V=arguments,J=V.length;return S.replace(a,function(gA){if(k>=J)return gA;var CA=V[k];switch(k+=1,gA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,k,V){var J=[S+"="+(k.format instanceof Function?k.format(k.push?V:V[k.name]):k.format)];if(k.names)for(var gA=0;gA{var e=Ff(),o=CK(),a=UC();A.grammar=a,A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),HS=Kh((A,e)=>{var o=e.exports={v:[{name:"version",reg:/^(\d*)$/}],o:[{name:"origin",reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:["username","sessionId","sessionVersion","netType","ipVer","address"],format:"%s %s %d %s IP%d %s"}],s:[{name:"name"}],i:[{name:"description"}],u:[{name:"uri"}],e:[{name:"email"}],p:[{name:"phone"}],z:[{name:"timezones"}],r:[{name:"repeats"}],t:[{name:"timing",reg:/^(\d*) (\d*)/,names:["start","stop"],format:"%d %d"}],c:[{name:"connection",reg:/^IN IP(\d) (\S*)/,names:["version","ip"],format:"IN IP%d %s"}],b:[{push:"bandwidth",reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:["type","limit"],format:"%s:%s"}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:["type","port","protocol","payloads"],format:"%s %d %s %s"}],a:[{push:"rtp",reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:["payload","codec","rate","encoding"],format:function(a){return a.encoding?"rtpmap:%d %s/%s/%s":a.rate?"rtpmap:%d %s/%s":"rtpmap:%d %s"}},{push:"fmtp",reg:/^fmtp:(\d*) ([\S| ]*)/,names:["payload","config"],format:"fmtp:%d %s"},{name:"control",reg:/^control:(.*)/,format:"control:%s"},{name:"rtcp",reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:["port","netType","ipVer","address"],format:function(a){return a.address!=null?"rtcp:%d %s IP%d %s":"rtcp:%d"}},{push:"rtcpFbTrrInt",reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:["payload","value"],format:"rtcp-fb:%s trr-int %d"},{push:"rtcpFb",reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:["payload","type","subtype"],format:function(a){return a.subtype!=null?"rtcp-fb:%s %s %s":"rtcp-fb:%s %s"}},{push:"ext",reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:["value","direction","encrypt-uri","uri","config"],format:function(a){return"extmap:%d"+(a.direction?"/%s":"%v")+(a["encrypt-uri"]?" %s":"%v")+" %s"+(a.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(a){return a.sessionConfig!=null?"crypto:%d %s %s %s":"crypto:%d %s %s"}},{name:"setup",reg:/^setup:(\w*)/,format:"setup:%s"},{name:"connectionType",reg:/^connection:(new|existing)/,format:"connection:%s"},{name:"mid",reg:/^mid:([^\s]*)/,format:"mid:%s"},{name:"msid",reg:/^msid:(.*)/,format:"msid:%s"},{name:"ptime",reg:/^ptime:(\d*(?:\.\d*)*)/,format:"ptime:%d"},{name:"maxptime",reg:/^maxptime:(\d*(?:\.\d*)*)/,format:"maxptime:%d"},{name:"direction",reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:"icelite",reg:/^(ice-lite)/},{name:"iceUfrag",reg:/^ice-ufrag:(\S*)/,format:"ice-ufrag:%s"},{name:"icePwd",reg:/^ice-pwd:(\S*)/,format:"ice-pwd:%s"},{name:"fingerprint",reg:/^fingerprint:(\S*) (\S*)/,names:["type","hash"],format:"fingerprint:%s %s"},{push:"candidates",reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:["foundation","component","transport","priority","ip","port","type","raddr","rport","tcptype","generation","network-id","network-cost"],format:function(a){var l="candidate:%s %d %s %d %s %d typ %s";return l+=a.raddr!=null?" raddr %s rport %d":"%v%v",l+=a.tcptype!=null?" tcptype %s":"%v",a.generation!=null&&(l+=" generation %d"),l+=a["network-id"]!=null?" network-id %d":"%v",l+=a["network-cost"]!=null?" network-cost %d":"%v"}},{name:"endOfCandidates",reg:/^(end-of-candidates)/},{name:"remoteCandidates",reg:/^remote-candidates:(.*)/,format:"remote-candidates:%s"},{name:"iceOptions",reg:/^ice-options:(\S*)/,format:"ice-options:%s"},{push:"ssrcs",reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:["id","attribute","value"],format:function(a){var l="ssrc:%d";return a.attribute!=null&&(l+=" %s",a.value!=null&&(l+=":%s")),l}},{push:"ssrcGroups",reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:["semantics","ssrcs"],format:"ssrc-group:%s %s"},{name:"msidSemantic",reg:/^msid-semantic:\s?(\w*) (\S*)/,names:["semantic","token"],format:"msid-semantic: %s %s"},{push:"groups",reg:/^group:(\w*) (.*)/,names:["type","mids"],format:"group:%s %s"},{name:"rtcpMux",reg:/^(rtcp-mux)/},{name:"rtcpRsize",reg:/^(rtcp-rsize)/},{name:"sctpmap",reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:["sctpmapNumber","app","maxMessageSize"],format:function(a){return a.maxMessageSize!=null?"sctpmap:%s %s %s":"sctpmap:%s %s"}},{name:"xGoogleFlag",reg:/^x-google-flag:([^\s]*)/,format:"x-google-flag:%s"},{push:"rids",reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:["id","direction","params"],format:function(a){return a.params?"rid:%s %s %s":"rid:%s %s"}},{push:"imageattrs",reg:new RegExp("^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?"),names:["pt","dir1","attrs1","dir2","attrs2"],format:function(a){return"imageattr:%s %s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast",reg:new RegExp("^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$"),names:["dir1","list1","dir2","list2"],format:function(a){return"simulcast:%s %s"+(a.dir2?" %s %s":"")}},{name:"simulcast_03",reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:["value"],format:"simulcast: %s"},{name:"framerate",reg:/^framerate:(\d+(?:$|\.\d+))/,format:"framerate:%s"},{name:"sourceFilter",reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:["filterMode","netType","addressTypes","destAddress","srcList"],format:"source-filter: %s %s %s %s %s"},{name:"bundleOnly",reg:/^(bundle-only)/},{name:"label",reg:/^label:(.+)/,format:"label:%s"},{name:"sctpPort",reg:/^sctp-port:(\d+)$/,format:"sctp-port:%s"},{name:"maxMessageSize",reg:/^max-message-size:(\d+)$/,format:"max-message-size:%s"},{push:"tsRefClocks",reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:["clksrc","clksrcExt"],format:function(a){return"ts-refclk:%s"+(a.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(a){var l="mediaclk:";return l+=a.id!=null?"id=%s %s":"%v%s",l+=a.mediaClockValue!=null?"=%s":"",l+=a.rateNumerator!=null?" rate=%s":"",l+=a.rateDenominator!=null?"/%s":""}},{name:"keywords",reg:/^keywds:(.+)$/,format:"keywds:%s"},{name:"content",reg:/^content:(.+)/,format:"content:%s"},{name:"bfcpFloorCtrl",reg:/^floorctrl:(c-only|s-only|c-s)/,format:"floorctrl:%s"},{name:"bfcpConfId",reg:/^confid:(\d+)/,format:"confid:%s"},{name:"bfcpUserId",reg:/^userid:(\d+)/,format:"userid:%s"},{name:"bfcpFloorId",reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:["id","mStream"],format:"floorid:%s mstrm:%s"},{push:"invalid",names:["value"]}]};Object.keys(o).forEach(function(a){o[a].forEach(function(l){l.reg||(l.reg=/(.*)/),l.format||(l.format="%s")})})}),kx=Kh(A=>{var e=function(h){return String(Number(h))===h?Number(h):h},o=function(h,y,S){var k=h.name&&h.names;h.push&&!y[h.push]?y[h.push]=[]:k&&!y[h.name]&&(y[h.name]={});var V=h.push?{}:k?y[h.name]:y;(function(J,cA,CA,MA){if(MA&&!CA)cA[MA]=e(J[1]);else for(var ie=0;ie1&&(h[S[0]]=void 0),h};A.parseParams=function(h){return h.split(/;\s?/).reduce(d,{})},A.parseFmtpConfig=A.parseParams,A.parsePayloads=function(h){return h.toString().split(" ").map(Number)},A.parseRemoteCandidates=function(h){for(var y=[],S=h.split(" ").map(e),k=0;k{var o=HS(),a=/%[sdv%]/g,l=function(S){var k=1,V=arguments,J=V.length;return S.replace(a,function(cA){if(k>=J)return cA;var CA=V[k];switch(k+=1,cA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,k,V){var J=[S+"="+(k.format instanceof Function?k.format(k.push?V:V[k.name]):k.format)];if(k.names)for(var cA=0;cA{var e=Dx(),o=Sx();A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),iK=gc(Kl()),qB=((co=qB||{})[co.INVALID_PARAMETER=4096]="INVALID_PARAMETER",co[co.INVALID_OPERATION=4097]="INVALID_OPERATION",co[co.NOT_SUPPORTED=4098]="NOT_SUPPORTED",co[co.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",co[co.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",co[co.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",co[co.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",co[co.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",co[co.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",co[co.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",co[co.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",co[co.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",co[co.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",co[co.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",co[co.CLIENT_BANNED=16448]="CLIENT_BANNED",co[co.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",co[co.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",co[co.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",co[co.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",co[co.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",co[co.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",co[co.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",co[co.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",co[co.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",co[co.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",co[co.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",co[co.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",co[co.API_CALL_ABORTED=16461]="API_CALL_ABORTED",co[co.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",co[co.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",co[co.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",co[co.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",co[co.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",co[co.UNKNOWN=65535]="UNKNOWN",co),dt=qB,Mx=class extends Error{constructor(A){let{name:e="RtcError",message:o,code:a=dt.UNKNOWN,extraCode:c=0,constraint:d}=A,C="<".concat(function(S){for(let k in dt)if(dt[k]===S)return k;return"UNKNOWN"}(a)," 0x").concat(a.toString(16),">"),y="".concat(o).concat(d?" constraint: ".concat(d):"").concat(o!=null&&o.includes(C)?"":" ".concat(C));super(y),Y(this,"code"),Y(this,"extraCode"),Y(this,"message"),Y(this,"originMessage"),Y(this,"name"),Y(this,"constraint"),this.code=a,this.extraCode=c,this.name=e,this.message=y,this.constraint=d,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ai=Mx,pb=0,vx=!0,KB=function(A){pb=A;let e=new Date;e.setTime(e.getTime()+A),QA[vx?"info":"debug"]("baseTime from server: ".concat(e," offset: ").concat(A)),vx=!1},Rx=function(){return pb},Lf=function(){return Date.now()+pb},_x=function(){let A=new Date;return A.setTime(Lf()),A.toLocaleString()},mb=function(A){let e=String(A.getMilliseconds());return"padStart"in String.prototype&&(e=e.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(e)},Hd={};Hh(Hd,{REPORT_TYPE:()=>_0,buildSSOPackage:()=>AQ,bytes2ms:()=>y0,calculateScaleResolutionDownNumber:()=>w0,concatArrayBuffers:()=>aM,convertObjectNumberToInt:()=>R0,copyProperties:()=>A2,deepClone:()=>zf,deepCloneBasic:()=>Zf,deepMerge:()=>Wh,delay:()=>LC,fibonacci:()=>Kf,formatedTime:()=>a2,getConstructorName:()=>iM,getContainerFromElement:()=>Jb,getEnv:()=>Zx,getFirst16Bits:()=>c2,getInternalVersion:()=>n2,getLast16Bits:()=>T0,getLoggerUrl:()=>Hf,getMediaStreamTrackInfo:()=>Wb,getMuteStateFromFlag:()=>wp,getNetworkType:()=>m0,getNumNetworkType:()=>qf,getReconnectionTimeout:()=>Rp,getStringByteLength:()=>v0,getTestSignalDomain:()=>Xx,getTurnServer:()=>r2,getUint32Version:()=>qb,getValueType:()=>Cg,getViewListFromView:()=>nM,glog:()=>t2,ipv4ToUint32:()=>sM,isArray:()=>wa,isAudioWorkletSupported:()=>i2,isBoolean:()=>Nr,isConstructor:()=>Wf,isEmpty:()=>S0,isFunction:()=>Ra,isLangChinese:()=>Wd,isMediaStreamTrack:()=>Yb,isNumber:()=>bn,isObject:()=>$E,isOverseaSdkAppId:()=>Kd,isPlainObject:()=>lE,isPortrait:()=>Hb,isPromise:()=>jf,isRemoteTrack:()=>Vb,isRotate90Or270:()=>$B,isSetSinkIdSupported:()=>o2,isString:()=>Yn,isUndefined:()=>Je,isVideoMixerOutputTrack:()=>_p,loadImage:()=>rM,loadVideo:()=>g2,ms2bytes:()=>e2,ms2samples:()=>D0,normalizeUrl:()=>jb,performanceNow:()=>ko,promiseAny:()=>oM,samples2ms:()=>xb,setNetworkTypeFromWebRTC:()=>f0,stringify:()=>zd,stringifyIncludeValue:()=>M0,throttlePromise:()=>Kb});var Tx={};Hh(Tx,{ASR_ROBOT_FROM_TYPE:()=>d0,AUDIO_MUTE_BIT:()=>Of,AUDIO_STAT_BIT:()=>jS,AUX_STAT_BIT:()=>KS,AUX_STREAM_MSID:()=>Fx,BACKEND_ENV:()=>Uf,BASE_DOC_URL:()=>qh,BASE_HOST:()=>Gx,CAPABILITIES_KEYS:()=>Gb,CLASS_NAME:()=>IK,CLOUD_CONSOLE_URL:()=>nK,CROSS_ROOM_BIT:()=>vb,DATA_CHANNEL_FROM_TYPE_BIT:()=>zB,DATA_FREEZE_TIMING:()=>Tb,DOC_BILLING_CN:()=>s0,DOC_BILLING_OVERSEA:()=>Db,DOC_URL:()=>rK,DTLS_STATE_UNKNOWN:()=>Kh,ENV_NAME:()=>jB,EXCHANGE_SDP_TIMEOUT:()=>Vx,IS_WORKER:()=>i0,IS_WORKLET:()=>o0,KIBANA_EVENT:()=>Ja,LOCAL_STREAM_PUBLISH_STATE:()=>Jx,LOGGER_CMD_TYPE:()=>bI,LOGGER_DOMAIN:()=>GI,LOGGER_DOMAIN_OVERSEA:()=>Dp,LOG_LEVEL:()=>WB,LOG_LEVEL_NAME:()=>EK,MAIN_STREAM_MSID:()=>uu,MAX_RTT:()=>E0,MICROPHONE_COMMUNICATIONS:()=>uK,MICROPHONE_DEFAULT:()=>ZS,MUTE_ALL_BIT:()=>Ux,NAME:()=>YA,NETWORK_TYPE:()=>n0,NOT_SUPPORTED_H264:()=>I0,PAUSED_RETRY_COUNT:()=>vp,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Nb,PEER_CONNECTION_STATE:()=>Co,PEER_LEAVE_REASON:()=>Kx,RECOVER_CAPTURE_INTERVAL:()=>$S,REMOTE_STREAM_TYPE_AUX:()=>Rb,REMOTE_STREAM_TYPE_MAIN:()=>a0,RENDER_FREEZE_TIMING:()=>Hx,SCHEDULE_DOMAIN:()=>XB,SCHEDULE_TIMEOUT:()=>qx,SDP_SEMANTICS_PLAN_B:()=>l0,SDP_SEMANTICS_UNIFIED_PLAN:()=>zS,SECOND_HOST:()=>bx,SIGNAL_PING_PONG_INTERVAL:()=>cE,SIGNAL_PING_TIMEOUT:()=>kx,SIGNAL_RECONNECTION_COUNT:()=>aK,SMALL_STAT_BIT:()=>Mb,SPEAKER_DEFAULT:()=>u0,STORAGE_EXPIRES_TIME:()=>r0,STREAM_TYPE_BIG:()=>cK,STREAM_TYPE_SMALL:()=>lK,SUBSCRIBE_SMALL_RETRY_COUNT:()=>XS,SYNC_USER_LIST_INTERVAL:()=>gK,Scene:()=>Ff,THIRD_HOST:()=>sK,TRANSPORT_DIRECTION:()=>zn,TRTC_ERROR_ASSISTANCE:()=>JS,TRTC_QUALITY_BAD:()=>Pf,TRTC_QUALITY_DISCONNECTED:()=>xx,TRTC_QUALITY_EXCELLENT:()=>g0,TRTC_QUALITY_GOOD:()=>ZB,TRTC_QUALITY_POOR:()=>Ox,TRTC_QUALITY_UNKNOWN:()=>wb,TRTC_QUALITY_VERY_BAD:()=>Px,UPDATE_OFFER_TIMEOUT:()=>Yx,VIDEO_MUTE_BIT:()=>WS,VIDEO_STAT_BIT:()=>qS,WEBGL_ATTRIBUTES:()=>bb,audioProfileMap:()=>Sp,defaultBigVideoProfile:()=>HS,defaultSmallVideoProfile:()=>Lx,getRetryCount:()=>xf,getScriptDir:()=>oK,innerVersion:()=>t0,loggerProxy:()=>yb,screenProfileMap:()=>Sb,setLoggerProxy:()=>VS,setRetryCount:()=>c0,setVersion:()=>Nx,version:()=>qd,videoProfileMap:()=>kC});var t0="4.15.00.1600",qd="5.0.0";function Nx(A){qd=A;let[e,o,a]=A.split(".").map(c=>parseInt(c,10));t0="".concat(e,".").concat(Math.min(15,o),".").concat(Math.min(15,a),".").concat(o.toString().padStart(2,"0")).concat(a.toString().padStart(2,"0"))}var fb,gE,i0=typeof importScripts<"u",o0=typeof registerProcessor<"u",oK=()=>{let A=i0?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},yb="",VS=A=>yb=A,Gx="web.sdk.qcloud.com",bx="web.sdk.tencent.cn",sK="web.sdk.cloud.tencent.cn",nK="https://console.cloud.tencent.com/trtc",qh="https://".concat(Gx,"/trtc/webrtc/doc"),rK="".concat(qh,"/zh-cn/"),s0="https://cloud.tencent.com/document/product/647/85386",Db="https://trtc.io/document/56025",GI="https://yun.tim.qq.com",Dp="https://apisgp.my-imcloud.com",JS="trtc_error_assistance",bI={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},jB={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},WB=((gE=WB||{})[gE.TRACE=0]="TRACE",gE[gE.DEBUG=1]="DEBUG",gE[gE.INFO=2]="INFO",gE[gE.WARN=3]="WARN",gE[gE.ERROR=4]="ERROR",gE[gE.NONE=5]="NONE",gE),kx=18e3,cE=2e3,n0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},r0=6048e5,Sp={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},kC={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},HS=kC["480p_2"],Lx=kC["120p_2"],Sb={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},YA={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},zn={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Uf={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Ff=((fb=Ff||{}).LIVE="live",fb.RTC="rtc",fb),qS=1,Mb=2,KS=4,jS=8,Of=64,WS=16,Ux=112,vb=128,zB=256,uu="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",Fx="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",a0=YA.MAIN,Rb=YA.AUXILIARY,wb=0,g0=1,ZB=2,Ox=3,Pf=4,Px=5,xx=6,Kh="unknown",Co={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},_b=1/0;function c0(A){_b=A}function xf(){return _b}var Mp,aK=30,Ja={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},gK=1e4,Yx=1e4,Vx=1e4,zS="unified-plan",l0="plan-b",I0=1028,Jx=((Mp=Jx||{})[Mp.UNPUBLISH=-1]="UNPUBLISH",Mp[Mp.PUBLISHING=0]="PUBLISHING",Mp[Mp.PUBLISHED=1]="PUBLISHED",Mp),Tb=500,Hx=1e3,cK=YA.BIG,lK=YA.SMALL,Nb=1e4,XB={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},qx=2e3,IK={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},vp=5,ZS="default",u0=ZS,uK="communications",EK=Object.keys(WB),Kx=["normal leave","timeout leave","kick","role change"],XS=10,$S=2e3,Gb=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],E0=1e4,d0=14,bb={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},jx=function(A,e,o,a){return new(o||(o=Promise))(function(c,d){function C(k){try{S(a.next(k))}catch(V){d(V)}}function y(k){try{S(a.throw(k))}catch(V){d(V)}}function S(k){k.done?c(k.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(k.value).then(C,y)}S((a=a.apply(A,[])).next())})},C0=Symbol(32),h0=Symbol(16),kb=Symbol(8),Yf=class{constructor(A){this.g=A,this.consumed=0,A&&(this.need=A.next().value)}setG(A){this.g=A,this.demand(A.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(A,e){return e&&this.consume(),this.need=A,this.flush()}read(A){return jx(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,o)=>{var a;this.reject=o,this.resolve=c=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(c)},this.demand(A,!0)||(a=this.pull)===null||a===void 0||a.call(this,A)})})}readU32(){return this.read(C0)}readU16(){return this.read(h0)}readU8(){return this.read(kb)}close(){var A;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(A=this.reject)===null||A===void 0||A.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let A=null,e=this.buffer.subarray(this.consumed),o=0,a=c=>e.length<(o=c);if(typeof this.need=="number"){if(a(this.need))return;A=e.subarray(0,o)}else if(this.need===C0){if(a(4))return;A=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===h0){if(a(2))return;A=e[0]<<8|e[1]}else if(this.need===kb){if(a(1))return;A=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(a(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(a(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,o)),A=this.need}return this.consumed+=o,this.g?this.demand(this.g.next(A).value,!0):this.resolve&&this.resolve(A),A}write(A){if(A instanceof Uint8Array?this.malloc(A.length).set(A):"buffer"in A?this.malloc(A.byteLength).set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength)):this.malloc(A.byteLength).set(new Uint8Array(A)),!this.g&&!this.resolve)return new Promise(e=>this.pull=e);this.flush()}writeU32(A){this.malloc(4).set([A>>24&255,A>>16&255,A>>8&255,255&A]),this.flush()}writeU16(A){this.malloc(2).set([A>>8&255,255&A]),this.flush()}writeU8(A){this.malloc(1)[0]=A,this.flush()}malloc(A){if(this.buffer){let e=this.buffer.length,o=e+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let a=new Uint8Array(o);a.set(this.buffer),this.buffer=a}return this.buffer.subarray(e,o)}return this.buffer=new Uint8Array(A),this.buffer}};Yf.U32=C0,Yf.U16=h0,Yf.U8=kb;var AM=128;function B0(A){let e=new Yf;for(;A>=128;)e.malloc(1)[0]=255&A|AM,A>>>=7;return e.malloc(1)[0]=255&A,e.buffer||new Uint8Array(0)}function Q0(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Yf,a=e<<3;switch(typeof A){case"boolean":let c=o.malloc(2);c[0]=a,c[1]=A?1:0;break;case"number":o.malloc(1)[0]=a,o.write(B0(A));break;case"string":o.malloc(1)[0]=2|a;let d=new TextEncoder().encode(A);o.write(B0(d.length));let C=o.malloc(d.length);for(let S=0;S>>24&255),this.buffer.push(A>>>16&255),this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeInt16(A){this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeByte(A){this.buffer.push(255&A)}writeBytes(A){for(let e=0;e>>24&255,A[o+1]=e>>>16&255,A[o+2]=e>>>8&255,A[o+3]=255&e}function Eu(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]}function zx(A,e){return A[e]}function Jf(A,e,o){return new TextDecoder().decode(function(a,c,d){return a.slice(c,c+d)}(A,e,o))}var eM=0,Lb=2654435769,p0=16,jh=2,tM=7;function Ub(A,e){let o=new Wx,a=function(ve,yi,Ge){let Bt=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&arguments[4]!==void 0?arguments[4]:2e3,encryption:arguments.length>5&&arguments[5]!==void 0?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&arguments[6]!==void 0?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:Ge,appId:ve,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:Bt,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:yi}}(e,A,eM);eM=eM+1&2147483647,o.writeInt32(0),o.writeInt32(a.version),o.writeByte(a.encryption);let c=new TextEncoder().encode(a.d2);o.writeInt32(c.length+4),c&&o.writeBytes(c),o.writeByte(a.uinType);let d=new TextEncoder().encode(a.uin);o.writeInt32(d.length+4),d.length&&o.writeBytes(d);let C=new Wx;C.writeInt32(0),C.writeInt32(a.reqHead.seqNumber),C.writeInt32(a.reqHead.appId),C.writeByte(a.reqHead.appId>>>24&255),C.writeByte(a.reqHead.appId>>>16&255),C.writeByte(a.reqHead.appId>>>8&255),C.writeByte(255&a.reqHead.appId);for(let ve=4;ve<16;ve++)C.writeByte(0);let y=new TextEncoder().encode(a.reqHead.a2);C.writeInt32(y.length+4),y.length&&C.writeBytes(y);let S=new TextEncoder().encode(a.reqHead.serviceCmd);C.writeInt32(S.length+4),S.length&&C.writeBytes(S);let k=new TextEncoder().encode(a.reqHead.cookie);C.writeInt32(k.length+4),k.length&&C.writeBytes(k);let V=new TextEncoder().encode(a.reqHead.imei);C.writeInt32(V.length+4),V.length&&C.writeBytes(V);let J=new TextEncoder().encode(a.reqHead.ksid);C.writeInt32(J.length+4),J.length&&C.writeBytes(J);let gA=new TextEncoder().encode(a.reqHead.clientVersionInfo);C.writeInt16(gA.length+2),gA.length&&C.writeBytes(gA);let CA=C.length;C.data[0]=CA>>>24&255,C.data[1]=CA>>>16&255,C.data[2]=CA>>>8&255,C.data[3]=255&CA,Yn(A)&&(A=new TextEncoder().encode(A)),C.writeInt32(A.length+4),A.length&&C.writeBytes(A);let MA=new Uint8Array(C.data),$A=null;a.encryption===1?$A=new TextEncoder().encode(a.uin):a.encryption===2&&($A=new Uint8Array(16)),$A&&(MA=function(ve,yi){let Ge=ve.length,Bt=(Ge+1+jh+tM)%8;Bt&&(Bt=8-Bt);let hi=Ge+1+jh+tM+Bt,Di=new Uint8Array(hi),Vo=0,Jo=new Uint8Array(8),Qn=new Uint8Array(8),Ho=new Uint8Array(8),Ns=0;Jo[0]=248&Math.floor(256*Math.random())|Bt,Ns=1;for(let ya=0;ya>>24&255,Be[1]=Ye>>>16&255,Be[2]=Ye>>>8&255,Be[3]=255&Ye,Be}function Fb(A,e,o,a,c,d){for(let C=0;C<8;C++)A[C]^=a[C];(function(C,y,S,k){let V=Eu(C,0),J=Eu(C,4),gA=[];for(let MA=0;MA<4;MA++)gA[MA]=Eu(y,4*MA);let CA=0;for(let MA=0;MA>>=0,V+=(J<<4)+gA[0]^J+CA^(J>>>5)+gA[1],V>>>=0,J+=(V<<4)+gA[2]^V+CA^(V>>>5)+gA[3],J>>>=0;Vf(S,V,k),Vf(S,J,k+4)})(A,e,c,d);for(let C=0;C<8;C++)c[d+C]^=o[C];for(let C=0;C<8;C++)o[C]=A[C]}var Zx=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Xx=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},Kd=A=>Number(A)<14e8,Hf=function(A,e){let o;o=yb||(Kd(A)?Dp:GI);let a=Math.floor(Math.random()*xS(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(a,"&sdkappid=").concat(A,"&cmdtype=").concat(e)},Ob="unknown";function m0(){(function(){var d;$x||($x=!0,(d=navigator.connection)==null||d.addEventListener("typechange",dK))})();let{userAgent:A,connection:e}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let a=e&&e.type&&e.type.toLowerCase(),c=e&&e.effectiveType&&e.effectiveType.toLowerCase();return c==="slow-2"&&(c="2g"),a?Pb(a,c):Ob}function dK(){QA.warn("netType changed",m0())}var $x=!1;function Pb(A,e){if(n0[A])return A;switch(A){case"cellular":case"wimax":return e||"unknown";case"ethernet":return"wired";default:return"unknown"}}function f0(A){Ob=Pb(A)}function qf(){return n0[m0()]}function A2(A,e){for(let o of Reflect.ownKeys(e))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let a=Object.getOwnPropertyDescriptor(e,o)||"";Object.defineProperty(A,o,a)}return A}function y0(A){return xb(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function xb(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function e2(A){return 4*D0(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function D0(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var t2=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Wd=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},lE=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function Kf(A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?e:Kf(A-1,e,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+e)}function Rp(A){return A>8?3e4:1e3*Kf(A)}function Cg(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ra=A=>typeof A=="function",Je=A=>A===void 0,Yn=A=>typeof A=="string",bn=A=>typeof A=="number",Nr=A=>typeof A=="boolean",$E=A=>Cg(A)==="object",wa=A=>Cg(A)==="array",Yb=A=>Cg(A)==="MediaStreamTrack".toLowerCase(),Vb=A=>A.isRemote,jf=A=>Cg(A)==="promise",Wf=A=>Ra(A)&&A.prototype.constructor===A,iM=A=>Wf(A)?A.prototype.constructor.name:"",i2=typeof AudioWorkletNode<"u",o2=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function oM(A){return new Promise((e,o)=>{let a=[];A.forEach(c=>{c.then(e).catch(d=>{a.push(d),a.length===A.length&&o(a)})})})}function ko(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var s2=A=>+A<10?"0".concat(A):A,n2=A=>{let e=A.match(/^\d+\.\d+\.\d+/)[0];if(!e)return A;let o=e.split("."),a=s2(o[1])+s2(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(a)},CK=Object.prototype.hasOwnProperty;function S0(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(lE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let e in A)if(CK.call(A,e))return!1;return!0}return!1}function wp(A,e){return{userId:e,hasAudio:!!(A&jS),hasVideo:!!(A&qS),hasAuxiliary:!!(A&KS),hasSmall:!!(A&Mb),audioMuted:!!(A&Of),videoMuted:!!(A&WS),audioAvailable:!(!(A&jS)||A&Of),videoAvailable:!(!(A&qS)||A&WS),hasDatachannel:!!(A&zB)}}function r2(A){let e={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!Je(A.username)&&!Je(A.credential)&&(e.username=A.username,e.credential=A.credential,e.credentialType="password",Je(A.credentialType)||(e.credentialType=A.credentialType)),e}function sM(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Yn(A))return 0;let o=A.split(".");return e?(Number(o[0])<<24|Number(o[1])<<16|Number(o[2])<<8|Number(o[3]))>>>0:(Number(o[3])<<24|Number(o[2])<<16|Number(o[1])<<8|Number(o[0]))>>>0}var Wh=function(A,e,o,a){if(!$E(A)||!$E(e))return 0;let c,d=0,C=Object.keys(e);for(let y=0,S=C.length;y{e[a]=zf(o)}),e}if($E(A)){let e={};return Object.keys(A).forEach(o=>{e[o]=zf(A[o])}),e}return A}var nM=A=>{let e=[];if(wa(A))e=[...A];else if(Yn(A)){let o=document.getElementById(A);o&&e.push(o)}else A&&e.push(A);return e},Jb=A=>Yn(A)?document.getElementById(A):A,a2=()=>(A=>{let e=S=>S<10?"0".concat(S):"".concat(S),o=A.getFullYear(),a=A.getMonth()+1,c=A.getDate(),d=e(A.getHours()),C=e(A.getMinutes()),y=e(A.getSeconds());return"".concat(o,"/").concat(a,"/").concat(c," ").concat(d,":").concat(C,":").concat(y)})(new Date);function zd(A,e){let{keysToInclude:o,keysToExclude:a}=e;try{if(wa(A))return"[".concat(A.map(y=>zd(y,{keysToInclude:o,keysToExclude:a})).join(","),"]");if(!lE(A)||!wa(o)&&!wa(a))return JSON.stringify(A);let c={},d=new Set(o),C=new Set(a);return Object.keys(A).forEach(y=>{(C.size===0&&d.has(y)||d.size===0&&!C.has(y))&&(c[y]=lE(A[y])||wa(A[y])?JSON.parse(zd(A[y],{keysToExclude:a,keysToInclude:o})):A[y])}),JSON.stringify(c)}catch{return"{}"}}function M0(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(a=>{e===A[a]&&o.push(a)}),zd(A,{keysToInclude:o})}function v0(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Hb=()=>{var A,e,o,a;return(A=window.screen)!=null&&A.orientation?!((a=(o=(e=window.screen)==null?void 0:e.orientation)==null?void 0:o.type)==null||!a.includes("portrait")):window.orientation===0||window.orientation===180},rM=A=>KA(null,null,function*(){return new Promise((e,o)=>{let a;if(Yn(A))a=new Image,a.crossOrigin="anonymous",a.src=A;else if(a=A,a.complete)return void e(a);a.onload=()=>e(a),a.onerror=()=>{o(new ai({code:dt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),qb=A=>{let e=A.split(".");return+e[0]<<24|+e[1]<<16|+e[2]<<8|+e[3]},R0=A=>(Object.keys(A).forEach(e=>{bn(A[e])&&(e.startsWith("uint")||e.startsWith("int"))?A[e]=Math.floor(A[e]):(lE(A[e])||wa(A[e]))&&R0(A[e])}),A);function LC(A,e){return new Promise(o=>{let a=setTimeout(o,A);e&&e(a)})}function Kb(A,e){let o=null;return function(){for(var a=arguments.length,c=new Array(a),d=0;do=null),o)}}function jb(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function Wb(A){var e;try{let{width:o,height:a,frameRate:c,sampleRate:d,sampleSize:C,channelCount:y}=(e=A.getSettings)==null?void 0:e.call(A),S=A.kind===YA.AUDIO?"".concat(d,"x").concat(C,"@").concat(y):"".concat(o,"x").concat(a,"@").concat(c),k=A.stats?" stats: ".concat(JSON.stringify(A.stats).replaceAll('"',"")):"";return"".concat(A.id," ").concat(A.readyState," muted:").concat(A.muted," ").concat(A.kind," ").concat(A.label," ").concat(S).concat(k)}catch{return""}}function w0(A,e){return A.width*A.height===e.width*e.height?1:Hb()&&e.width>e.height&&A.height>e.width?Math.max(A.width/e.height,A.height/e.width,1):Math.max(A.width/e.width,A.height/e.height,1)}function $B(A){return A===90||A===270}function g2(A){return KA(this,null,function*(){return new Promise((e,o)=>{let a=document.createElement("video");a.crossOrigin="anonymous",a.src=A,a.muted=!0,a.loop=!0,a.playsInline=!0,a.play().then(()=>e(a)),a.onerror=()=>{o(a.error)}})})}function Zf(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(e.has(A))return e.get(A);if(Array.isArray(A)){let o=[];return e.set(A,o),A.forEach((a,c)=>{o[c]=Zf(a,e)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return e.set(A,o),Reflect.ownKeys(A).forEach(a=>{o[a]=Zf(A[a],e)}),o}return A}var _0=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(_0||{});function AQ(A,e,o,a){try{let c=function(d,C,y,S){let k={data:d,random:Math.floor(2147483648*Math.random()),sdkAppId:y};return Je(S)||(k=Qo(mi({},k),{gzip:+S})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:C,bytes_report_data:JSON.stringify(k)}}}(A,e,o,a);return Ub(Q0(c),o)}catch{return JSON.stringify(A)}}function aM(A,e){let o=new Uint8Array(A.byteLength+e.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(e),A.byteLength),o.buffer}function T0(A){return(65535&A)>>>0}function c2(A){return(4294901760&A)>>>0}function _p(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function hK(A){let e=function(o){try{let a={},c=0;a.totalLength=Eu(o,c),c+=4,a.version=Eu(o,c),c+=4,a.encryption=zx(o,c),c+=1,a.uinType=zx(o,c),c+=1,a.uinLength=Eu(o,c),c+=4,a.uin=a.uinLength>4?Jf(o,c,a.uinLength-4):"",c+=a.uinLength-4;let d=o.slice(c);return a.encryption===2?(o=function(C,y){let S=0,k=new Uint8Array(8).fill(0),V=new Uint8Array(C.slice(0,8)),J=N0(V,y),gA=7&J[0],CA=C.length-1-gA-jh-tM,MA=new Uint8Array(CA),$A=0,Be=k,Ye=C.slice(0,8);S=8;let ve=1;ve+=gA;for(let Ge=1;Ge<=jh;)if(ve<8)ve++,Ge++;else if(ve===8){let Bt=Xf(C,S,Be,Ye,J,y);Be=Bt.ivPreCrypt,Ye=Bt.ivCurCrypt,J=Bt.debiBuf,S=Bt.bufPos,ve=0}let yi=CA;for(;yi>0;)if(ve<8)MA[$A++]=J[ve]^Be[ve],ve++,yi--;else if(ve===8){let Ge=Xf(C,S,Be,Ye,J,y);Be=Ge.ivPreCrypt,Ye=Ge.ivCurCrypt,J=Ge.debiBuf,S=Ge.bufPos,ve=0}for(let Ge=1;Ge<=tM;)if(ve<8)J[ve],Be[ve],ve++,Ge++;else if(ve===8){if(S>=C.length)break;let Bt=Xf(C,S,Be,Ye,J,y);if(!Bt.success)break;Be=Bt.ivPreCrypt,Ye=Bt.ivCurCrypt,J=Bt.debiBuf,S=Bt.bufPos,ve=0}return MA}(d,new Uint8Array(16).fill(0)),a.decrypted=!0,c=0):(o=d,c=0),a.rspHeadLength=Eu(o,c),c+=4,a.seqNo=Eu(o,c),c+=4,a.retCode=Eu(o,c),c+=4,a.retStrLength=Eu(o,c),c+=4,a.retStr=a.retStrLength?Jf(o,c,a.retStrLength-4):"",c+=a.retStrLength-4,a.serviceCmdLength=Eu(o,c),c+=4,a.serviceCmd=a.serviceCmdLength?Jf(o,c,a.serviceCmdLength-4):"",c+=a.serviceCmdLength-4,a.cookieLength=Eu(o,c),c+=4,a.cookie=a.cookieLength?Jf(o,c,a.cookieLength-4):"",c+=a.cookieLength-4,a.flag=Eu(o,c),c+=4,a.busiBuffLength=Eu(o,c),c+=4,a.busiBuff=a.busiBuffLength?Jf(o,c,a.busiBuffLength-4):"",c+=a.busiBuffLength-4,a}catch{}}(A);return e?.busiBuff}function N0(A,e){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],a=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,a>>>=0;let c=Lb*p0>>>0;for(let d=0;d>>5)+e[3],a>>>=0,o-=(a<<4)+e[0]^a+c^(a>>>5)+e[1],o>>>=0,c-=Lb,c>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}function Xf(A,e,o,a,c,d){if(e+8>A.length)return{success:!1};let C=new Uint8Array(a),y=A.slice(e,e+8),S=new Uint8Array(8);for(let k=0;k<8;k++)S[k]=c[k]^y[k];return{success:!0,ivPreCrypt:C,ivCurCrypt:y,debiBuf:N0(S,d),bufPos:e+8}}var Tp=typeof TextDecoder<"u"?new TextDecoder:void 0;function eQ(A){let{url:e,body:o,method:a="POST",timeout:c,priority:d}=A;return new Promise((C,y)=>{if("fetch"in window)return fetch(e,{method:a,body:o,priority:d}).then(k=>k.clone().json().then(V=>({data:V}),()=>k.arrayBuffer().then(V=>({data:hK(new Uint8Array(V))||(Tp?Tp.decode(V):V)})))).then(C,y);let S=new XMLHttpRequest;S.onreadystatechange=()=>{if(S.readyState===4)if(S.status>=200&&S.status<300)try{let k=JSON.parse(S.response);C({data:k})}catch{C({data:S.response})}else y({status:S.status,statusText:S.statusText||"request failed!"})},S.timeout=c||5e3,S.open(a,e,!0),S.send(o)})}function zb(A){return KA(this,null,function*(){let e=ko(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let a=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),c=yield(yield(yield new Response(a)).blob()).arrayBuffer();return QA.debug("compressJSON ".concat(o.length," -> ").concat(c.byteLength," ").concat(ko()-e,"ms")),c}catch{return o}})}var l2=Object.prototype.hasOwnProperty,Np=A=>typeof A=="function",Ad=A=>A===void 0,Zb=A=>typeof A=="string",I2=A=>typeof A=="boolean",Xb=A=>A.isRemote,u2=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},gM=function(A){let{retryFunction:e,settings:o,onError:a,onRetrying:c,onRetryFailed:d,onRetrySuccess:C,context:y}=A;return function(){for(var S=arguments.length,k=new Array(S),V=0;VKA(this,null,function*(){let yi=y||this;try{let Ge=yield e.apply(yi,k);CA>0&&C&&C.call(this,CA),CA=0,Ye(Ge)}catch(Ge){let Bt=()=>{clearTimeout(MA),CA=0,$A=2,ve(Ge)},hi=()=>{$A!==2&&CA<(Np(J)?J():J)?(CA++,$A=1,Np(c)&&c.call(this,CA,Bt),MA=window.setTimeout(()=>{MA=-1,Be(Ye,ve)},Np(gA)?gA(CA):gA)):(Bt(),Np(d)&&d.call(this,Ge))};Np(a)?a.call(this,{error:Ge,retry:hi,reject:ve,retryFuncArgs:k,retriedCount:CA}):hi()}});return new Promise(Be)}},$b=class T9{constructor(e){Y(this,"_parentPath"),Y(this,"userId"),Y(this,"remoteUserId"),Y(this,"id"),Y(this,"sdkAppId"),Y(this,"type"),Y(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!I2(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(e){let o=new T9({id:e.id,userId:Ad(e.userId)?this.userId:e.userId,sdkAppId:Ad(e.sdkAppId)?this.sdkAppId:e.sdkAppId,type:Ad(e.type)?this.type:e.type,isLocal:Ad(e.isLocal)?this.isLocal:e.isLocal,remoteUserId:Ad(e.remoteUserId)?this.remoteUserId:e.remoteUserId});return o.bindParent(this),o}bindParent(e){let o=e.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=o,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,o){let a=this.isLocal?this.userId:this.remoteUserId,c=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(c).concat(a?"|".concat(a):"","]")),QA.log(e,o,Ad(this.userId)||function(d){if(d==null)return!0;if(typeof d=="boolean")return!1;if(typeof d=="number")return d===0;if(typeof d=="string"||typeof d=="function"||Array.isArray(d))return d.length===0;if(d instanceof Error)return d.message==="";if(u2(d))switch(Object.prototype.toString.call(d)){case"[object File]":case"[object Map]":case"[object Set]":return d.size===0;case"[object Object]":for(let C in d)if(l2.call(d,C))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,o=new Array(e),a=0;ak0,CHROME_MAJOR_VERSION:()=>id,CHROME_VERSION:()=>H0,EDGE_VERSION:()=>ek,EDG_MAJOR_VERSION:()=>U0,EDG_VERSION:()=>tk,ELECTRON_MAJOR_VERSION:()=>m2,FIREFOX_MAJOR_VERSION:()=>L0,FIREFOX_VERSION:()=>lM,HUAWEI_VERSION:()=>uk,IE_VERSION:()=>pK,IOS_MAIN_VERSION:()=>Zd,IOS_VERSION:()=>kI,IPADQQB_VERSION:()=>dM,IS_ANDROID:()=>Ha,IS_ANDROID_WEBVIEW:()=>Ck,IS_ANY_SAFARI:()=>Fp,IS_CHROME:()=>J0,IS_CHROME_OS:()=>gk,IS_CHROMIUM_128_TO_143:()=>sy,IS_CHROMIUM_BASE:()=>IE,IS_DESKTOP_IOS_CHROME:()=>D2,IS_EDG:()=>Ay,IS_EDGE:()=>$f,IS_ELECTRON:()=>mK,IS_FIREFOX:()=>er,IS_HEADLESS_CHROME:()=>p2,IS_HONOR:()=>Ik,IS_HUAWEI:()=>lk,IS_HUAWEIBROWSER:()=>zh,IS_IE:()=>B2,IS_IE8:()=>QK,IS_IOS:()=>eg,IS_IOS_13_OR_14:()=>y2,IS_IOS_15_1:()=>f2,IS_IOS_CHROME:()=>mM,IS_IPAD:()=>Gp,IS_IPADQQB:()=>x0,IS_IPAD_PRO:()=>b0,IS_IPHONE:()=>bp,IS_IPOD:()=>C2,IS_LINUX:()=>iy,IS_LOCAL:()=>Op,IS_MAC:()=>iQ,IS_MACQQB:()=>EM,IS_MIBROWSER:()=>Y0,IS_MQQB:()=>uM,IS_NATIVE_ANDROID:()=>h2,IS_OLD_ANDROID:()=>BK,IS_OPENHARMONY:()=>oy,IS_OPPOBROWSER:()=>hM,IS_SAFARI:()=>Bg,IS_SAFARI_15_1:()=>fK,IS_SAMSUNGBROWSER:()=>CM,IS_SOGOU:()=>O0,IS_SOGOUM:()=>IM,IS_TBS:()=>td,IS_UCBROWSER:()=>ck,IS_VIVOBROWSER:()=>BM,IS_WECHAT:()=>tQ,IS_WIN:()=>ty,IS_WQQB:()=>P0,IS_WX:()=>Q2,IS_X5MQQB:()=>Lp,IS_XWEB:()=>kp,MACQQB_VERSION:()=>ak,MI_VERSION:()=>Up,MQQB_VERSION:()=>ey,OPENHARMONY_VERSION:()=>V0,OPPO_VERSION:()=>dk,SAFARI_VERSION:()=>oQ,SAMSUNG_VERSION:()=>Ek,SOGOUM_VERSION:()=>F0,SOGOU_VERSION:()=>ik,TBS_VERSION:()=>ok,UA_DATA_STRING:()=>UC,USER_AGENT:()=>ed,VIVO_VERSION:()=>QM,WECHAT_VERSION:()=>nk,WQQB_VERSION:()=>rk,XWEB_VERSION:()=>sk,browserInfo:()=>nQ,getBrowserCoreNumber:()=>jl,getBrowserInfo:()=>Bk,getChromeMajorVersion:()=>pM,getDeviceModel:()=>rQ,getDeviceModelFromUA:()=>Qk,getGPUInfo:()=>Pp,getOSName:()=>El,getOSNumber:()=>xp,getOSString:()=>Yp,getOSType:()=>Q,getTerminalType:()=>Cn,getUserAgentData:()=>fM,isAMDGPU:()=>ry,isAppleSiliconGPU:()=>yK,isLocalStorageEnabled:()=>sQ,isMobile:()=>q0,isNvidiaGPU:()=>S2,isRealIOS:()=>cM,isVersionLargerThan:()=>ny,isVersionSmallerThan:()=>hk});var ed=typeof navigator>"u"?"":navigator.userAgent,Ts=A=>new RegExp(A,"i").test(ed),hg=A=>{if(Ts(A)){let e=new RegExp("".concat(A,"\\/([\\d.]+)")),o=ed.match(e);if(o&&o[1])return o[1]}return""},G0=A=>{if(Ts(A)){let e=new RegExp("".concat(A,"\\/(\\d+)")),o=ed.match(e);if(o&&o[1])return parseFloat(o[1])}return NaN},Ak=/AppleWebKit\/([\d.]+)/i.exec(ed),d2=Ak?parseFloat(Ak[1]):NaN,Gp=Ts("iPad"),b0=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ts("Macintosh"),bp=Ts("iPhone")&&!Gp,C2=Ts("iPod"),eg=bp||Gp||C2||b0,cM=()=>{try{return eg&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return eg}},Ha=Ts("Android"),k0=function(){if(Ha){let A=ed.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let e=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(e&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(e)return e}}return NaN}(),BK=Ha&&Ts("webkit")&&k0<2.3,h2=Ha&&k0<5&&d2<537,er=Ts("Firefox"),lM=hg("Firefox"),L0=G0("Firefox"),$f=Ts("Edge"),ek=hg("Edge"),Ay=Ts("Edg"),tk=hg("Edg"),U0=G0("Edg"),IM=Ts("SogouMobileBrowser"),F0=hg("SogouMobileBrowser"),O0=Ts("MetaSr\\s"),ik=hg("MetaSr\\s"),td=Ts("TBS"),ok=hg("TBS"),kp=Ts("XWEB"),sk=hg("XWEB"),QK=Ts("MSIE\\s8\\.0"),B2=Ts("MSIE\\/\\d+"),pK=function(){if(B2){let A=/MSIE\s(\d+)\.\d/.exec(ed),e=A&&parseFloat(A[1]);return!e&&/Trident\/7.0/i.test(ed)&&/rv:11.0/.test(ed)&&(e=11),e}return NaN}(),tQ=Ts("(micromessenger|webbrowser)"),nk=hg("MicroMessenger"),Lp=!td&&Ts("MQQBrowser")&&Ts("COVC"),uM=!td&&Ts("MQQBrowser")&&!Ts("COVC"),ey=uM||Lp?hg("MQQBrowser"):"",P0=!td&&Ts(" QQBrowser"),rk=hg(" QQBrowser"),EM=!td&&Ts("QQBrowserLite"),ak=hg("QQBrowserLite"),x0=!td&&Ts("MQBHD"),dM=hg("MQBHD"),ty=Ts("Windows"),iQ=!eg&&Ts("MAC OS X"),iy=!Ha&&Ts("Linux"),gk=Ts("CrOS"),Q2=Ts("MicroMessenger"),ck=Ts("UCBrowser"),mK=Ts("Electron"),Y0=Ts("MiuiBrowser"),Up=hg("MiuiBrowser"),zh=Ts("HuaweiBrowser"),lk=Ts("Huawei")||Ts("HUAWEI"),Ik=Ts("Honor")||Ts("HONOR"),uk=hg("HuaweiBrowser"),CM=Ts("SamsungBrowser"),Ek=hg("SamsungBrowser"),hM=Ts("HeyTapBrowser"),dk=hg("HeyTapBrowser"),BM=Ts("VivoBrowser"),QM=hg("VivoBrowser"),oy=Ts("OpenHarmony"),V0=hg("OpenHarmony"),pM=()=>G0("Chrome"),mM=Ts("CriOS"),IE=Ts("Chrome"),J0=!$f&&!O0&&!IM&&!td&&!kp&&!Ay&&!P0&&!Y0&&!zh&&!CM&&!hM&&!BM&&IE,p2=Ts("HeadlessChrome"),id=pM(),sy=IE&&id>=128&&id<=143,H0=hg("Chrome"),m2=G0("Electron"),Bg=!IE&&!uM&&!Lp&&!EM&&!x0&&Ts("Safari"),Fp=Bg||eg,oQ=hg("Version"),Ck=/Android.*(wv|.0.0.0)/.test(ed),kI=(()=>{if(b0)return oQ;if(eg){let A=ed.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let e=A[1];return A[2]&&(e+=".".concat(A[2])),e}}return""})();function hk(A,e){let o=A.split(".").map(c=>Number(c)),a=e.split(".").map(c=>Number(c));for(let c=0;cC)return!1}return!1}function ny(A,e){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],a=A.split(".").map(d=>Number(d)),c=e.split(".").map(d=>Number(d));for(let d=0;dy)return!0;if(C{let A=Number(kI.split(".")[0]);return A===14||A===13})(),D2=mM&&oQ==="11.1.1",Op=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),sQ=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),nQ=Bk();function Bk(){let A=new Map([[er,["Firefox",lM]],[Ay,["Edg",tk]],[J0,["Chrome",H0]],[mM,["ChiOS",hg("CriOS")]],[Bg&&!mM,["Safari",oQ]],[td,["TBS",ok]],[kp,["XWEB",sk]],[tQ&&bp,["WeChat",nk]],[P0,["QQ(Win)",rk]],[uM,["QQ(Mobile)",ey]],[Lp,["QQ(Mobile X5)",ey]],[EM,["QQ(Mac)",ak]],[x0,["QQ(iPad)",dM]],[Y0,["MI",Up]],[zh,["HW",uk]],[CM,["Samsung",Ek]],[hM,["OPPO",dk]],[BM,["VIVO",QM]],[$f,["EDGE",ek]],[IM,["SogouMobile",F0]],[O0,["Sogou",ik]]]),e="unknown",o="unknown";return A.has(!0)&&([e,o]=A.get(!0)),{name:e,version:o}}var Pr=null;function q0(){return Pr&&typeof Pr.mobile=="boolean"?Pr.mobile:Ha||eg||bp||Gp||oy}var UC="";function fM(){return KA(this,null,function*(){if(Pr)return Pr;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Pr=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!UC&&(UC="UAData: ".concat(Pr.platform,"/").concat(Pr.platformVersion),Pr.architecture&&Pr.bitness&&(UC+=" ".concat(Pr.architecture,"/").concat(Pr.bitness)),Pr.mobile&&(UC+=" mobile"),Pr.model&&(UC+=" model: ".concat(Pr.model.replace(/\s+/g,"/"))),Pr.fullVersionList&&(UC+=" ".concat(Pr.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Pr}catch{return null}})}var yM="";function Pp(){try{if(yM)return yM;let A=document.createElement("canvas"),e=A.getContext("webgl")||A.getContext("experimental-webgl");if(!e)return"";let o=e.getExtension("WEBGL_debug_renderer_info");if(o){let a=e.getParameter(o.UNMASKED_VENDOR_WEBGL),c=e.getParameter(o.UNMASKED_RENDERER_WEBGL);return yM="".concat(a," ").concat(c)}return""}catch{return""}}function ry(){try{let A=Pp();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function S2(){try{let A=Pp();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function yK(){try{return Pp().includes("Apple M")}catch{return!1}}function rQ(){return Pr?.model||Qk()||""}function Qk(){let A=ed.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var M2=new Map([[Ha,"Android"],[eg,"iOS"],[ty,"Windows"],[iQ,"MacOS"],[iy,"Linux"],[gk,"ChromeOS"]]),El=function(){return M2.get(!0)?M2.get(!0):Pr?Pr.platform:"unknown"};function xp(){return ty?1:Ha?2:iQ?3:eg?4:iy?5:gk?6:oy?7:0}function jl(){return tQ||kp?4:IE?1:Bg?2:er?3:0}var Yp=()=>{let A=El();return Pr!=null&&Pr.platformVersion?A+="/".concat(Pr.platformVersion):eg?A+="/".concat(kI):Ha&&(A+="/".concat(k0)),A+="/".concat(nQ.name,"/").concat(Bg&&!mM?nQ.version:nQ.version.split(".")[0]),Pr!=null&&Pr.architecture&&(A+="/".concat(Pr.architecture)),A};function Cn(){return Ha?4:bp?2:Gp?3:iQ?12:ty?5:iy?13:oy?22:1}function Q(){return Ha?"Android":bp?"iPhone":Gp?"iPad":iQ?"Mac":ty?"Windows":iy?"Linux":"unknown"}var R,F=new(gc(Kl(),1)).default,eA=((R=eA||{}).ROOM_DESTROY="1",R.JOIN_START="21",R.JOIN_SCHEDULE_SUCCESS="22",R.JOIN_SIGNAL_CONNECTION_START="23",R.JOIN_SIGNAL_CONNECTION_END="24",R.JOIN_SEND_CMD="25",R.JOIN_RECEIVED_CMD_RES="26",R.JOIN_SUCCESS="27",R.JOIN_FAILED="28",R.LEAVE_START="51",R.LEAVE_SEND_CMD="52",R.LEAVE_SUCCESS="53",R.PUBLISH_START="61",R.SEND_FIRST_VIDEO_FRAME="62",R.PUBLISH_FAILED="63",R.SUBSCRIBE_START="81",R.SUBSCRIBE_SUCCESS="82",R.SUBSCRIBE_FAILED="84",R.UNSUBSCRIBE_SUCCESS="83",R.LOCAL_TRACK_CAPTURE_START="101",R.LOCAL_TRACK_CAPTURE_SUCCESS="102",R.LOCAL_TRACK_CAPTURE_FAILED="103",R.LOCAL_TRACK_PUBLISHED="104",R.LOCAL_TRACK_UNPUBLISHED="105",R.LOCAL_TRACK_REPLACED="106",R.SWITCH_DEVICE_SUCCESS="107",R.TRACK_MUTED="108",R.TRACK_UNMUTED="109",R.REMOTE_TRACK_SUBSCRIBED="110",R.REMOTE_TRACK_UNSUBSCRIBED="111",R.LOCAL_TRACK_RECAPTURE="112",R.LOCAL_AUDIO_STARTED="113",R.LOCAL_AUDIO_STOPPED="114",R.REMOTE_AUDIO_STARTED="115",R.REMOTE_AUDIO_STOPPED="116",R.LOCAL_TRACK_STOPPED="117",R.LOCAL_VIDEO_TRACK_PREPROCESSED="118",R.PLAY_TRACK_START="151",R.PLAYER_STATE_CHANGED="152",R.VIDEO_LOADED_DATA="153",R.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",R.AUDIO_CONTEXT_LONG_SUSPENDED="155",R.REMOTE_VIDEO_PLAY_START="156",R.REMOTE_VIDEO_PLAY_FINISH="157",R.SIGNAL_CONNECTION_STATE_CHANGED="201",R.PEER_CONNECTION_STATE_CHANGED="202",R.SINGLE_CONNECTION_STAT="203",R.SPC_RECONNECTED="204",R.HEARTBEAT_REPORT="251",R.RECEIVED_PUBLISHED_USER_LIST="252",R.REMOTE_PUBLISH_STATE_CHANGED="253",R.AUDIO_LEVEL_INTERVAL="260",R.NETWORK_QUALITY="261",R.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",R.QUALITY_LIMITATION_CHANGED="263",R.LOG="264",R.AUDIO_PROCESSOR_DEBUG="265",R.SSO_SWITCH="266",R.SEI_MESSAGE="267",R.USER_PAUSE_IN_PIP="268",R.USER_RESUME_IN_PIP="269",R.ENTER_PICTURE_IN_PICTURE="270",R.LEAVE_PICTURE_IN_PICTURE="271",R.SWITCH_ROOM_START="401",R.SWITCH_ROOM_SUCCESS="407",R.SWITCH_ROOM_FAILED="408",R),nA=eA,_A=new class{constructor(){Y(this,"enable",!1),Y(this,"ssoFailCount",0),F.on("22",A=>{let{schedule:e}=A;var o;(o=e?.config)!=null&&o.sso&&F.emit("266",{enable:!0})}),F.on("266",A=>{let{enable:e}=A;this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&F.emit("266",{enable:!1})}},ZA=class N9{constructor(){Y(this,"_isEnableUploadLog",!0),Y(this,"_localJoinedUser",new Map),Y(this,"_queue",[]),Y(this,"_timeoutId",-1),Y(this,"_logLevel",1),Y(this,"_logLevelToUpload",2),!i0&&!o0&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){F.on(nA.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:o}=e;var a;(a=o?.config)!=null&&a.logLevelToUpload&&WB[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),F.on(nA.JOIN_START,e=>{let{params:o}=e;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),F.on(nA.LEAVE_SUCCESS,e=>{let{room:o}=e;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return e;let o=0;for(;o{let{userId:d,sdkAppId:C}=c;e.map.has(d)?e.map.get(d).logs.push(a):e.map.set(d,{userId:d,sdkAppId:C,logs:[a]})});else if(Yn(a.userId)&&bn(a.sdkAppId)){let{userId:c,sdkAppId:d}=a;e.map.has(c)?e.map.get(c).logs.push(a):e.map.set(c,{userId:c,sdkAppId:d,logs:[a]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,o)),e}upload(){return KA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:e,splicedQueue:o}=this.getLogsToUpload();if(e.size===0)return;try{let c=[...e.values()];for(let d=0;dgA.log).join(` -`)},V=JSON.stringify(k),J=_A.enable?AQ(k,2002,y):V;yield this.uploadLogWithRetry(J,y,J instanceof Uint8Array,V),S.forEach(gA=>gA.uploaded=!0)}}catch{}let a=o.filter(c=>!c.uploaded);a.length>0&&(this._queue=a.concat(this._queue))})}uploadLogWithRetry(e,o,a,c){return gM({retryFunction:()=>eQ({url:Hf(o,bI.LOG),body:e,timeout:5e3,priority:"low"}).then(d=>{a&&d.data!=="ok"&&(_A.handleUploadFailed(),this.uploadLogWithRetry(c,o,!1,c))}),settings:{retries:3,timeout:2e3},onError:d=>{let{retry:C}=d;C()}})()}getPrefix(e){let o=new Date;return o.setTime(Lf()),"[".concat(mb(o),"] <").concat(WB[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Je(WB[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(Yn(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch{return""}}addLogToQueue(e,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],c=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0,C={log:o.reduce((y,S)=>"".concat(y," ").concat(this.logChunkToString(S)).trim(),""),level:e,userId:c,sdkAppId:d,forAllJoinedClients:a};F.emit(nA.LOG,{log:C}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(C)}log(e,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],c=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0;var C;if(o.unshift(this.getPrefix(e)),this.addLogToQueue(e,o,a,c,d),e{let e=16*Math.random()|0;return(A=="x"?e:3&e|8).toString(16)})},jA=new class{constructor(){Y(this,"_prefix","TRTC"),Y(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){sQ()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let e=localStorage.getItem(A);if(!e)return!1;let o=JSON.parse(e);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(sQ())try{for(let[A,e]of this._queue)localStorage.setItem(A,JSON.stringify(e))}catch(A){QA.warn(A)}}getItem(A){if(!sQ())return null;try{let e=localStorage.getItem(this.getRealKey(A));if(!e)return null;let o=JSON.parse(e);return o&&o.expiresIn>=Date.now()?o.value:null}catch(e){QA.warn(e)}}setItem(A,e){if(sQ())try{let o={expiresIn:Date.now()+r0,value:e};this._queue.set(this.getRealKey(A),o)}catch(o){QA.warn(o)}}deleteItem(A){if(!sQ())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(e){return QA.warn(e),!1}}clear(){if(sQ())try{localStorage.clear()}catch(A){QA.warn(A)}}},te={};Hh(te,{HTTPS_API:()=>bk,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>L2,IS_GET_CAPABILITIES_SUPPORTED:()=>k2,IS_GET_SETTINGS_SUPPORTED:()=>Cy,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>Pk,IS_INSERTABLE_STREAM_SUPPORTED:()=>Kp,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>uQ,IS_RTC_RTP_SENDER_SUPPORTED:()=>FC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>e_,IS_SEI_SUPPORTED:()=>xk,IS_SPC_SUPPORTED:()=>GM,basis:()=>F2,capabilityCheck:()=>Jk,checkSystemRequirementsInternal:()=>Nk,decodeSupportStatus:()=>Tk,detectH264SupportedByFakeStreaming:()=>G2,detectVideoCodecCapabilities:()=>kM,detectVideoDecoderCapabilities:()=>qk,detectVideoEncoderCapabilities:()=>Hk,encodeSupportStatus:()=>wM,getBrowserInfo:()=>vM,getDisplayResolution:()=>nd,getH264ProfileLevelIds:()=>x2,isAddTransceiverSupported:()=>Xd,isBrowserSupported:()=>wk,isCanvasCaptureStreamAPISupported:()=>TM,isCanvasSmallStreamSupported:()=>A_,isGetReceiversSupported:()=>dy,isGetSendersSupported:()=>LI,isGetTransceiversSupported:()=>IQ,isGetUserMediaSupported:()=>kk,isMediaDevicesSupported:()=>_k,isMediaSessionSupported:()=>U2,isMediaStreamTrackGeneratorSupported:()=>MK,isMediaStreamTrackProcessorSupported:()=>RM,isReplaceTrackSupported:()=>b2,isRequestVideoFrameCallbackSupported:()=>jp,isSIMDSupported:()=>bM,isScaleResolutionDownBySupported:()=>Uk,isScreenCaptureApiAvailable:()=>qp,isSelectedCandidatePair:()=>_M,isSetParametersSupported:()=>Ok,isSetSinkIdSupported:()=>RK,isSmallStreamSupported:()=>NM,isStopTransceiverSupported:()=>ia,isTRTCSupported:()=>vK,isUnifiedPlanDefault:()=>Fk,isUsedInHttpProtocol:()=>du,isWebAudioSupported:()=>Lk,isWebCodecSupported:()=>t_,isWebCodecsSupported:()=>$0,isWebRTCSupported:()=>hy,isWebTransportSupported:()=>By});var ke={};Hh(ke,{AUDIO_LEVEL_SCALE:()=>od,AlphaStitchingType:()=>Iy,AudioCodecPipelineType:()=>lQ,AudioDecoderDowngradeState:()=>DM,AudioPlayerMode:()=>W0,AudioType:()=>v2,BASIC_TYPE:()=>Dk,BannedReason:()=>Qg,CONNECTION_CLOSED_REASON:()=>Ht,CheckPermissionType:()=>cr,ClientEvent:()=>Xe,CodecType:()=>SM,ConnectionEvent:()=>xo,ConnectionState:()=>ay,DECODE_FAILED_ERROR_CODE:()=>MM,DenoiserMode:()=>Vp,DeviceType:()=>Sk,FacingMode:()=>mk,FrameWorkType:()=>to,LeaveReason:()=>fk,LocalTrackEvent:()=>So,MULTI_VIDEO_DATA_TYPE:()=>ly,MediaType:()=>K0,MediaTypeLabel:()=>DK,MonitorEventId:()=>dl,MutedFlag:()=>Zn,NetworkQualityValue:()=>uE,PlayerState:()=>uo,ReceiveMode:()=>Wl,RemoteStreamType:()=>cy,RemoteTrackEvent:()=>hn,RoomEvent:()=>Io,SMALL_MODE:()=>Hp,SceneNumber:()=>qa,StreamEvent:()=>Si,StreamType:()=>cQ,SubscribeMediaType:()=>yk,TIMER_TYPE:()=>Z0,TRACK_ACTION:()=>pk,TRACK_KIND:()=>aQ,TrackEvent:()=>Yo,UserRole:()=>Fc,UserRoleNumber:()=>ts,VideoCodec:()=>Cl,VideoCodecPipelineType:()=>Jp,VideoContentHint:()=>z0,VideoDecoderDowngradeState:()=>gy,VideoPlayerMode:()=>j0,VideoType:()=>gQ});var Te,he,lt,gi,et,Ke,dA,pt,At,Vi,li,to=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(to||{}),xo=((li=xo||{}).TRACK_ADDED="track-added",li.TRACK_UPDATED="track-updated",li.TRACK_SUBSCRIBED="track-subscribed",li.STREAM_ADDED="stream-added",li.STREAM_REMOVED="stream-removed",li.STREAM_UPDATED="stream-updated",li.STREAM_PUBLISHED="stream-published",li.STREAM_SUBSCRIBED="stream-subscribed",li.STREAM_UNSUBSCRIBED="stream-unsubscribed",li.STATE_CHANGED="state-changed",li.ERROR="error",li.CONNECTION_STATE_CHANGED="connection-state-changed",li.FIREWALL_RESTRICTION="firewall-restriction",li.SEI_MESSAGE="sei-message",li.CLOSED="closed",li),Ht=(A=>(A.REMOTE_LEAVE="remote user exitRoom",A.REMOTE_UNPUBLISH="remote user unpublished",A.LOCAL_LEAVE="you exitRoom",A.LOCAL_UNPUBLISH="you unpublished",A.LOCAL_UNSUBSCRIBE="you unsubscribed",A.SWITCH_ROLE="you switch role to audience",A))(Ht||{}),Xe=((Vi=Xe||{}).STREAM_ADDED="stream-added",Vi.STREAM_REMOVED="stream-removed",Vi.STREAM_UPDATED="stream-updated",Vi.STREAM_SUBSCRIBED="stream-subscribed",Vi.CONNECTION_STATE_CHANGED="connection-state-changed",Vi.PEER_JOIN="peer-join",Vi.PEER_LEAVE="peer-leave",Vi.MUTE_AUDIO="mute-audio",Vi.MUTE_VIDEO="mute-video",Vi.UNMUTE_AUDIO="unmute-audio",Vi.UNMUTE_VIDEO="unmute-video",Vi.CLIENT_BANNED="client-banned",Vi.NETWORK_QUALITY="network-quality",Vi.AUDIO_VOLUME="audio-volume",Vi.SEI_MESSAGE="sei-message",Vi.ERROR="error",Vi),Si=((At=Si||{}).PLAYER_STATE_CHANGED="player-state-changed",At.SCREEN_SHARING_STOPPED="screen-sharing-stopped",At.CONNECTION_STATE_CHANGED="connection-state-changed",At.DEVICE_AUTO_RECOVERED="device-auto-recovered",At.ERROR="error",At),So=((pt=So||{}).DEVICE_AUTO_RECOVERED="1",pt.DEVICE_RECOVER_FAILED="5",pt.DEVICE_CHANGED="2",pt.ERROR="3",pt.PUBLISH_STATE_CHANGED="4",pt.ENCODE_FAILED="6",pt.TRACK_ENDED="7",pt.RENDER="render",pt),uo=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(uo||{}),Io=((dA=Io||{}).PEER_JOIN="peer-join",dA.PEER_LEAVE="peer-leave",dA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",dA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",dA.BANNED="banned",dA.NETWORK_QUALITY="network-quality",dA.AUDIO_VOLUME="audio-volume",dA.SEI_MESSAGE="sei-message",dA.ERROR="error",dA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",dA.REMOTE_PUBLISHED="remote-published",dA.REMOTE_UNPUBLISHED="remote-unpublished",dA.FIREWALL_RESTRICTION="firewall-restriction",dA.HEARTBEAT_REPORT="heartbeat-report",dA.CUSTOM_MESSAGE="custom-message",dA.LAYER_DATA="layerData",dA.FIRST_VIDEO_FRAME="first-video-frame",dA.FIRST_FRAME_RENDER="first-frame-render",dA.DUMP="dump",dA.AUDIO_FRAME="audio-frame",dA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",dA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",dA.NTP_TIME_UPDATED="ntp-time-updated",dA.DATA_CHANNEL_MESSAGE="data-channel-message",dA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",dA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",dA),Yo=((Ke=Yo||{}).PLAYER_STATE_CHANGED="player-state-changed",Ke.MUTE="mute",Ke.UNMUTE="unmute",Ke.ERROR="error",Ke.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",Ke.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",Ke.FIRST_VIDEO_FRAME="first-video-frame",Ke.FIRST_FRAME_RENDER="first-frame-render",Ke.VIDEO_SIZE_CHANGED="video-size-changed",Ke),hn=(A=>(A.DECODE_FAILED="decode-failed",A.DECODE_FAILED_DURING_CALL="decode-failed-during-call",A.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",A.REMOTE_PUBLISH_CHANGED="remote-publish-changed",A.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",A))(hn||{}),Zn=((et=Zn||{})[et.VIDEO=1]="VIDEO",et[et.SMALL=2]="SMALL",et[et.AUX=4]="AUX",et[et.AUDIO=8]="AUDIO",et[et.VIDEO_MUTE=16]="VIDEO_MUTE",et[et.AUX_MUTE=32]="AUX_MUTE",et[et.AUDIO_MUTE=64]="AUDIO_MUTE",et),qa=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(qa||{}),ts=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(ts||{}),Fc=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(Fc||{}),ay=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(ay||{}),DM=((gi=DM||{}).INITIALIZED="INITIALIZED",gi.STARTING="STARTING",gi.STARTED="STARTED",gi.FAILED="FAILED",gi),gy=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(gy||{}),aQ=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(aQ||{}),pk=(A=>(A.ADD="add",A.REMOVE="remove",A))(pk||{}),K0=(A=>(A[A.NULL=0]="NULL",A[A.AUDIO=1]="AUDIO",A[A.AUX_VIDEO=2]="AUX_VIDEO",A[A.BIG_VIDEO=4]="BIG_VIDEO",A[A.SMALL_VIDEO=8]="SMALL_VIDEO",A))(K0||{}),DK={1:"audio",2:"auxVideo",4:"video"},v2=((lt=v2||{})[lt.opus=111]="opus",lt),gQ=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(gQ||{}),cQ=(A=>(A.Big="big",A.Small="small",A))(cQ||{}),cy=(A=>(A.Main="main",A.Aux="auxiliary",A))(cy||{}),ly=(A=>(A[A.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",A[A.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",A[A.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",A[A.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",A[A.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",A))(ly||{}),dl=((he=dl||{})[he.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",he[he.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",he[he.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",he[he.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",he[he.MUTE_AUDIO=32772]="MUTE_AUDIO",he[he.MUTE_VIDEO=32773]="MUTE_VIDEO",he[he.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",he[he.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",he[he.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",he[he.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",he[he.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",he[he.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",he[he.SWITCH_CAMERA=32780]="SWITCH_CAMERA",he[he.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",he[he.REPLACE_VIDEO=32782]="REPLACE_VIDEO",he[he.REPLACE_AUDIO=32783]="REPLACE_AUDIO",he[he.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",he[he.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",he[he.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",he[he.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",he[he.JOIN=32788]="JOIN",he[he.LEAVE=32789]="LEAVE",he[he.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",he[he.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",he[he.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",he[he.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",he[he.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",he[he.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",he[he.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",he[he.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",he[he.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",he[he.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",he[he.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",he[he.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",he[he.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",he[he.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",he[he.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",he[he.PUBLISH_AUX=32805]="PUBLISH_AUX",he[he.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",he[he.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",he[he.VIDEO_ENCODER=4004]="VIDEO_ENCODER",he[he.VIDEO_DECODER=4005]="VIDEO_DECODER",he),uE=(A=>(A[A.UNKNOWN=0]="UNKNOWN",A[A.EXCELLENT=1]="EXCELLENT",A[A.GOOD=2]="GOOD",A[A.POOR=3]="POOR",A[A.BAD=4]="BAD",A[A.VERY_BAD=5]="VERY_BAD",A[A.DISCONNECTED=6]="DISCONNECTED",A))(uE||{}),Wl=(A=>(A[A.MANUAL=0]="MANUAL",A[A.AUTO_AUDIO=1]="AUTO_AUDIO",A[A.AUTO_VIDEO=2]="AUTO_VIDEO",A[A.AUTO_ALL=3]="AUTO_ALL",A))(Wl||{}),mk=(A=>(A.user="user",A.environment="environment",A))(mk||{}),j0=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",A[A.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",A))(j0||{}),W0=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(W0||{}),Qg=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(Qg||{}),fk=(A=>(A[A.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",A[A.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",A[A.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",A[A.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",A[A.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",A[A.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",A[A.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",A[A.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",A[A.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",A))(fk||{}),od=1e8,Vp=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(Vp||{}),yk=class{constructor(){Y(this,"mediaType",0)}set audio(A){A?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(A){A?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(A){A?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(A){A?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},Dk=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(Dk||{}),Cl=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(Cl||{}),Jp=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.DUMP=1]="DUMP",A[A.SEI=2]="SEI",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(Jp||{}),lQ=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",A[A.DUMP=2]="DUMP",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(lQ||{}),SM=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(SM||{}),MM=((Te=MM||{})[Te.SUCCESS=0]="SUCCESS",Te[Te.FAILED=1]="FAILED",Te[Te.WEBCODEC_INIT=2]="WEBCODEC_INIT",Te[Te.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",Te[Te.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",Te[Te.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",Te[Te.WASM_INIT=6]="WASM_INIT",Te[Te.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",Te[Te.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",Te[Te.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",Te[Te.TEST=10]="TEST",Te[Te.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",Te),z0=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(z0||{}),Z0=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(Z0||{}),Hp=(A=>(A.CANVAS="canvas",A.API="api",A))(Hp||{}),cr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(cr||{}),Sk=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(Sk||{}),Iy=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(Iy||{}),Mo={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX",SWITCH_PLAYBACK_QUALITY_TIMEOUT:"SWITCH_PLAYBACK_QUALITY_TIMEOUT"},cc={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(c,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:a,value:c}=A,d="".concat(e||o.name),C="";return C=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(C," when calling ").concat(a,"(), received type: ").concat(Cg(c),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' cannot be '").concat(c,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:a,value:c}=A,d="".concat(e||o.name),C="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(C," when calling ").concat(a,"(), received type: ").concat(Cg(c),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(c,".")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,fnName:a,value:c}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(c,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,fnName:a,value:c}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(c,".")},API_CALL_TIMEOUT:A=>"".concat(A.commandDesc||A.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:A=>"SignalChannel setup failure: (errorCode: ".concat(A.errorCode,", errorMsg: ").concat(A.errorMsg," })."),ERROR_MESSAGE(A){let e="".concat(A.type," failed");return A.message&&(e="".concat(e,": ").concat(A.message,".")),e},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:A=>"exchange sdp failed ".concat(A.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:A=>"'".concat(A,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:A=>"'".concat(A,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(A){let{error:e,code:o}=A;return"Failed to join room - ".concat(e," code: ").concat(o)},REJOIN_ROOM_FAILED:A=>"reJoin room: ".concat(A.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:A=>"duplicate ".concat(A," stream publishing, please unpublish your prev ").concat(A," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(A){let{message:e,userId:o,streamType:a}=A;return"failed to subscribe ".concat(o," ").concat(a," stream, reason: ").concat(e,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:A=>"switchRole failed, errCode: ".concat(A.code," errMsg: ").concat(A.message,"."),CLIENT_BANNED:A=>"client was banned because of ".concat(A.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:A=>"startPublishCDNStream failed, errMsg: ".concat(A.message,"."),STOP_PUBLISH_CDN_FAILED:A=>"stopPublishCDNStream failed, errMsg: ".concat(A.message,"."),INVALID_STREAM_ID:A=>"'".concat(A,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:A=>"cannot replace ".concat(A.kind," track because stream has not ").concat(A.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:A=>"startMixTranscode failed, errMsg: ".concat(A.message,"."),STOP_MIX_TRANSCODE_FAILED:A=>"stopMixTranscode failed, errMsg: ".concat(A.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:A=>"'".concat(A,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:A=>{let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:e,fnName:o,type:a}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},PLAY_FAILED:A=>"".concat(A.media," play failed, browser exception: ").concat(A.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:A=>"".concat(A,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:A=>"".concat(A.signalResponse," failed, response code is ").concat(A.code," , errMsg: ").concat(A.message,"."),CATCH_HANDLER_ERROR(A){let{name:e,event:o}=A;return"an error was caught in ".concat(e,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:e}=A;return"experimental api ".concat(e," does not exist.")},REPEAT_JOIN:A=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(A){let{funName:e}=A;return"failed to call ".concat(e,"() because client was destroyed.")},SEI_NOT_SUPPORT:A=>"not support to sendSEIMessage".concat(A===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:A=>{let{isSize:e,name:o,timesInSecond:a,maxSizeInSecond:c}=A;return"api ".concat(o," call ").concat(e?"size":"times"," is over ").concat(e?"".concat(c," bytes"):a," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let e;return e=A.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(A.userId," ").concat(A.streamType," stream aborted, reason: remote user ").concat(A.userId," unpublished stream."):"API aborted, reason: ".concat(A.message),e},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:A=>"'streamType' is required when 'userId' is not '*', calling ".concat(A,"()"),SWITCH_PLAYBACK_QUALITY_TIMEOUT:A=>"switchPlaybackQuality timeout: waiting for first frame of user ".concat(A.userId,".")},R2=(A,e)=>e?"".concat(qh,"/").concat(A,"/").concat(e):"".concat(qh,"/").concat(A,"/index.html"),Mk=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let A=localStorage==null?void 0:localStorage.getItem(JS);if(A){A=JSON.parse(A);let e=document.createElement("script");e.type="text/javascript",e.text=A.message,document.body.appendChild(e);let o=window.TRTC_ERROR_INFO,a=window.TRTC_ERROR_LINK;return document.body.removeChild(e),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:a}}return{}};function Xo(A){let{key:e,data:o,link:a,addDocLink:c=!0}=A,d="",C="",y="";Ra(cc[e])?d=cc[e](o):Yn(cc[e])&&(d=cc[e]);let{TRTC_ERROR_INFO:S,TRTC_ERROR_LINK:k}=Mk();a?y="".concat(a.className,".html#").concat(a.fnName):k&&k[e]&&(Ra(k[e])?y=k[e](o):Yn(k[e])&&(y=k[e]));let V=d;return Wd()&&(S&&S[e]&&(Ra(S[e])?C=S[e](o):Yn(S[e])&&(C=S[e])),C&&(V=c?"".concat(C,` -请查看文档: `).concat(R2("zh-cn",y),` +`}}),Sb=Kh(A=>{var e=kx(),o=Lx();A.write=o,A.parse=e.parse,A.parseParams=e.parseParams,A.parseFmtpConfig=e.parseFmtpConfig,A.parsePayloads=e.parsePayloads,A.parseRemoteCandidates=e.parseRemoteCandidates,A.parseImageAttributes=e.parseImageAttributes,A.parseSimulcastStreamList=e.parseSimulcastStreamList}),BK=gc(jl()),WB=((lo=WB||{})[lo.INVALID_PARAMETER=4096]="INVALID_PARAMETER",lo[lo.INVALID_OPERATION=4097]="INVALID_OPERATION",lo[lo.NOT_SUPPORTED=4098]="NOT_SUPPORTED",lo[lo.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",lo[lo.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",lo[lo.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",lo[lo.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",lo[lo.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",lo[lo.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",lo[lo.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",lo[lo.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",lo[lo.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",lo[lo.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",lo[lo.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",lo[lo.CLIENT_BANNED=16448]="CLIENT_BANNED",lo[lo.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",lo[lo.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",lo[lo.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",lo[lo.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",lo[lo.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",lo[lo.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",lo[lo.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",lo[lo.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",lo[lo.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",lo[lo.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",lo[lo.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",lo[lo.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",lo[lo.API_CALL_ABORTED=16461]="API_CALL_ABORTED",lo[lo.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",lo[lo.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",lo[lo.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",lo[lo.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",lo[lo.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",lo[lo.UNKNOWN=65535]="UNKNOWN",lo),Ct=WB,Ux=class extends Error{constructor(A){let{name:e="RtcError",message:o,code:a=Ct.UNKNOWN,extraCode:l=0,constraint:d}=A,h="<".concat(function(S){for(let k in Ct)if(Ct[k]===S)return k;return"UNKNOWN"}(a)," 0x").concat(a.toString(16),">"),y="".concat(o).concat(d?" constraint: ".concat(d):"").concat(o!=null&&o.includes(h)?"":" ".concat(h));super(y),Y(this,"code"),Y(this,"extraCode"),Y(this,"message"),Y(this,"originMessage"),Y(this,"name"),Y(this,"constraint"),this.code=a,this.extraCode=l,this.name=e,this.message=y,this.constraint=d,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},gi=Ux,Mb=0,Fx=!0,zB=function(A){Mb=A;let e=new Date;e.setTime(e.getTime()+A),pA[Fx?"info":"debug"]("baseTime from server: ".concat(e," offset: ").concat(A)),Fx=!1},Ox=function(){return Mb},Of=function(){return Date.now()+Mb},Px=function(){let A=new Date;return A.setTime(Of()),A.toLocaleString()},vb=function(A){let e=String(A.getMilliseconds());return"padStart"in String.prototype&&(e=e.toString().padStart(3,"0")),"".concat(A.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1"),":").concat(e)},Hd={};jh(Hd,{REPORT_TYPE:()=>G0,buildSSOPackage:()=>iQ,bytes2ms:()=>M0,calculateScaleResolutionDownNumber:()=>N0,concatArrayBuffers:()=>lM,convertObjectNumberToInt:()=>T0,copyProperties:()=>c2,deepClone:()=>$f,deepCloneBasic:()=>Ay,deepMerge:()=>Xh,delay:()=>OC,fibonacci:()=>zf,formatedTime:()=>B2,getConstructorName:()=>nM,getContainerFromElement:()=>zb,getEnv:()=>r2,getFirst16Bits:()=>p2,getInternalVersion:()=>C2,getLast16Bits:()=>b0,getLoggerUrl:()=>jf,getMediaStreamTrackInfo:()=>ek,getMuteStateFromFlag:()=>Np,getNetworkType:()=>D0,getNumNetworkType:()=>Wf,getReconnectionTimeout:()=>Tp,getStringByteLength:()=>_0,getTestSignalDomain:()=>a2,getTurnServer:()=>h2,getUint32Version:()=>Xb,getValueType:()=>Cg,getViewListFromView:()=>gM,glog:()=>I2,ipv4ToUint32:()=>aM,isArray:()=>wa,isAudioWorkletSupported:()=>u2,isBoolean:()=>Nr,isConstructor:()=>Xf,isEmpty:()=>R0,isFunction:()=>Ra,isLangChinese:()=>Wd,isMediaStreamTrack:()=>jb,isNumber:()=>kn,isObject:()=>XE,isOverseaSdkAppId:()=>Kd,isPlainObject:()=>IE,isPortrait:()=>Zb,isPromise:()=>Zf,isRemoteTrack:()=>Wb,isRotate90Or270:()=>tQ,isSetSinkIdSupported:()=>E2,isString:()=>Vn,isUndefined:()=>Ke,isVideoMixerOutputTrack:()=>Gp,loadImage:()=>cM,loadVideo:()=>Q2,ms2bytes:()=>l2,ms2samples:()=>v0,normalizeUrl:()=>Ak,performanceNow:()=>ko,promiseAny:()=>rM,samples2ms:()=>Kb,setNetworkTypeFromWebRTC:()=>S0,stringify:()=>zd,stringifyIncludeValue:()=>w0,throttlePromise:()=>$b});var xx={};jh(xx,{ASR_ROBOT_FROM_TYPE:()=>B0,AUDIO_MUTE_BIT:()=>Yf,AUDIO_STAT_BIT:()=>ZS,AUX_STAT_BIT:()=>zS,AUX_STREAM_MSID:()=>jx,BACKEND_ENV:()=>Pf,BASE_DOC_URL:()=>Wh,BASE_HOST:()=>Vx,CAPABILITIES_KEYS:()=>Ob,CLASS_NAME:()=>vK,CLOUD_CONSOLE_URL:()=>mK,CROSS_ROOM_BIT:()=>Gb,DATA_CHANNEL_FROM_TYPE_BIT:()=>$B,DATA_FREEZE_TIMING:()=>Ub,DOC_BILLING_CN:()=>a0,DOC_BILLING_OVERSEA:()=>_b,DOC_URL:()=>fK,DTLS_STATE_UNKNOWN:()=>zh,ENV_NAME:()=>ZB,EXCHANGE_SDP_TIMEOUT:()=>$x,IS_WORKER:()=>n0,IS_WORKLET:()=>r0,KIBANA_EVENT:()=>Ja,LOCAL_STREAM_PUBLISH_STATE:()=>A2,LOGGER_CMD_TYPE:()=>kI,LOGGER_DOMAIN:()=>bI,LOGGER_DOMAIN_OVERSEA:()=>vp,LOG_LEVEL:()=>XB,LOG_LEVEL_NAME:()=>wK,MAIN_STREAM_MSID:()=>Eu,MAX_RTT:()=>h0,MICROPHONE_COMMUNICATIONS:()=>RK,MICROPHONE_DEFAULT:()=>AM,MUTE_ALL_BIT:()=>Kx,NAME:()=>YA,NETWORK_TYPE:()=>g0,NOT_SUPPORTED_H264:()=>d0,PAUSED_RETRY_COUNT:()=>_p,PEERCONNECTION_CONNECTING_TIMEOUT:()=>Fb,PEER_CONNECTION_STATE:()=>ho,PEER_LEAVE_REASON:()=>i2,RECOVER_CAPTURE_INTERVAL:()=>tM,REMOTE_STREAM_TYPE_AUX:()=>bb,REMOTE_STREAM_TYPE_MAIN:()=>l0,RENDER_FREEZE_TIMING:()=>e2,SCHEDULE_DOMAIN:()=>eQ,SCHEDULE_TIMEOUT:()=>t2,SDP_SEMANTICS_PLAN_B:()=>E0,SDP_SEMANTICS_UNIFIED_PLAN:()=>$S,SECOND_HOST:()=>Jx,SIGNAL_PING_PONG_INTERVAL:()=>lE,SIGNAL_PING_TIMEOUT:()=>Hx,SIGNAL_RECONNECTION_COUNT:()=>yK,SMALL_STAT_BIT:()=>Nb,SPEAKER_DEFAULT:()=>C0,STORAGE_EXPIRES_TIME:()=>c0,STREAM_TYPE_BIG:()=>SK,STREAM_TYPE_SMALL:()=>MK,SUBSCRIBE_SMALL_RETRY_COUNT:()=>eM,SYNC_USER_LIST_INTERVAL:()=>DK,Scene:()=>xf,THIRD_HOST:()=>pK,TRANSPORT_DIRECTION:()=>Xn,TRTC_ERROR_ASSISTANCE:()=>KS,TRTC_QUALITY_BAD:()=>Vf,TRTC_QUALITY_DISCONNECTED:()=>Zx,TRTC_QUALITY_EXCELLENT:()=>I0,TRTC_QUALITY_GOOD:()=>AQ,TRTC_QUALITY_POOR:()=>Wx,TRTC_QUALITY_UNKNOWN:()=>kb,TRTC_QUALITY_VERY_BAD:()=>zx,UPDATE_OFFER_TIMEOUT:()=>Xx,VIDEO_MUTE_BIT:()=>XS,VIDEO_STAT_BIT:()=>WS,WEBGL_ATTRIBUTES:()=>Pb,audioProfileMap:()=>Rp,defaultBigVideoProfile:()=>jS,defaultSmallVideoProfile:()=>qx,getRetryCount:()=>Jf,getScriptDir:()=>QK,innerVersion:()=>s0,loggerProxy:()=>wb,screenProfileMap:()=>Tb,setLoggerProxy:()=>qS,setRetryCount:()=>u0,setVersion:()=>Yx,version:()=>qd,videoProfileMap:()=>FC});var s0="4.15.00.1600",qd="5.0.0";function Yx(A){qd=A;let[e,o,a]=A.split(".").map(l=>parseInt(l,10));s0="".concat(e,".").concat(Math.min(15,o),".").concat(Math.min(15,a),".").concat(o.toString().padStart(2,"0")).concat(a.toString().padStart(2,"0"))}var Rb,cE,n0=typeof importScripts<"u",r0=typeof registerProcessor<"u",QK=()=>{let A=n0?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},wb="",qS=A=>wb=A,Vx="web.sdk.qcloud.com",Jx="web.sdk.tencent.cn",pK="web.sdk.cloud.tencent.cn",mK="https://console.cloud.tencent.com/trtc",Wh="https://".concat(Vx,"/trtc/webrtc/doc"),fK="".concat(Wh,"/zh-cn/"),a0="https://cloud.tencent.com/document/product/647/85386",_b="https://trtc.io/document/56025",bI="https://yun.tim.qq.com",vp="https://apisgp.my-imcloud.com",KS="trtc_error_assistance",kI={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},ZB={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},XB=((cE=XB||{})[cE.TRACE=0]="TRACE",cE[cE.DEBUG=1]="DEBUG",cE[cE.INFO=2]="INFO",cE[cE.WARN=3]="WARN",cE[cE.ERROR=4]="ERROR",cE[cE.NONE=5]="NONE",cE),Hx=18e3,lE=2e3,g0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},c0=6048e5,Rp={standard:{sampleRate:48e3,channelCount:1,bitrate:40},"standard-stereo":{sampleRate:48e3,channelCount:2,bitrate:64},high:{sampleRate:48e3,channelCount:1,bitrate:128},"high-stereo":{sampleRate:48e3,channelCount:2,bitrate:192}},FC={"120p":{width:160,height:120,frameRate:15,bitrate:200},"120p_2":{width:160,height:120,frameRate:15,bitrate:100},"180p":{width:320,height:180,frameRate:15,bitrate:350},"180p_2":{width:320,height:180,frameRate:15,bitrate:150},"240p":{width:320,height:240,frameRate:15,bitrate:400},"240p_2":{width:320,height:240,frameRate:15,bitrate:200},"360p":{width:640,height:360,frameRate:15,bitrate:800},"360p_2":{width:640,height:360,frameRate:15,bitrate:400},"480p":{width:640,height:480,frameRate:15,bitrate:900},"480p_2":{width:640,height:480,frameRate:15,bitrate:500},"720p":{width:1280,height:720,frameRate:15,bitrate:1500},"1080p":{width:1920,height:1080,frameRate:15,bitrate:2e3},"1440p":{width:2560,height:1440,frameRate:30,bitrate:4860},"4K":{width:3840,height:2160,frameRate:30,bitrate:9e3}},jS=FC["480p_2"],qx=FC["120p_2"],Tb={"480p":{width:640,height:480,frameRate:5,bitrate:900},"480p_2":{width:640,height:480,frameRate:30,bitrate:1e3},"720p":{width:1280,height:720,frameRate:5,bitrate:1200},"720p_2":{width:1280,height:720,frameRate:30,bitrate:3e3},"1080p":{width:1920,height:1080,frameRate:5,bitrate:1600},"1080p_2":{width:1920,height:1080,frameRate:30,bitrate:4e3}},YA={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},Xn={INACTIVE:"inactive",SENDONLY:"sendonly",RECVONLY:"recvonly"},Pf={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},xf=((Rb=xf||{}).LIVE="live",Rb.RTC="rtc",Rb),WS=1,Nb=2,zS=4,ZS=8,Yf=64,XS=16,Kx=112,Gb=128,$B=256,Eu="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",jx="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",l0=YA.MAIN,bb=YA.AUXILIARY,kb=0,I0=1,AQ=2,Wx=3,Vf=4,zx=5,Zx=6,zh="unknown",ho={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Lb=1/0;function u0(A){Lb=A}function Jf(){return Lb}var wp,yK=30,Ja={JOIN:"join",DELTA_JOIN:"delta-join",REJOIN:"rejoin",LEAVE:"leave",DELTA_LEAVE:"delta-leave",PUBLISH:"publish",DELTA_PUBLISH:"delta-publish",UNPUBLISH:"unpublish",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",UPLINK_CONNECTION:"uplink-connection",UPLINK_RECONNECTION:"uplink-reconnection",DOWNLINK_CONNECTION:"downlink-connection",DOWNLINK_RECONNECTION:"downlink-reconnection",ON_TRACK:"ontrack",ICE_CONNECTION_STATE:"iceConnectionState",LOCAL_STREAM_INITIALIZE:"stream-initialize",SIGNAL_CONNECTION:"websocketConnectionState",SIGNAL_RECONNECTION:"websocketReconnectionState",UPDATE_STREAM:"update-stream",RECOVER_LOCAL_AUDIO_TRACK:"recover-local-audio-track",RECOVER_LOCAL_VIDEO_TRACK:"recover-local-video-track",RECOVER_SUBSCRIPTION:"recover-subscription",START_MIX_TRANSCODE:"start-mix-transcode",STOP_MIX_TRANSCODE:"stop-mix-transcode",PLAYER_ERROR:"player-error",SCHEDULE:"schedule",LOAD_WORKLET:"load-worklet",VIDEO_FROZEN_COUNT:"videoFrozenCount",GET_USER_MEDIA_RETRY:"getUserMedia-retry",VIDEO_ENCODE_FAILED_DURING_CALL:"video-encode-failed-during-call",VIDEO_ENCODE_RESUME_DURING_CALL:"video-encode-resume-during-call",AUDIO_ENCODE_FAILED_DURING_CALL:"audio-encode-failed-during-call",AUDIO_ENCODE_RESUME_DURING_CALL:"audio-encode-resume-during-call",VIDEO_DECODE_FAILED_DURING_CALL:"video-decode-failed-during-call",VIDEO_DECODE_RESUME_DURING_CALL:"video-decode-resume-during-call",AUDIO_DECODE_FAILED_DURING_CALL:"audio-decode-failed-during-call",AUDIO_DECODE_RESUME_DURING_CALL:"audio-decode-resume-during-call",VIDEO_HARDWARE_DECODE_FAILED:"video-hardware-decode-failed",VIDEO_HARDWARE_DECODE_RESUME:"video-hardware-decode-resume"},DK=1e4,Xx=1e4,$x=1e4,$S="unified-plan",E0="plan-b",d0=1028,A2=((wp=A2||{})[wp.UNPUBLISH=-1]="UNPUBLISH",wp[wp.PUBLISHING=0]="PUBLISHING",wp[wp.PUBLISHED=1]="PUBLISHED",wp),Ub=500,e2=1e3,SK=YA.BIG,MK=YA.SMALL,Fb=1e4,eQ={MAIN:"schedule.cloud-rtc.com",BACKUP:"schedule.cloud-rtc.net",MAIN_OVERSEA:"schedule.rtc-web.com",BACKUP_OVERSEA:"schedule.rtc-web.io",MAIN_OVERSEA_BACKUP:"intl-schedule.cloud-rtc.com"},t2=2e3,vK={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},_p=5,AM="default",C0=AM,RK="communications",wK=Object.keys(XB),i2=["normal leave","timeout leave","kick","role change"],eM=10,tM=2e3,Ob=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],h0=1e4,B0=14,Pb={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},o2=function(A,e,o,a){return new(o||(o=Promise))(function(l,d){function h(k){try{S(a.next(k))}catch(V){d(V)}}function y(k){try{S(a.throw(k))}catch(V){d(V)}}function S(k){k.done?l(k.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(k.value).then(h,y)}S((a=a.apply(A,[])).next())})},Q0=Symbol(32),p0=Symbol(16),xb=Symbol(8),Hf=class{constructor(A){this.g=A,this.consumed=0,A&&(this.need=A.next().value)}setG(A){this.g=A,this.demand(A.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(A,e){return e&&this.consume(),this.need=A,this.flush()}read(A){return o2(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((e,o)=>{var a;this.reject=o,this.resolve=l=>{delete this.lastReadPromise,delete this.resolve,delete this.need,e(l)},this.demand(A,!0)||(a=this.pull)===null||a===void 0||a.call(this,A)})})}readU32(){return this.read(Q0)}readU16(){return this.read(p0)}readU8(){return this.read(xb)}close(){var A;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(A=this.reject)===null||A===void 0||A.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let A=null,e=this.buffer.subarray(this.consumed),o=0,a=l=>e.length<(o=l);if(typeof this.need=="number"){if(a(this.need))return;A=e.subarray(0,o)}else if(this.need===Q0){if(a(4))return;A=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===p0){if(a(2))return;A=e[0]<<8|e[1]}else if(this.need===xb){if(a(1))return;A=e[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(a(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(e.subarray(0,o)),A=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(a(this.need.byteLength))return;new Uint8Array(this.need).set(e.subarray(0,o)),A=this.need}return this.consumed+=o,this.g?this.demand(this.g.next(A).value,!0):this.resolve&&this.resolve(A),A}write(A){if(A instanceof Uint8Array?this.malloc(A.length).set(A):"buffer"in A?this.malloc(A.byteLength).set(new Uint8Array(A.buffer,A.byteOffset,A.byteLength)):this.malloc(A.byteLength).set(new Uint8Array(A)),!this.g&&!this.resolve)return new Promise(e=>this.pull=e);this.flush()}writeU32(A){this.malloc(4).set([A>>24&255,A>>16&255,A>>8&255,255&A]),this.flush()}writeU16(A){this.malloc(2).set([A>>8&255,255&A]),this.flush()}writeU8(A){this.malloc(1)[0]=A,this.flush()}malloc(A){if(this.buffer){let e=this.buffer.length,o=e+A;if(o<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,o);else{let a=new Uint8Array(o);a.set(this.buffer),this.buffer=a}return this.buffer.subarray(e,o)}return this.buffer=new Uint8Array(A),this.buffer}};Hf.U32=Q0,Hf.U16=p0,Hf.U8=xb;var iM=128;function m0(A){let e=new Hf;for(;A>=128;)e.malloc(1)[0]=255&A|iM,A>>>=7;return e.malloc(1)[0]=255&A,e.buffer||new Uint8Array(0)}function f0(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Hf,a=e<<3;switch(typeof A){case"boolean":let l=o.malloc(2);l[0]=a,l[1]=A?1:0;break;case"number":o.malloc(1)[0]=a,o.write(m0(A));break;case"string":o.malloc(1)[0]=2|a;let d=new TextEncoder().encode(A);o.write(m0(d.length));let h=o.malloc(d.length);for(let S=0;S>>24&255),this.buffer.push(A>>>16&255),this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeInt16(A){this.buffer.push(A>>>8&255),this.buffer.push(255&A)}writeByte(A){this.buffer.push(255&A)}writeBytes(A){for(let e=0;e>>24&255,A[o+1]=e>>>16&255,A[o+2]=e>>>8&255,A[o+3]=255&e}function du(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]}function n2(A,e){return A[e]}function Kf(A,e,o){return new TextDecoder().decode(function(a,l,d){return a.slice(l,l+d)}(A,e,o))}var oM=0,Yb=2654435769,y0=16,Zh=2,sM=7;function Vb(A,e){let o=new s2,a=function(we,Di,Le){let Qt=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"AVQualityReportSvc.C2S";return{version:arguments.length>4&&arguments[4]!==void 0?arguments[4]:2e3,encryption:arguments.length>5&&arguments[5]!==void 0?arguments[5]:2,d2:"",d2Len:0,uinType:arguments.length>6&&arguments[6]!==void 0?arguments[6]:30,uin:"",uinLen:0,reqHead:{seqNumber:Le,appId:we,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:Qt,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:Di}}(e,A,oM);oM=oM+1&2147483647,o.writeInt32(0),o.writeInt32(a.version),o.writeByte(a.encryption);let l=new TextEncoder().encode(a.d2);o.writeInt32(l.length+4),l&&o.writeBytes(l),o.writeByte(a.uinType);let d=new TextEncoder().encode(a.uin);o.writeInt32(d.length+4),d.length&&o.writeBytes(d);let h=new s2;h.writeInt32(0),h.writeInt32(a.reqHead.seqNumber),h.writeInt32(a.reqHead.appId),h.writeByte(a.reqHead.appId>>>24&255),h.writeByte(a.reqHead.appId>>>16&255),h.writeByte(a.reqHead.appId>>>8&255),h.writeByte(255&a.reqHead.appId);for(let we=4;we<16;we++)h.writeByte(0);let y=new TextEncoder().encode(a.reqHead.a2);h.writeInt32(y.length+4),y.length&&h.writeBytes(y);let S=new TextEncoder().encode(a.reqHead.serviceCmd);h.writeInt32(S.length+4),S.length&&h.writeBytes(S);let k=new TextEncoder().encode(a.reqHead.cookie);h.writeInt32(k.length+4),k.length&&h.writeBytes(k);let V=new TextEncoder().encode(a.reqHead.imei);h.writeInt32(V.length+4),V.length&&h.writeBytes(V);let J=new TextEncoder().encode(a.reqHead.ksid);h.writeInt32(J.length+4),J.length&&h.writeBytes(J);let cA=new TextEncoder().encode(a.reqHead.clientVersionInfo);h.writeInt16(cA.length+2),cA.length&&h.writeBytes(cA);let CA=h.length;h.data[0]=CA>>>24&255,h.data[1]=CA>>>16&255,h.data[2]=CA>>>8&255,h.data[3]=255&CA,Vn(A)&&(A=new TextEncoder().encode(A)),h.writeInt32(A.length+4),A.length&&h.writeBytes(A);let MA=new Uint8Array(h.data),ie=null;a.encryption===1?ie=new TextEncoder().encode(a.uin):a.encryption===2&&(ie=new Uint8Array(16)),ie&&(MA=function(we,Di){let Le=we.length,Qt=(Le+1+Zh+sM)%8;Qt&&(Qt=8-Qt);let Bi=Le+1+Zh+sM+Qt,Si=new Uint8Array(Bi),Jo=0,Ho=new Uint8Array(8),Qn=new Uint8Array(8),qo=new Uint8Array(8),Ns=0;Ho[0]=248&Math.floor(256*Math.random())|Qt,Ns=1;for(let ya=0;ya>>24&255,pe[1]=qe>>>16&255,pe[2]=qe>>>8&255,pe[3]=255&qe,pe}function Jb(A,e,o,a,l,d){for(let h=0;h<8;h++)A[h]^=a[h];(function(h,y,S,k){let V=du(h,0),J=du(h,4),cA=[];for(let MA=0;MA<4;MA++)cA[MA]=du(y,4*MA);let CA=0;for(let MA=0;MA>>=0,V+=(J<<4)+cA[0]^J+CA^(J>>>5)+cA[1],V>>>=0,J+=(V<<4)+cA[2]^V+CA^(V>>>5)+cA[3],J>>>=0;qf(S,V,k),qf(S,J,k+4)})(A,e,l,d);for(let h=0;h<8;h++)l[d+h]^=o[h];for(let h=0;h<8;h++)o[h]=A[h]}var r2=function(){return new URLSearchParams(location.search).get("trtc_env")||""},a2=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},Kd=A=>Number(A)<14e8,jf=function(A,e){let o;o=wb||(Kd(A)?vp:bI);let a=Math.floor(Math.random()*JS(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(a,"&sdkappid=").concat(A,"&cmdtype=").concat(e)},Hb="unknown";function D0(){(function(){var d;g2||(g2=!0,(d=navigator.connection)==null||d.addEventListener("typechange",_K))})();let{userAgent:A,connection:e}=navigator,o=(A.match(/NetType\/\S+/)||[])[0]||"";o=o.toLowerCase().replace("nettype/",""),o==="3gnet"&&(o="3g");let a=e&&e.type&&e.type.toLowerCase(),l=e&&e.effectiveType&&e.effectiveType.toLowerCase();return l==="slow-2"&&(l="2g"),a?qb(a,l):Hb}function _K(){pA.warn("netType changed",D0())}var g2=!1;function qb(A,e){if(g0[A])return A;switch(A){case"cellular":case"wimax":return e||"unknown";case"ethernet":return"wired";default:return"unknown"}}function S0(A){Hb=qb(A)}function Wf(){return g0[D0()]}function c2(A,e){for(let o of Reflect.ownKeys(e))if(o!=="constructor"&&o!=="prototype"&&o!=="name"){let a=Object.getOwnPropertyDescriptor(e,o)||"";Object.defineProperty(A,o,a)}return A}function M0(A){return Kb(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function Kb(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function l2(A){return 4*v0(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function v0(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var I2=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Wd=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},IE=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)};function zf(A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?e:zf(A-1,e,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+e)}function Tp(A){return A>8?3e4:1e3*zf(A)}function Cg(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ra=A=>typeof A=="function",Ke=A=>A===void 0,Vn=A=>typeof A=="string",kn=A=>typeof A=="number",Nr=A=>typeof A=="boolean",XE=A=>Cg(A)==="object",wa=A=>Cg(A)==="array",jb=A=>Cg(A)==="MediaStreamTrack".toLowerCase(),Wb=A=>A.isRemote,Zf=A=>Cg(A)==="promise",Xf=A=>Ra(A)&&A.prototype.constructor===A,nM=A=>Xf(A)?A.prototype.constructor.name:"",u2=typeof AudioWorkletNode<"u",E2=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function rM(A){return new Promise((e,o)=>{let a=[];A.forEach(l=>{l.then(e).catch(d=>{a.push(d),a.length===A.length&&o(a)})})})}function ko(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var d2=A=>+A<10?"0".concat(A):A,C2=A=>{let e=A.match(/^\d+\.\d+\.\d+/)[0];if(!e)return A;let o=e.split("."),a=d2(o[1])+d2(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(a)},TK=Object.prototype.hasOwnProperty;function R0(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(IE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let e in A)if(TK.call(A,e))return!1;return!0}return!1}function Np(A,e){return{userId:e,hasAudio:!!(A&ZS),hasVideo:!!(A&WS),hasAuxiliary:!!(A&zS),hasSmall:!!(A&Nb),audioMuted:!!(A&Yf),videoMuted:!!(A&XS),audioAvailable:!(!(A&ZS)||A&Yf),videoAvailable:!(!(A&WS)||A&XS),hasDatachannel:!!(A&$B)}}function h2(A){let e={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!Ke(A.username)&&!Ke(A.credential)&&(e.username=A.username,e.credential=A.credential,e.credentialType="password",Ke(A.credentialType)||(e.credentialType=A.credentialType)),e}function aM(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];if(!Vn(A))return 0;let o=A.split(".");return e?(Number(o[0])<<24|Number(o[1])<<16|Number(o[2])<<8|Number(o[3]))>>>0:(Number(o[3])<<24|Number(o[2])<<16|Number(o[1])<<8|Number(o[0]))>>>0}var Xh=function(A,e,o,a){if(!XE(A)||!XE(e))return 0;let l,d=0,h=Object.keys(e);for(let y=0,S=h.length;y{e[a]=$f(o)}),e}if(XE(A)){let e={};return Object.keys(A).forEach(o=>{e[o]=$f(A[o])}),e}return A}var gM=A=>{let e=[];if(wa(A))e=[...A];else if(Vn(A)){let o=document.getElementById(A);o&&e.push(o)}else A&&e.push(A);return e},zb=A=>Vn(A)?document.getElementById(A):A,B2=()=>(A=>{let e=S=>S<10?"0".concat(S):"".concat(S),o=A.getFullYear(),a=A.getMonth()+1,l=A.getDate(),d=e(A.getHours()),h=e(A.getMinutes()),y=e(A.getSeconds());return"".concat(o,"/").concat(a,"/").concat(l," ").concat(d,":").concat(h,":").concat(y)})(new Date);function zd(A,e){let{keysToInclude:o,keysToExclude:a}=e;try{if(wa(A))return"[".concat(A.map(y=>zd(y,{keysToInclude:o,keysToExclude:a})).join(","),"]");if(!IE(A)||!wa(o)&&!wa(a))return JSON.stringify(A);let l={},d=new Set(o),h=new Set(a);return Object.keys(A).forEach(y=>{(h.size===0&&d.has(y)||d.size===0&&!h.has(y))&&(l[y]=IE(A[y])||wa(A[y])?JSON.parse(zd(A[y],{keysToExclude:a,keysToInclude:o})):A[y])}),JSON.stringify(l)}catch{return"{}"}}function w0(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=[];return Object.keys(A).forEach(a=>{e===A[a]&&o.push(a)}),zd(A,{keysToInclude:o})}function _0(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var Zb=()=>{var A,e,o,a;return(A=window.screen)!=null&&A.orientation?!((a=(o=(e=window.screen)==null?void 0:e.orientation)==null?void 0:o.type)==null||!a.includes("portrait")):window.orientation===0||window.orientation===180},cM=A=>WA(null,null,function*(){return new Promise((e,o)=>{let a;if(Vn(A))a=new Image,a.crossOrigin="anonymous",a.src=A;else if(a=A,a.complete)return void e(a);a.onload=()=>e(a),a.onerror=()=>{o(new gi({code:Ct.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),Xb=A=>{let e=A.split(".");return+e[0]<<24|+e[1]<<16|+e[2]<<8|+e[3]},T0=A=>(Object.keys(A).forEach(e=>{kn(A[e])&&(e.startsWith("uint")||e.startsWith("int"))?A[e]=Math.floor(A[e]):(IE(A[e])||wa(A[e]))&&T0(A[e])}),A);function OC(A,e){return new Promise(o=>{let a=setTimeout(o,A);e&&e(a)})}function $b(A,e){let o=null;return function(){for(var a=arguments.length,l=new Array(a),d=0;do=null),o)}}function Ak(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function ek(A){var e;try{let{width:o,height:a,frameRate:l,sampleRate:d,sampleSize:h,channelCount:y}=(e=A.getSettings)==null?void 0:e.call(A),S=A.kind===YA.AUDIO?"".concat(d,"x").concat(h,"@").concat(y):"".concat(o,"x").concat(a,"@").concat(l),k=A.stats?" stats: ".concat(JSON.stringify(A.stats).replaceAll('"',"")):"";return"".concat(A.id," ").concat(A.readyState," muted:").concat(A.muted," ").concat(A.kind," ").concat(A.label," ").concat(S).concat(k)}catch{return""}}function N0(A,e){return A.width*A.height===e.width*e.height?1:Zb()&&e.width>e.height&&A.height>e.width?Math.max(A.width/e.height,A.height/e.width,1):Math.max(A.width/e.width,A.height/e.height,1)}function tQ(A){return A===90||A===270}function Q2(A){return WA(this,null,function*(){return new Promise((e,o)=>{let a=document.createElement("video");a.crossOrigin="anonymous",a.src=A,a.muted=!0,a.loop=!0,a.playsInline=!0,a.play().then(()=>e(a)),a.onerror=()=>{o(a.error)}})})}function Ay(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new WeakMap;if(typeof A!="object"||A===null)return A;if(e.has(A))return e.get(A);if(Array.isArray(A)){let o=[];return e.set(A,o),A.forEach((a,l)=>{o[l]=Ay(a,e)}),o}if(Object.prototype.toString.call(A)==="[object Object]"){let o={};return e.set(A,o),Reflect.ownKeys(A).forEach(a=>{o[a]=Ay(A[a],e)}),o}return A}var G0=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(G0||{});function iQ(A,e,o,a){try{let l=function(d,h,y,S){let k={data:d,random:Math.floor(2147483648*Math.random()),sdkAppId:y};return Ke(S)||(k=po(fi({},k),{gzip:+S})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:h,bytes_report_data:JSON.stringify(k)}}}(A,e,o,a);return Vb(f0(l),o)}catch{return JSON.stringify(A)}}function lM(A,e){let o=new Uint8Array(A.byteLength+e.byteLength);return o.set(new Uint8Array(A),0),o.set(new Uint8Array(e),A.byteLength),o.buffer}function b0(A){return(65535&A)>>>0}function p2(A){return(4294901760&A)>>>0}function Gp(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function NK(A){let e=function(o){try{let a={},l=0;a.totalLength=du(o,l),l+=4,a.version=du(o,l),l+=4,a.encryption=n2(o,l),l+=1,a.uinType=n2(o,l),l+=1,a.uinLength=du(o,l),l+=4,a.uin=a.uinLength>4?Kf(o,l,a.uinLength-4):"",l+=a.uinLength-4;let d=o.slice(l);return a.encryption===2?(o=function(h,y){let S=0,k=new Uint8Array(8).fill(0),V=new Uint8Array(h.slice(0,8)),J=k0(V,y),cA=7&J[0],CA=h.length-1-cA-Zh-sM,MA=new Uint8Array(CA),ie=0,pe=k,qe=h.slice(0,8);S=8;let we=1;we+=cA;for(let Le=1;Le<=Zh;)if(we<8)we++,Le++;else if(we===8){let Qt=ey(h,S,pe,qe,J,y);pe=Qt.ivPreCrypt,qe=Qt.ivCurCrypt,J=Qt.debiBuf,S=Qt.bufPos,we=0}let Di=CA;for(;Di>0;)if(we<8)MA[ie++]=J[we]^pe[we],we++,Di--;else if(we===8){let Le=ey(h,S,pe,qe,J,y);pe=Le.ivPreCrypt,qe=Le.ivCurCrypt,J=Le.debiBuf,S=Le.bufPos,we=0}for(let Le=1;Le<=sM;)if(we<8)J[we],pe[we],we++,Le++;else if(we===8){if(S>=h.length)break;let Qt=ey(h,S,pe,qe,J,y);if(!Qt.success)break;pe=Qt.ivPreCrypt,qe=Qt.ivCurCrypt,J=Qt.debiBuf,S=Qt.bufPos,we=0}return MA}(d,new Uint8Array(16).fill(0)),a.decrypted=!0,l=0):(o=d,l=0),a.rspHeadLength=du(o,l),l+=4,a.seqNo=du(o,l),l+=4,a.retCode=du(o,l),l+=4,a.retStrLength=du(o,l),l+=4,a.retStr=a.retStrLength?Kf(o,l,a.retStrLength-4):"",l+=a.retStrLength-4,a.serviceCmdLength=du(o,l),l+=4,a.serviceCmd=a.serviceCmdLength?Kf(o,l,a.serviceCmdLength-4):"",l+=a.serviceCmdLength-4,a.cookieLength=du(o,l),l+=4,a.cookie=a.cookieLength?Kf(o,l,a.cookieLength-4):"",l+=a.cookieLength-4,a.flag=du(o,l),l+=4,a.busiBuffLength=du(o,l),l+=4,a.busiBuff=a.busiBuffLength?Kf(o,l,a.busiBuffLength-4):"",l+=a.busiBuffLength-4,a}catch{}}(A);return e?.busiBuff}function k0(A,e){let o=A[0]<<24|A[1]<<16|A[2]<<8|A[3],a=A[4]<<24|A[5]<<16|A[6]<<8|A[7];o>>>=0,a>>>=0;let l=Yb*y0>>>0;for(let d=0;d>>5)+e[3],a>>>=0,o-=(a<<4)+e[0]^a+l^(a>>>5)+e[1],o>>>=0,l-=Yb,l>>>=0;return new Uint8Array([o>>>24&255,o>>>16&255,o>>>8&255,255&o,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}function ey(A,e,o,a,l,d){if(e+8>A.length)return{success:!1};let h=new Uint8Array(a),y=A.slice(e,e+8),S=new Uint8Array(8);for(let k=0;k<8;k++)S[k]=l[k]^y[k];return{success:!0,ivPreCrypt:h,ivCurCrypt:y,debiBuf:k0(S,d),bufPos:e+8}}var bp=typeof TextDecoder<"u"?new TextDecoder:void 0;function oQ(A){let{url:e,body:o,method:a="POST",timeout:l,priority:d}=A;return new Promise((h,y)=>{if("fetch"in window)return fetch(e,{method:a,body:o,priority:d}).then(k=>k.clone().json().then(V=>({data:V}),()=>k.arrayBuffer().then(V=>({data:NK(new Uint8Array(V))||(bp?bp.decode(V):V)})))).then(h,y);let S=new XMLHttpRequest;S.onreadystatechange=()=>{if(S.readyState===4)if(S.status>=200&&S.status<300)try{let k=JSON.parse(S.response);h({data:k})}catch{h({data:S.response})}else y({status:S.status,statusText:S.statusText||"request failed!"})},S.timeout=l||5e3,S.open(a,e,!0),S.send(o)})}function tk(A){return WA(this,null,function*(){let e=ko(),o=JSON.stringify(A);try{if(!CompressionStream||o.length<=2800)return o;let a=new Blob([o],{type:"application/json"}).stream().pipeThrough(new CompressionStream("gzip")),l=yield(yield(yield new Response(a)).blob()).arrayBuffer();return pA.debug("compressJSON ".concat(o.length," -> ").concat(l.byteLength," ").concat(ko()-e,"ms")),l}catch{return o}})}var m2=Object.prototype.hasOwnProperty,kp=A=>typeof A=="function",$E=A=>A===void 0,ik=A=>typeof A=="string",f2=A=>typeof A=="boolean",ok=A=>A.isRemote,y2=function(A){if(!A||typeof A!="object"||Object.prototype.toString.call(A)!="[object Object]")return!1;let e=Object.getPrototypeOf(A);if(e===null)return!0;let o=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return typeof o=="function"&&o instanceof o&&Function.prototype.toString.call(o)===Function.prototype.toString.call(Object)},IM=function(A){let{retryFunction:e,settings:o,onError:a,onRetrying:l,onRetryFailed:d,onRetrySuccess:h,context:y}=A;return function(){for(var S=arguments.length,k=new Array(S),V=0;VWA(this,null,function*(){let Di=y||this;try{let Le=yield e.apply(Di,k);CA>0&&h&&h.call(this,CA),CA=0,qe(Le)}catch(Le){let Qt=()=>{clearTimeout(MA),CA=0,ie=2,we(Le)},Bi=()=>{ie!==2&&CA<(kp(J)?J():J)?(CA++,ie=1,kp(l)&&l.call(this,CA,Qt),MA=window.setTimeout(()=>{MA=-1,pe(qe,we)},kp(cA)?cA(CA):cA)):(Qt(),kp(d)&&d.call(this,Le))};kp(a)?a.call(this,{error:Le,retry:Bi,reject:we,retryFuncArgs:k,retriedCount:CA}):Bi()}});return new Promise(pe)}},sk=class AX{constructor(e){Y(this,"_parentPath"),Y(this,"userId"),Y(this,"remoteUserId"),Y(this,"id"),Y(this,"sdkAppId"),Y(this,"type"),Y(this,"isLocal"),this.id=e.id,this.userId=e.userId,this.sdkAppId=e.sdkAppId,this.remoteUserId=e.remoteUserId,this.isLocal=!f2(e.isLocal)||e.isLocal,this.type=this.isLocal?"":e.type}getFullId(){return this._parentPath&&this.id?"".concat(this._parentPath,"-").concat(this.id):this._parentPath?this._parentPath:this.id}createChild(e){let o=new AX({id:e.id,userId:$E(e.userId)?this.userId:e.userId,sdkAppId:$E(e.sdkAppId)?this.sdkAppId:e.sdkAppId,type:$E(e.type)?this.type:e.type,isLocal:$E(e.isLocal)?this.isLocal:e.isLocal,remoteUserId:$E(e.remoteUserId)?this.remoteUserId:e.remoteUserId});return o.bindParent(this),o}bindParent(e){let o=e.getFullId();this._parentPath!==o&&(this.debug("bind logger parent: ".concat(e.id)),this._parentPath=o,this.userId=e.userId||this.userId,this.sdkAppId=e.sdkAppId||this.sdkAppId)}setUserId(e){this.userId=e}setSdkAppId(e){this.sdkAppId=e}log(e,o){let a=this.isLocal?this.userId:this.remoteUserId,l=this.getFullId();o.unshift("[".concat(this.isLocal?"↑":"↓").concat(this.type&&this.type!=="main"?"*":"").concat(l).concat(a?"|".concat(a):"","]")),pA.log(e,o,$E(this.userId)||function(d){if(d==null)return!0;if(typeof d=="boolean")return!1;if(typeof d=="number")return d===0;if(typeof d=="string"||typeof d=="function"||Array.isArray(d))return d.length===0;if(d instanceof Error)return d.message==="";if(y2(d))switch(Object.prototype.toString.call(d)){case"[object File]":case"[object Map]":case"[object Set]":return d.size===0;case"[object Object]":for(let h in d)if(m2.call(d,h))return!1;return!0}return!1}(this.userId),this.userId,this.sdkAppId)}info(){for(var e=arguments.length,o=new Array(e),a=0;aF0,CHROME_MAJOR_VERSION:()=>td,CHROME_VERSION:()=>j0,EDGE_VERSION:()=>rk,EDG_MAJOR_VERSION:()=>P0,EDG_VERSION:()=>ak,ELECTRON_MAJOR_VERSION:()=>T2,FIREFOX_MAJOR_VERSION:()=>O0,FIREFOX_VERSION:()=>EM,HUAWEI_VERSION:()=>Qk,IE_VERSION:()=>kK,IOS_MAIN_VERSION:()=>Zd,IOS_VERSION:()=>LI,IPADQQB_VERSION:()=>BM,IS_ANDROID:()=>Ha,IS_ANDROID_WEBVIEW:()=>fk,IS_ANY_SAFARI:()=>xp,IS_CHROME:()=>K0,IS_CHROME_OS:()=>dk,IS_CHROMIUM_128_TO_143:()=>ay,IS_CHROMIUM_BASE:()=>uE,IS_DESKTOP_IOS_CHROME:()=>b2,IS_EDG:()=>iy,IS_EDGE:()=>ty,IS_ELECTRON:()=>LK,IS_FIREFOX:()=>or,IS_HEADLESS_CHROME:()=>_2,IS_HONOR:()=>Bk,IS_HUAWEI:()=>hk,IS_HUAWEIBROWSER:()=>$h,IS_IE:()=>R2,IS_IE8:()=>bK,IS_IOS:()=>eg,IS_IOS_13_OR_14:()=>G2,IS_IOS_15_1:()=>N2,IS_IOS_CHROME:()=>DM,IS_IPAD:()=>Lp,IS_IPADQQB:()=>J0,IS_IPAD_PRO:()=>U0,IS_IPHONE:()=>Up,IS_IPOD:()=>M2,IS_LINUX:()=>ny,IS_LOCAL:()=>Yp,IS_MAC:()=>nQ,IS_MACQQB:()=>hM,IS_MIBROWSER:()=>H0,IS_MQQB:()=>CM,IS_NATIVE_ANDROID:()=>v2,IS_OLD_ANDROID:()=>GK,IS_OPENHARMONY:()=>ry,IS_OPPOBROWSER:()=>pM,IS_SAFARI:()=>Bg,IS_SAFARI_15_1:()=>UK,IS_SAMSUNGBROWSER:()=>QM,IS_SOGOU:()=>Y0,IS_SOGOUM:()=>dM,IS_TBS:()=>ed,IS_UCBROWSER:()=>Ck,IS_VIVOBROWSER:()=>mM,IS_WECHAT:()=>sQ,IS_WIN:()=>sy,IS_WQQB:()=>V0,IS_WX:()=>w2,IS_X5MQQB:()=>Op,IS_XWEB:()=>Fp,MACQQB_VERSION:()=>Ek,MI_VERSION:()=>Pp,MQQB_VERSION:()=>oy,OPENHARMONY_VERSION:()=>q0,OPPO_VERSION:()=>mk,SAFARI_VERSION:()=>rQ,SAMSUNG_VERSION:()=>pk,SOGOUM_VERSION:()=>x0,SOGOU_VERSION:()=>gk,TBS_VERSION:()=>ck,UA_DATA_STRING:()=>PC,USER_AGENT:()=>Ad,VIVO_VERSION:()=>fM,WECHAT_VERSION:()=>Ik,WQQB_VERSION:()=>uk,XWEB_VERSION:()=>lk,browserInfo:()=>gQ,getBrowserCoreNumber:()=>Wl,getBrowserInfo:()=>Dk,getChromeMajorVersion:()=>yM,getDeviceModel:()=>cQ,getDeviceModelFromUA:()=>Sk,getGPUInfo:()=>Vp,getOSName:()=>El,getOSNumber:()=>Jp,getOSString:()=>Hp,getOSType:()=>Q,getTerminalType:()=>Cn,getUserAgentData:()=>SM,isAMDGPU:()=>cy,isAppleSiliconGPU:()=>FK,isLocalStorageEnabled:()=>aQ,isMobile:()=>W0,isNvidiaGPU:()=>k2,isRealIOS:()=>uM,isVersionLargerThan:()=>gy,isVersionSmallerThan:()=>yk});var Ad=typeof navigator>"u"?"":navigator.userAgent,Ts=A=>new RegExp(A,"i").test(Ad),hg=A=>{if(Ts(A)){let e=new RegExp("".concat(A,"\\/([\\d.]+)")),o=Ad.match(e);if(o&&o[1])return o[1]}return""},L0=A=>{if(Ts(A)){let e=new RegExp("".concat(A,"\\/(\\d+)")),o=Ad.match(e);if(o&&o[1])return parseFloat(o[1])}return NaN},nk=/AppleWebKit\/([\d.]+)/i.exec(Ad),S2=nk?parseFloat(nk[1]):NaN,Lp=Ts("iPad"),U0=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ts("Macintosh"),Up=Ts("iPhone")&&!Lp,M2=Ts("iPod"),eg=Up||Lp||M2||U0,uM=()=>{try{return eg&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return eg}},Ha=Ts("Android"),F0=function(){if(Ha){let A=Ad.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(A){let e=A[1]&&parseFloat(A[1]),o=A[2]&&parseFloat(A[2]);if(e&&o)return parseFloat("".concat(A[1],".").concat(A[2]));if(e)return e}}return NaN}(),GK=Ha&&Ts("webkit")&&F0<2.3,v2=Ha&&F0<5&&S2<537,or=Ts("Firefox"),EM=hg("Firefox"),O0=L0("Firefox"),ty=Ts("Edge"),rk=hg("Edge"),iy=Ts("Edg"),ak=hg("Edg"),P0=L0("Edg"),dM=Ts("SogouMobileBrowser"),x0=hg("SogouMobileBrowser"),Y0=Ts("MetaSr\\s"),gk=hg("MetaSr\\s"),ed=Ts("TBS"),ck=hg("TBS"),Fp=Ts("XWEB"),lk=hg("XWEB"),bK=Ts("MSIE\\s8\\.0"),R2=Ts("MSIE\\/\\d+"),kK=function(){if(R2){let A=/MSIE\s(\d+)\.\d/.exec(Ad),e=A&&parseFloat(A[1]);return!e&&/Trident\/7.0/i.test(Ad)&&/rv:11.0/.test(Ad)&&(e=11),e}return NaN}(),sQ=Ts("(micromessenger|webbrowser)"),Ik=hg("MicroMessenger"),Op=!ed&&Ts("MQQBrowser")&&Ts("COVC"),CM=!ed&&Ts("MQQBrowser")&&!Ts("COVC"),oy=CM||Op?hg("MQQBrowser"):"",V0=!ed&&Ts(" QQBrowser"),uk=hg(" QQBrowser"),hM=!ed&&Ts("QQBrowserLite"),Ek=hg("QQBrowserLite"),J0=!ed&&Ts("MQBHD"),BM=hg("MQBHD"),sy=Ts("Windows"),nQ=!eg&&Ts("MAC OS X"),ny=!Ha&&Ts("Linux"),dk=Ts("CrOS"),w2=Ts("MicroMessenger"),Ck=Ts("UCBrowser"),LK=Ts("Electron"),H0=Ts("MiuiBrowser"),Pp=hg("MiuiBrowser"),$h=Ts("HuaweiBrowser"),hk=Ts("Huawei")||Ts("HUAWEI"),Bk=Ts("Honor")||Ts("HONOR"),Qk=hg("HuaweiBrowser"),QM=Ts("SamsungBrowser"),pk=hg("SamsungBrowser"),pM=Ts("HeyTapBrowser"),mk=hg("HeyTapBrowser"),mM=Ts("VivoBrowser"),fM=hg("VivoBrowser"),ry=Ts("OpenHarmony"),q0=hg("OpenHarmony"),yM=()=>L0("Chrome"),DM=Ts("CriOS"),uE=Ts("Chrome"),K0=!ty&&!Y0&&!dM&&!ed&&!Fp&&!iy&&!V0&&!H0&&!$h&&!QM&&!pM&&!mM&&uE,_2=Ts("HeadlessChrome"),td=yM(),ay=uE&&td>=128&&td<=143,j0=hg("Chrome"),T2=L0("Electron"),Bg=!uE&&!CM&&!Op&&!hM&&!J0&&Ts("Safari"),xp=Bg||eg,rQ=hg("Version"),fk=/Android.*(wv|.0.0.0)/.test(Ad),LI=(()=>{if(U0)return rQ;if(eg){let A=Ad.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let e=A[1];return A[2]&&(e+=".".concat(A[2])),e}}return""})();function yk(A,e){let o=A.split(".").map(l=>Number(l)),a=e.split(".").map(l=>Number(l));for(let l=0;lh)return!1}return!1}function gy(A,e){let o=arguments.length>2&&arguments[2]!==void 0&&arguments[2],a=A.split(".").map(d=>Number(d)),l=e.split(".").map(d=>Number(d));for(let d=0;dy)return!0;if(h{let A=Number(LI.split(".")[0]);return A===14||A===13})(),b2=DM&&rQ==="11.1.1",Yp=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),aQ=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),gQ=Dk();function Dk(){let A=new Map([[or,["Firefox",EM]],[iy,["Edg",ak]],[K0,["Chrome",j0]],[DM,["ChiOS",hg("CriOS")]],[Bg&&!DM,["Safari",rQ]],[ed,["TBS",ck]],[Fp,["XWEB",lk]],[sQ&&Up,["WeChat",Ik]],[V0,["QQ(Win)",uk]],[CM,["QQ(Mobile)",oy]],[Op,["QQ(Mobile X5)",oy]],[hM,["QQ(Mac)",Ek]],[J0,["QQ(iPad)",BM]],[H0,["MI",Pp]],[$h,["HW",Qk]],[QM,["Samsung",pk]],[pM,["OPPO",mk]],[mM,["VIVO",fM]],[ty,["EDGE",rk]],[dM,["SogouMobile",x0]],[Y0,["Sogou",gk]]]),e="unknown",o="unknown";return A.has(!0)&&([e,o]=A.get(!0)),{name:e,version:o}}var Pr=null;function W0(){return Pr&&typeof Pr.mobile=="boolean"?Pr.mobile:Ha||eg||Up||Lp||ry}var PC="";function SM(){return WA(this,null,function*(){if(Pr)return Pr;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Pr=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!PC&&(PC="UAData: ".concat(Pr.platform,"/").concat(Pr.platformVersion),Pr.architecture&&Pr.bitness&&(PC+=" ".concat(Pr.architecture,"/").concat(Pr.bitness)),Pr.mobile&&(PC+=" mobile"),Pr.model&&(PC+=" model: ".concat(Pr.model.replace(/\s+/g,"/"))),Pr.fullVersionList&&(PC+=" ".concat(Pr.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Pr}catch{return null}})}var MM="";function Vp(){try{if(MM)return MM;let A=document.createElement("canvas"),e=A.getContext("webgl")||A.getContext("experimental-webgl");if(!e)return"";let o=e.getExtension("WEBGL_debug_renderer_info");if(o){let a=e.getParameter(o.UNMASKED_VENDOR_WEBGL),l=e.getParameter(o.UNMASKED_RENDERER_WEBGL);return MM="".concat(a," ").concat(l)}return""}catch{return""}}function cy(){try{let A=Vp();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function k2(){try{let A=Vp();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function FK(){try{return Vp().includes("Apple M")}catch{return!1}}function cQ(){return Pr?.model||Sk()||""}function Sk(){let A=Ad.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var L2=new Map([[Ha,"Android"],[eg,"iOS"],[sy,"Windows"],[nQ,"MacOS"],[ny,"Linux"],[dk,"ChromeOS"]]),El=function(){return L2.get(!0)?L2.get(!0):Pr?Pr.platform:"unknown"};function Jp(){return sy?1:Ha?2:nQ?3:eg?4:ny?5:dk?6:ry?7:0}function Wl(){return sQ||Fp?4:uE?1:Bg?2:or?3:0}var Hp=()=>{let A=El();return Pr!=null&&Pr.platformVersion?A+="/".concat(Pr.platformVersion):eg?A+="/".concat(LI):Ha&&(A+="/".concat(F0)),A+="/".concat(gQ.name,"/").concat(Bg&&!DM?gQ.version:gQ.version.split(".")[0]),Pr!=null&&Pr.architecture&&(A+="/".concat(Pr.architecture)),A};function Cn(){return Ha?4:Up?2:Lp?3:nQ?12:sy?5:ny?13:ry?22:1}function Q(){return Ha?"Android":Up?"iPhone":Lp?"iPad":nQ?"Mac":sy?"Windows":ny?"Linux":"unknown"}var R,F=new(gc(jl(),1)).default,eA=((R=eA||{}).ROOM_DESTROY="1",R.JOIN_START="21",R.JOIN_SCHEDULE_SUCCESS="22",R.JOIN_SIGNAL_CONNECTION_START="23",R.JOIN_SIGNAL_CONNECTION_END="24",R.JOIN_SEND_CMD="25",R.JOIN_RECEIVED_CMD_RES="26",R.JOIN_SUCCESS="27",R.JOIN_FAILED="28",R.LEAVE_START="51",R.LEAVE_SEND_CMD="52",R.LEAVE_SUCCESS="53",R.PUBLISH_START="61",R.SEND_FIRST_VIDEO_FRAME="62",R.PUBLISH_FAILED="63",R.SUBSCRIBE_START="81",R.SUBSCRIBE_SUCCESS="82",R.SUBSCRIBE_FAILED="84",R.UNSUBSCRIBE_SUCCESS="83",R.LOCAL_TRACK_CAPTURE_START="101",R.LOCAL_TRACK_CAPTURE_SUCCESS="102",R.LOCAL_TRACK_CAPTURE_FAILED="103",R.LOCAL_TRACK_PUBLISHED="104",R.LOCAL_TRACK_UNPUBLISHED="105",R.LOCAL_TRACK_REPLACED="106",R.SWITCH_DEVICE_SUCCESS="107",R.TRACK_MUTED="108",R.TRACK_UNMUTED="109",R.REMOTE_TRACK_SUBSCRIBED="110",R.REMOTE_TRACK_UNSUBSCRIBED="111",R.LOCAL_TRACK_RECAPTURE="112",R.LOCAL_AUDIO_STARTED="113",R.LOCAL_AUDIO_STOPPED="114",R.REMOTE_AUDIO_STARTED="115",R.REMOTE_AUDIO_STOPPED="116",R.LOCAL_TRACK_STOPPED="117",R.LOCAL_VIDEO_TRACK_PREPROCESSED="118",R.PLAY_TRACK_START="151",R.PLAYER_STATE_CHANGED="152",R.VIDEO_LOADED_DATA="153",R.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",R.AUDIO_CONTEXT_LONG_SUSPENDED="155",R.REMOTE_VIDEO_PLAY_START="156",R.REMOTE_VIDEO_PLAY_FINISH="157",R.SIGNAL_CONNECTION_STATE_CHANGED="201",R.PEER_CONNECTION_STATE_CHANGED="202",R.SINGLE_CONNECTION_STAT="203",R.SPC_RECONNECTED="204",R.HEARTBEAT_REPORT="251",R.RECEIVED_PUBLISHED_USER_LIST="252",R.REMOTE_PUBLISH_STATE_CHANGED="253",R.AUDIO_LEVEL_INTERVAL="260",R.NETWORK_QUALITY="261",R.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",R.QUALITY_LIMITATION_CHANGED="263",R.LOG="264",R.AUDIO_PROCESSOR_DEBUG="265",R.SSO_SWITCH="266",R.SEI_MESSAGE="267",R.USER_PAUSE_IN_PIP="268",R.USER_RESUME_IN_PIP="269",R.ENTER_PICTURE_IN_PICTURE="270",R.LEAVE_PICTURE_IN_PICTURE="271",R.SWITCH_ROOM_START="401",R.SWITCH_ROOM_SUCCESS="407",R.SWITCH_ROOM_FAILED="408",R),nA=eA,TA=new class{constructor(){Y(this,"enable",!1),Y(this,"ssoFailCount",0),F.on("22",A=>{let{schedule:e}=A;var o;(o=e?.config)!=null&&o.sso&&F.emit("266",{enable:!0})}),F.on("266",A=>{let{enable:e}=A;this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&F.emit("266",{enable:!1})}},$A=class eX{constructor(){Y(this,"_isEnableUploadLog",!0),Y(this,"_localJoinedUser",new Map),Y(this,"_queue",[]),Y(this,"_timeoutId",-1),Y(this,"_logLevel",1),Y(this,"_logLevelToUpload",2),!n0&&!r0&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){F.on(nA.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:o}=e;var a;(a=o?.config)!=null&&a.logLevelToUpload&&XB[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),F.on(nA.JOIN_START,e=>{let{params:o}=e;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),F.on(nA.LEAVE_SUCCESS,e=>{let{room:o}=e;this.deleteJoinedUser(o.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(e){this._localJoinedUser.set(e.userId,e),this.startUpload()}deleteJoinedUser(e){this._localJoinedUser.delete(e)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){let e={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return e;let o=0;for(;o{let{userId:d,sdkAppId:h}=l;e.map.has(d)?e.map.get(d).logs.push(a):e.map.set(d,{userId:d,sdkAppId:h,logs:[a]})});else if(Vn(a.userId)&&kn(a.sdkAppId)){let{userId:l,sdkAppId:d}=a;e.map.has(l)?e.map.get(l).logs.push(a):e.map.set(l,{userId:l,sdkAppId:d,logs:[a]})}}return e.map.size>0&&(e.splicedQueue=this._queue.splice(0,o)),e}upload(){return WA(this,null,function*(){if(this._queue.length===0||!this._isEnableUploadLog)return;let{map:e,splicedQueue:o}=this.getLogsToUpload();if(e.size===0)return;try{let l=[...e.values()];for(let d=0;dcA.log).join(` +`)},V=JSON.stringify(k),J=TA.enable?iQ(k,2002,y):V;yield this.uploadLogWithRetry(J,y,J instanceof Uint8Array,V),S.forEach(cA=>cA.uploaded=!0)}}catch{}let a=o.filter(l=>!l.uploaded);a.length>0&&(this._queue=a.concat(this._queue))})}uploadLogWithRetry(e,o,a,l){return IM({retryFunction:()=>oQ({url:jf(o,kI.LOG),body:e,timeout:5e3,priority:"low"}).then(d=>{a&&d.data!=="ok"&&(TA.handleUploadFailed(),this.uploadLogWithRetry(l,o,!1,l))}),settings:{retries:3,timeout:2e3},onError:d=>{let{retry:h}=d;h()}})()}getPrefix(e){let o=new Date;return o.setTime(Of()),"[".concat(vb(o),"] <").concat(XB[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){Ke(XB[e])||(this._logLevel!==e&&this.info("setLogLevel",e),this._logLevel=e)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(e){if(Vn(e))return e;try{return e instanceof Error?e.toString():JSON.stringify(e)}catch{return""}}addLogToQueue(e,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0,h={log:o.reduce((y,S)=>"".concat(y," ").concat(this.logChunkToString(S)).trim(),""),level:e,userId:l,sdkAppId:d,forAllJoinedClients:a};F.emit(nA.LOG,{log:h}),this._isEnableUploadLog&&e>=this._logLevelToUpload&&this._queue.push(h)}log(e,o){let a=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2],l=arguments.length>3?arguments[3]:void 0,d=arguments.length>4?arguments[4]:void 0;var h;if(o.unshift(this.getPrefix(e)),this.addLogToQueue(e,o,a,l,d),e{let e=16*Math.random()|0;return(A=="x"?e:3&e|8).toString(16)})},zA=new class{constructor(){Y(this,"_prefix","TRTC"),Y(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){aQ()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(A=>{if(A.startsWith(this._prefix))try{let e=localStorage.getItem(A);if(!e)return!1;let o=JSON.parse(e);if(o&&o.expiresInlocalStorage.removeItem(A)))}doFlush(){if(aQ())try{for(let[A,e]of this._queue)localStorage.setItem(A,JSON.stringify(e))}catch(A){pA.warn(A)}}getItem(A){if(!aQ())return null;try{let e=localStorage.getItem(this.getRealKey(A));if(!e)return null;let o=JSON.parse(e);return o&&o.expiresIn>=Date.now()?o.value:null}catch(e){pA.warn(e)}}setItem(A,e){if(aQ())try{let o={expiresIn:Date.now()+c0,value:e};this._queue.set(this.getRealKey(A),o)}catch(o){pA.warn(o)}}deleteItem(A){if(!aQ())return!1;try{return A=this.getRealKey(A),this._queue.delete(A),localStorage.removeItem(A),!0}catch(e){return pA.warn(e),!1}}clear(){if(aQ())try{localStorage.clear()}catch(A){pA.warn(A)}}},re={};jh(re,{HTTPS_API:()=>Pk,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>q2,IS_GET_CAPABILITIES_SUPPORTED:()=>H2,IS_GET_SETTINGS_SUPPORTED:()=>Qy,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>qk,IS_INSERTABLE_STREAM_SUPPORTED:()=>zp,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>CQ,IS_RTC_RTP_SENDER_SUPPORTED:()=>xC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>o_,IS_SEI_SUPPORTED:()=>Kk,IS_SPC_SUPPORTED:()=>LM,basis:()=>j2,capabilityCheck:()=>zk,checkSystemRequirementsInternal:()=>Fk,decodeSupportStatus:()=>Uk,detectH264SupportedByFakeStreaming:()=>V2,detectVideoCodecCapabilities:()=>FM,detectVideoDecoderCapabilities:()=>Xk,detectVideoEncoderCapabilities:()=>Zk,encodeSupportStatus:()=>NM,getBrowserInfo:()=>_M,getDisplayResolution:()=>sd,getH264ProfileLevelIds:()=>Z2,isAddTransceiverSupported:()=>Xd,isBrowserSupported:()=>kk,isCanvasCaptureStreamAPISupported:()=>bM,isCanvasSmallStreamSupported:()=>i_,isGetReceiversSupported:()=>By,isGetSendersSupported:()=>UI,isGetTransceiversSupported:()=>dQ,isGetUserMediaSupported:()=>xk,isMediaDevicesSupported:()=>Lk,isMediaSessionSupported:()=>K2,isMediaStreamTrackGeneratorSupported:()=>xK,isMediaStreamTrackProcessorSupported:()=>TM,isReplaceTrackSupported:()=>J2,isRequestVideoFrameCallbackSupported:()=>Zp,isSIMDSupported:()=>UM,isScaleResolutionDownBySupported:()=>Vk,isScreenCaptureApiAvailable:()=>Wp,isSelectedCandidatePair:()=>GM,isSetParametersSupported:()=>Hk,isSetSinkIdSupported:()=>VK,isSmallStreamSupported:()=>kM,isStopTransceiverSupported:()=>oa,isTRTCSupported:()=>YK,isUnifiedPlanDefault:()=>Jk,isUsedInHttpProtocol:()=>Cu,isWebAudioSupported:()=>Yk,isWebCodecSupported:()=>s_,isWebCodecsSupported:()=>t_,isWebRTCSupported:()=>py,isWebTransportSupported:()=>fy});var Ue={};jh(Ue,{AUDIO_LEVEL_SCALE:()=>id,AlphaStitchingType:()=>dy,AudioCodecPipelineType:()=>EQ,AudioDecoderDowngradeState:()=>vM,AudioPlayerMode:()=>X0,AudioType:()=>U2,BASIC_TYPE:()=>_k,BannedReason:()=>Qg,CONNECTION_CLOSED_REASON:()=>qt,CheckPermissionType:()=>ur,ClientEvent:()=>$e,CodecType:()=>RM,ConnectionEvent:()=>Yo,ConnectionState:()=>ly,DECODE_FAILED_ERROR_CODE:()=>wM,DenoiserMode:()=>qp,DeviceType:()=>Tk,FacingMode:()=>vk,FrameWorkType:()=>oo,LeaveReason:()=>Rk,LocalTrackEvent:()=>Mo,MULTI_VIDEO_DATA_TYPE:()=>Ey,MediaType:()=>z0,MediaTypeLabel:()=>OK,MonitorEventId:()=>dl,MutedFlag:()=>$n,NetworkQualityValue:()=>EE,PlayerState:()=>Eo,ReceiveMode:()=>zl,RemoteStreamType:()=>uy,RemoteTrackEvent:()=>hn,RoomEvent:()=>uo,SMALL_MODE:()=>jp,SceneNumber:()=>qa,StreamEvent:()=>Mi,StreamType:()=>uQ,SubscribeMediaType:()=>wk,TIMER_TYPE:()=>A_,TRACK_ACTION:()=>Mk,TRACK_KIND:()=>lQ,TrackEvent:()=>Vo,UserRole:()=>Fc,UserRoleNumber:()=>is,VideoCodec:()=>Cl,VideoCodecPipelineType:()=>Kp,VideoContentHint:()=>$0,VideoDecoderDowngradeState:()=>Iy,VideoPlayerMode:()=>Z0,VideoType:()=>IQ});var be,Qe,Et,ci,et,ze,dA,ft,At,Hi,Ii,oo=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(oo||{}),Yo=((Ii=Yo||{}).TRACK_ADDED="track-added",Ii.TRACK_UPDATED="track-updated",Ii.TRACK_SUBSCRIBED="track-subscribed",Ii.STREAM_ADDED="stream-added",Ii.STREAM_REMOVED="stream-removed",Ii.STREAM_UPDATED="stream-updated",Ii.STREAM_PUBLISHED="stream-published",Ii.STREAM_SUBSCRIBED="stream-subscribed",Ii.STREAM_UNSUBSCRIBED="stream-unsubscribed",Ii.STATE_CHANGED="state-changed",Ii.ERROR="error",Ii.CONNECTION_STATE_CHANGED="connection-state-changed",Ii.FIREWALL_RESTRICTION="firewall-restriction",Ii.SEI_MESSAGE="sei-message",Ii.CLOSED="closed",Ii),qt=(A=>(A.REMOTE_LEAVE="remote user exitRoom",A.REMOTE_UNPUBLISH="remote user unpublished",A.LOCAL_LEAVE="you exitRoom",A.LOCAL_UNPUBLISH="you unpublished",A.LOCAL_UNSUBSCRIBE="you unsubscribed",A.SWITCH_ROLE="you switch role to audience",A))(qt||{}),$e=((Hi=$e||{}).STREAM_ADDED="stream-added",Hi.STREAM_REMOVED="stream-removed",Hi.STREAM_UPDATED="stream-updated",Hi.STREAM_SUBSCRIBED="stream-subscribed",Hi.CONNECTION_STATE_CHANGED="connection-state-changed",Hi.PEER_JOIN="peer-join",Hi.PEER_LEAVE="peer-leave",Hi.MUTE_AUDIO="mute-audio",Hi.MUTE_VIDEO="mute-video",Hi.UNMUTE_AUDIO="unmute-audio",Hi.UNMUTE_VIDEO="unmute-video",Hi.CLIENT_BANNED="client-banned",Hi.NETWORK_QUALITY="network-quality",Hi.AUDIO_VOLUME="audio-volume",Hi.SEI_MESSAGE="sei-message",Hi.ERROR="error",Hi),Mi=((At=Mi||{}).PLAYER_STATE_CHANGED="player-state-changed",At.SCREEN_SHARING_STOPPED="screen-sharing-stopped",At.CONNECTION_STATE_CHANGED="connection-state-changed",At.DEVICE_AUTO_RECOVERED="device-auto-recovered",At.ERROR="error",At),Mo=((ft=Mo||{}).DEVICE_AUTO_RECOVERED="1",ft.DEVICE_RECOVER_FAILED="5",ft.DEVICE_CHANGED="2",ft.ERROR="3",ft.PUBLISH_STATE_CHANGED="4",ft.ENCODE_FAILED="6",ft.TRACK_ENDED="7",ft.RENDER="render",ft),Eo=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(Eo||{}),uo=((dA=uo||{}).PEER_JOIN="peer-join",dA.PEER_LEAVE="peer-leave",dA.SIGNAL_CONNECTION_STATE_CHANGED="signal-connection-state-changed",dA.MEDIA_CONNECTION_STATE_CHANGED="media-connection-state-changed",dA.BANNED="banned",dA.NETWORK_QUALITY="network-quality",dA.AUDIO_VOLUME="audio-volume",dA.SEI_MESSAGE="sei-message",dA.ERROR="error",dA.REMOTE_PUBLISH_STATE_CHANGED="remote-publish-state-changed",dA.REMOTE_PUBLISHED="remote-published",dA.REMOTE_UNPUBLISHED="remote-unpublished",dA.FIREWALL_RESTRICTION="firewall-restriction",dA.HEARTBEAT_REPORT="heartbeat-report",dA.CUSTOM_MESSAGE="custom-message",dA.LAYER_DATA="layerData",dA.FIRST_VIDEO_FRAME="first-video-frame",dA.FIRST_FRAME_RENDER="first-frame-render",dA.DUMP="dump",dA.AUDIO_FRAME="audio-frame",dA.SUBSCRIBE_SMALL_VIDEO_CHANGED="subscribe-small-video-changed",dA.LOCAL_PUBLISH_FLAG_CHANGED="local-publish-flag-changed",dA.NTP_TIME_UPDATED="ntp-time-updated",dA.DATA_CHANNEL_MESSAGE="data-channel-message",dA.ASR_ROBOT_PEER_JOIN="asr-robot-peer-join",dA.ASR_ROBOT_PEER_LEAVE="asr-robot-peer-leave",dA),Vo=((ze=Vo||{}).PLAYER_STATE_CHANGED="player-state-changed",ze.MUTE="mute",ze.UNMUTE="unmute",ze.ERROR="error",ze.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",ze.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",ze.FIRST_VIDEO_FRAME="first-video-frame",ze.FIRST_FRAME_RENDER="first-frame-render",ze.VIDEO_SIZE_CHANGED="video-size-changed",ze),hn=(A=>(A.DECODE_FAILED="decode-failed",A.DECODE_FAILED_DURING_CALL="decode-failed-during-call",A.DECODE_DOWNGRADE_STATE_CHANGED="decode-downgrade-state-changed",A.REMOTE_PUBLISH_CHANGED="remote-publish-changed",A.AUDIO_FRAME_WITH_NTP="audio-frame-with-ntp",A))(hn||{}),$n=((et=$n||{})[et.VIDEO=1]="VIDEO",et[et.SMALL=2]="SMALL",et[et.AUX=4]="AUX",et[et.AUDIO=8]="AUDIO",et[et.VIDEO_MUTE=16]="VIDEO_MUTE",et[et.AUX_MUTE=32]="AUX_MUTE",et[et.AUDIO_MUTE=64]="AUDIO_MUTE",et),qa=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(qa||{}),is=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(is||{}),Fc=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(Fc||{}),ly=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(ly||{}),vM=((ci=vM||{}).INITIALIZED="INITIALIZED",ci.STARTING="STARTING",ci.STARTED="STARTED",ci.FAILED="FAILED",ci),Iy=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))(Iy||{}),lQ=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(lQ||{}),Mk=(A=>(A.ADD="add",A.REMOVE="remove",A))(Mk||{}),z0=(A=>(A[A.NULL=0]="NULL",A[A.AUDIO=1]="AUDIO",A[A.AUX_VIDEO=2]="AUX_VIDEO",A[A.BIG_VIDEO=4]="BIG_VIDEO",A[A.SMALL_VIDEO=8]="SMALL_VIDEO",A))(z0||{}),OK={1:"audio",2:"auxVideo",4:"video"},U2=((Et=U2||{})[Et.opus=111]="opus",Et),IQ=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))(IQ||{}),uQ=(A=>(A.Big="big",A.Small="small",A))(uQ||{}),uy=(A=>(A.Main="main",A.Aux="auxiliary",A))(uy||{}),Ey=(A=>(A[A.MULTI_DATA_AUDIO=1]="MULTI_DATA_AUDIO",A[A.MULTI_DATA_BIG_IMG=2]="MULTI_DATA_BIG_IMG",A[A.MULTI_DATA_SMALL_IMG=3]="MULTI_DATA_SMALL_IMG",A[A.MULTI_DATA_AUX_IMG=7]="MULTI_DATA_AUX_IMG",A[A.MULTI_DATA_TYPE_BUTT=12]="MULTI_DATA_TYPE_BUTT",A))(Ey||{}),dl=((Qe=dl||{})[Qe.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",Qe[Qe.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",Qe[Qe.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",Qe[Qe.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",Qe[Qe.MUTE_AUDIO=32772]="MUTE_AUDIO",Qe[Qe.MUTE_VIDEO=32773]="MUTE_VIDEO",Qe[Qe.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",Qe[Qe.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",Qe[Qe.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",Qe[Qe.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",Qe[Qe.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",Qe[Qe.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",Qe[Qe.SWITCH_CAMERA=32780]="SWITCH_CAMERA",Qe[Qe.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",Qe[Qe.REPLACE_VIDEO=32782]="REPLACE_VIDEO",Qe[Qe.REPLACE_AUDIO=32783]="REPLACE_AUDIO",Qe[Qe.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",Qe[Qe.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",Qe[Qe.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",Qe[Qe.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",Qe[Qe.JOIN=32788]="JOIN",Qe[Qe.LEAVE=32789]="LEAVE",Qe[Qe.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",Qe[Qe.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",Qe[Qe.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",Qe[Qe.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",Qe[Qe.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",Qe[Qe.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",Qe[Qe.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",Qe[Qe.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",Qe[Qe.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",Qe[Qe.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",Qe[Qe.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",Qe[Qe.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",Qe[Qe.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",Qe[Qe.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",Qe[Qe.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",Qe[Qe.PUBLISH_AUX=32805]="PUBLISH_AUX",Qe[Qe.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",Qe[Qe.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",Qe[Qe.VIDEO_ENCODER=4004]="VIDEO_ENCODER",Qe[Qe.VIDEO_DECODER=4005]="VIDEO_DECODER",Qe),EE=(A=>(A[A.UNKNOWN=0]="UNKNOWN",A[A.EXCELLENT=1]="EXCELLENT",A[A.GOOD=2]="GOOD",A[A.POOR=3]="POOR",A[A.BAD=4]="BAD",A[A.VERY_BAD=5]="VERY_BAD",A[A.DISCONNECTED=6]="DISCONNECTED",A))(EE||{}),zl=(A=>(A[A.MANUAL=0]="MANUAL",A[A.AUTO_AUDIO=1]="AUTO_AUDIO",A[A.AUTO_VIDEO=2]="AUTO_VIDEO",A[A.AUTO_ALL=3]="AUTO_ALL",A))(zl||{}),vk=(A=>(A.user="user",A.environment="environment",A))(vk||{}),Z0=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CANVAS_FROM_ELEMENT=1]="CANVAS_FROM_ELEMENT",A[A.CANVAS_WITHOUT_ELEMENT=2]="CANVAS_WITHOUT_ELEMENT",A))(Z0||{}),X0=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(X0||{}),Qg=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(Qg||{}),Rk=(A=>(A[A.USER_EXIT_REASON_TC_USER_EXIT_NORMAL=0]="USER_EXIT_REASON_TC_USER_EXIT_NORMAL",A[A.USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT=1]="USER_EXIT_REASON_TC_USER_EXIT_TIMEOUT",A[A.USER_EXIT_REASON_TC_USER_EXIT_KICKED=2]="USER_EXIT_REASON_TC_USER_EXIT_KICKED",A[A.USER_EXIT_REASON_TC_USER_EXIT_CHANGED=3]="USER_EXIT_REASON_TC_USER_EXIT_CHANGED",A[A.USER_KICK_OUT_CODE_BUSINESS_USER=4]="USER_KICK_OUT_CODE_BUSINESS_USER",A[A.USER_KICK_OUT_CODE_BUSINESS_ROOM=5]="USER_KICK_OUT_CODE_BUSINESS_ROOM",A[A.USER_KICK_OUT_CODE_SERVER_USER=6]="USER_KICK_OUT_CODE_SERVER_USER",A[A.USER_KICK_OUT_CODE_SERVER_ROOM=7]="USER_KICK_OUT_CODE_SERVER_ROOM",A[A.USER_KICK_SESS_EXSIT=8]="USER_KICK_SESS_EXSIT",A))(Rk||{}),id=1e8,qp=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(qp||{}),wk=class{constructor(){Y(this,"mediaType",0)}set audio(A){A?this.mediaType|=1:this.mediaType&=-2}get audio(){return!!(1&this.mediaType)}set video(A){A?this.mediaType|=4:this.mediaType&=-5}get video(){return!!(4&this.mediaType)}set auxiliary(A){A?this.mediaType|=2:this.mediaType&=-3}get auxiliary(){return!!(2&this.mediaType)}set smallVideo(A){A?this.mediaType|=8:this.mediaType&=-9}get smallVideo(){return!!(8&this.mediaType)}},_k=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(_k||{}),Cl=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(Cl||{}),Kp=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.DUMP=1]="DUMP",A[A.SEI=2]="SEI",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(Kp||{}),EQ=(A=>(A[A.ENCRYPT_AND_DECRYPT=0]="ENCRYPT_AND_DECRYPT",A[A.NTP_TO_AUDIO_FRAME=1]="NTP_TO_AUDIO_FRAME",A[A.DUMP=2]="DUMP",A[A.ENCODE_AND_DECODE=3]="ENCODE_AND_DECODE",A))(EQ||{}),RM=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(RM||{}),wM=((be=wM||{})[be.SUCCESS=0]="SUCCESS",be[be.FAILED=1]="FAILED",be[be.WEBCODEC_INIT=2]="WEBCODEC_INIT",be[be.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",be[be.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",be[be.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",be[be.WASM_INIT=6]="WASM_INIT",be[be.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",be[be.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",be[be.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",be[be.TEST=10]="TEST",be[be.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",be),$0=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))($0||{}),A_=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(A_||{}),jp=(A=>(A.CANVAS="canvas",A.API="api",A))(jp||{}),ur=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(ur||{}),Tk=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(Tk||{}),dy=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(dy||{}),vo={AVOID_REPEATED_CALL:"AVOID_REPEATED_CALL",INVALID_PARAMETER_REQUIRED:"INVALID_PARAMETER_REQUIRED",INVALID_PARAMETER_TYPE:"INVALID_PARAMETER_TYPE",INVALID_PARAMETER_EMPTY:"INVALID_PARAMETER_EMPTY",INVALID_PARAMETER_INSTANCE:"INVALID_PARAMETER_INSTANCE",INVALID_PARAMETER_RANGE:"INVALID_PARAMETER_RANGE",INVALID_PARAMETER_MIN:"INVALID_PARAMETER_MIN",INVALID_PARAMETER_MAX:"INVALID_PARAMETER_MAX",INVALID_PARAMETER_STREAMTYPE:"INVALID_PARAMETER_STREAMTYPE",API_CALL_TIMEOUT:"API_CALL_TIMEOUT",SIGNAL_CHANNEL_RECONNECTION_FAILED:"SIGNAL_CHANNEL_RECONNECTION_FAILED",SIGNAL_CHANNEL_SETUP_FAILED:"SIGNAL_CHANNEL_SETUP_FAILED",ERROR_MESSAGE:"ERROR_MESSAGE",EXCHANGE_SDP_TIMEOUT:"EXCHANGE_SDP_TIMEOUT",DOWNLINK_RECONNECTION_FAILED:"DOWNLINK_RECONNECTION_FAILED",EXCHANGE_SDP_FAILED:"EXCHANGE_SDP_FAILED",UPDATE_OFFER_TIMEOUT:"UPDATE_OFFER_TIMEOUT",UPLINK_RECONNECTION_FAILED:"UPLINK_RECONNECTION_FAILED",INVALID_RECORDID:"INVALID_RECORDID",INVALID_PURE_AUDIO:"INVALID_PURE_AUDIO",INVALID_STREAMID:"INVALID_STREAMID",INVALID_USER_DEFINE_RECORDID:"INVALID_USER_DEFINE_RECORDID",INVALID_USER_DEFINE_PUSH_ARGS:"INVALID_USER_DEFINE_PUSH_ARGS",INVALID_PROXY:"INVALID_PROXY",INVALID_JOIN:"INVALID_JOIN",INVALID_ROOMID_STRING:"INVALID_ROOMID_STRING",INVALID_ROOMID_INTEGER:"INVALID_ROOMID_INTEGER",INVALID_SIGNAL_CHANNEL:"INVALID_SIGNAL_CHANNEL",JOIN_ROOM_TIMEOUT:"JOIN_ROOM_TIMEOUT",JOIN_ROOM_FAILED:"JOIN_ROOM_FAILED",REJOIN_ROOM_FAILED:"REJOIN_ROOM_FAILED",INVALID_DESTROY:"INVALID_DESTROY",INVALID_PUBLISH:"INVALID_PUBLISH",INVALID_UNPUBLISH:"INVALID_UNPUBLISH",INVALID_AUDIENCE:"INVALID_AUDIENCE",INVALID_INITIALIZE:"INVALID_INITIALIZE",INVALID_DUPLICATE_PUBLISHING:"INVALID_DUPLICATE_PUBLISHING",INVALID_SUBSCRIBE_UNDEFINED:"INVALID_SUBSCRIBE_UNDEFINED",INVALID_SUBSCRIBE_LOCAL:"INVALID_SUBSCRIBE_LOCAL",INVALID_REMOTE_STREAM:"INVALID_REMOTE_STREAM",SUBSCRIBE_FAILED:"SUBSCRIBE_FAILED",INVALID_ROLE:"INVALID_ROLE",INVALID_PARAMETER_SWITCH_ROLE:"INVALID_PARAMETER_SWITCH_ROLE",INVALID_OPERATION_SWITCH_ROLE:"INVALID_OPERATION_SWITCH_ROLE",SWITCH_ROLE_TIMEOUT:"SWITCH_ROLE_TIMEOUT",SWITCH_ROLE_FAILED:"SWITCH_ROLE_FAILED",CLIENT_BANNED:"CLIENT_BANNED",INVALID_OPERATION_START_PUBLISH_CDN:"INVALID_OPERATION_START_PUBLISH_CDN",INVALID_OPERATION_STOP_PUBLISH_CDN:"INVALID_OPERATION_STOP_PUBLISH_CDN",INVALID_STREAM_ID:"INVALID_STREAM_ID",START_PUBLISH_CDN_FAILED:"START_PUBLISH_CDN_FAILED",STOP_PUBLISH_CDN_FAILED:"STOP_PUBLISH_CDN_FAILED",START_MIX_TRANSCODE:"START_MIX_TRANSCODE",STOP_MIX_TRANSCODE:"STOP_MIX_TRANSCODE",INVALID_AUDIO_VOLUME:"INVALID_AUDIO_VOLUME",ENABLE_SMALL_STREAM_PUBLISHED:"ENABLE_SMALL_STREAM_PUBLISHED",DISABLE_SMALL_STREAM_PUBLISHED:"DISABLE_SMALL_STREAM_PUBLISHED",NOT_SUPPORTED_SMALL_STREAM:"NOT_SUPPORTED_SMALL_STREAM",INVALID_SMALL_STREAM_PROFILE:"INVALID_SMALL_STREAM_PROFILE",INVALID_PARAMETER_REMOTE_STREAM:"INVALID_PARAMETER_REMOTE_STREAM",INVALID_OPERATION_CHANGE_SMALL:"INVALID_OPERATION_CHANGE_SMALL",REMOTE_NOT_PUBLISH_SMALL_STREAM:"REMOTE_NOT_PUBLISH_SMALL_STREAM",INVALID_SWITCH_DEVICE:"INVALID_SWITCH_DEVICE",INVALID_SWITCH_DEVICE_PUBLISHING:"INVALID_SWITCH_DEVICE_PUBLISHING",INVALID_REPLACE_TRACK:"INVALID_REPLACE_TRACK",INVALID_INITIALIZE_LOCAL_STREAM:"INVALID_INITIALIZE_LOCAL_STREAM",INVALID_ADD_TRACK_REPETITIVE:"INVALID_ADD_TRACK_REPETITIVE",INVALID_ADD_TRACK_REMOVING:"INVALID_ADD_TRACK_REMOVING",INVALID_ADD_TRACK_PUBLISHING:"INVALID_ADD_TRACK_PUBLISHING",INVALID_STREAM_INITIALIZED:"INVALID_STREAM_INITIALIZED",INVALID_ADD_TRACK_NUMBER:"INVALID_ADD_TRACK_NUMBER",INVALID_REMOVE_AUDIO_TRACK:"INVALID_REMOVE_AUDIO_TRACK",INVALID_REMOVE_AUDIO_ADDING:"INVALID_REMOVE_AUDIO_ADDING",INVALID_REMOVE_AUDIO_ON:"INVALID_REMOVE_AUDIO_ON",INVALID_REMOVE_TRACK_PUBLISHING:"INVALID_REMOVE_TRACK_PUBLISHING",INVALID_REMOVE_TRACK_NOT_TRACK:"INVALID_REMOVE_TRACK_NOT_TRACK",INVALID_REMOVE_TRACK_NUMBER:"INVALID_REMOVE_TRACK_NUMBER",INVALID_REPLACE_TRACK_NO_TRACK:"INVALID_REPLACE_TRACK_NO_TRACK",REPEAT_JOIN:"REPEAT_JOIN",CLIENT_DESTROYED:"CLIENT_DESTROYED",NOT_BUG_PACKAGE:"NOT_BUG_PACKAGE",START_MIX_TRANSCODE_FAILED:"START_MIX_TRANSCODE_FAILED",STOP_MIX_TRANSCODE_FAILED:"STOP_MIX_TRANSCODE_FAILED",MIX_TRANSCODE_NOT_STARTED:"MIX_TRANSCODE_NOT_STARTED",CANNOT_LESS_THAN_ZERO:"CANNOT_LESS_THAN_ZERO",MIX_PARAMS_VIDEO_FRAMERATE:"MIX_PARAMS_VIDEO_FRAMERATE",MIX_PARAMS_VIDEO_GOP:"MIX_PARAMS_VIDEO_GOP",MIX_PARAMS_AUDIO_BITRATE:"MIX_PARAMS_AUDIO_BITRATE",MIX_PARAMS_USER_Z_ORDER:"MIX_PARAMS_USER_Z_ORDER",MIX_PARAMS_NOT_SELF:"MIX_PARAMS_NOT_SELF",MIX_PARAMS_USER_STREAM:"MIX_PARAMS_USER_STREAM",INVALID_PLAY:"INVALID_PLAY",INVALID_ELEMENT_ID:"INVALID_ELEMENT_ID",INVALID_ELEMENT_ID_TYPE:"INVALID_ELEMENT_ID_TYPE",PLAY_FAILED:"PLAY_FAILED",INVALID_USERID:"INVALID_USERID",INVALID_CREATE_STREAM_SOURCE:"INVALID_CREATE_STREAM_SOURCE",INVALID_CREATE_STREAM_SCREEN:"INVALID_CREATE_STREAM_SCREEN",INVALID_CREATE_STREAM_AUDIO:"INVALID_CREATE_STREAM_AUDIO",INVALID_CREATE_STREAM_SCREEN_AUDIO:"INVALID_CREATE_STREAM_SCREEN_AUDIO",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",NOT_SUPPORTED_WEBRTC:"NOT_SUPPORTED_WEBRTC",NOT_SUPPORTED_PROFILE:"NOT_SUPPORTED_PROFILE",NOT_SUPPORTED_MEDIA:"NOT_SUPPORTED_MEDIA",NOT_SUPPORTED_H264ENCODE:"NOT_SUPPORTED_H264ENCODE",NOT_SUPPORTED_H264DECODE:"NOT_SUPPORTED_H264DECODE",NOT_SUPPORTED_TRACK:"NOT_SUPPORTED_TRACK",NOT_SUPPORTED_SWITCH_DEVICE:"NOT_SUPPORTED_SWITCH_DEVICE",NOT_SUPPORTED_CAPTURE:"NOT_SUPPORTED_CAPTURE",NOT_SUPPORTED_AUX:"NOT_SUPPORTED_AUX",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND",SIGNAL_RESPONSE_FAILED:"SIGNAL_RESPONSE_FAILED",CATCH_HANDLER_ERROR:"CATCH_HANDLER_ERROR",API_NOT_EXIST:"API_NOT_EXIST",CONNECTION_CLOSED:"CONNECTION_CLOSED",SUBSCRIBE_ALL_FALSE:"SUBSCRIBE_ALL_FALSE",SEI_NOT_SUPPORT:"SEI_NOT_SUPPORT",SEI_DISABLED:"SEI_DISABLED",SEI_BEFORE_PUBLISH:"SEI_BEFORE_PUBLISH",SEI_NOT_VIDEO:"SEI_NOT_VIDEO",CALL_FREQUENCY_LIMIT:"CALL_FREQUENCY_LIMIT",CONNECTION_ABORTED:"CONNECTION_ABORTED",API_CALL_ABORTED:"API_CALL_ABORTED",DUPLICATE_AUX:"DUPLICATE_AUX",SWITCH_PLAYBACK_QUALITY_TIMEOUT:"SWITCH_PLAYBACK_QUALITY_TIMEOUT"},cc={AVOID_REPEATED_CALL:A=>"previous ".concat(A.name,"() is ongoing, please avoid repeated calls."),INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:a,value:l}=A,d="".concat(e||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(Cg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:a,value:l}=A,d="".concat(e||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(Cg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,fnName:a,value:l}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(l,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,fnName:a,value:l}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(l,".")},API_CALL_TIMEOUT:A=>"".concat(A.commandDesc||A.command," timeout observed."),SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:A=>"SignalChannel setup failure: (errorCode: ".concat(A.errorCode,", errorMsg: ").concat(A.errorMsg," })."),ERROR_MESSAGE(A){let e="".concat(A.type," failed");return A.message&&(e="".concat(e,": ").concat(A.message,".")),e},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:A=>"exchange sdp failed ".concat(A.errMsg,"."),UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:A=>"'".concat(A,"' must be validate string when useStringRoomId is true."),INVALID_ROOMID_INTEGER:A=>"'".concat(A,"' must be an integer between [1, 4294967294] when useStringRoomId is false."),INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED(A){let{error:e,code:o}=A;return"Failed to join room - ".concat(e," code: ").concat(o)},REJOIN_ROOM_FAILED:A=>"reJoin room: ".concat(A.roomId," failed, please check your network."),INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:A=>"duplicate ".concat(A," stream publishing, please unpublish your prev ").concat(A," stream and then re-publish."),INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED(A){let{message:e,userId:o,streamType:a}=A;return"failed to subscribe ".concat(o," ").concat(a," stream, reason: ").concat(e,".")},INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:A=>"switchRole failed, errCode: ".concat(A.code," errMsg: ").concat(A.message,"."),CLIENT_BANNED:A=>"client was banned because of ".concat(A.message,"."),INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:A=>"startPublishCDNStream failed, errMsg: ".concat(A.message,"."),STOP_PUBLISH_CDN_FAILED:A=>"stopPublishCDNStream failed, errMsg: ".concat(A.message,"."),INVALID_STREAM_ID:A=>"'".concat(A,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores."),START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:A=>"cannot replace ".concat(A.kind," track because stream has not ").concat(A.kind," track"),NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:A=>"startMixTranscode failed, errMsg: ".concat(A.message,"."),STOP_MIX_TRANSCODE_FAILED:A=>"stopMixTranscode failed, errMsg: ".concat(A.message,"."),MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:A=>"'".concat(A,"' is required and must be between 1 and 15."),MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:A=>{let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE:A=>{let{key:e,fnName:o,type:a}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},PLAY_FAILED:A=>"".concat(A.media," play failed, browser exception: ").concat(A.error.toString()),INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:A=>"".concat(A,"Track is not supported on your browser."),NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:A=>"".concat(A.signalResponse," failed, response code is ").concat(A.code," , errMsg: ").concat(A.message,"."),CATCH_HANDLER_ERROR(A){let{name:e,event:o}=A;return"an error was caught in ".concat(e,".on('").concat(o,"', handler), please check your code in 'handler'.")},API_NOT_EXIST(A){let{name:e}=A;return"experimental api ".concat(e," does not exist.")},REPEAT_JOIN:A=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED(A){let{funName:e}=A;return"failed to call ".concat(e,"() because client was destroyed.")},SEI_NOT_SUPPORT:A=>"not support to sendSEIMessage".concat(A===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:A=>{let{isSize:e,name:o,timesInSecond:a,maxSizeInSecond:l}=A;return"api ".concat(o," call ").concat(e?"size":"times"," is over ").concat(e?"".concat(l," bytes"):a," in a second.")},CONNECTION_ABORTED:A=>"connection aborted due to: ".concat(A),API_CALL_ABORTED(A){let e;return e=A.message.includes("REMOTE_STREAM_NOT_EXIST")?"Subscribe ".concat(A.userId," ").concat(A.streamType," stream aborted, reason: remote user ").concat(A.userId," unpublished stream."):"API aborted, reason: ".concat(A.message),e},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:A=>"'streamType' is required when 'userId' is not '*', calling ".concat(A,"()"),SWITCH_PLAYBACK_QUALITY_TIMEOUT:A=>"switchPlaybackQuality timeout: waiting for first frame of user ".concat(A.userId,".")},F2=(A,e)=>e?"".concat(Wh,"/").concat(A,"/").concat(e):"".concat(Wh,"/").concat(A,"/index.html"),Nk=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let A=localStorage==null?void 0:localStorage.getItem(KS);if(A){A=JSON.parse(A);let e=document.createElement("script");e.type="text/javascript",e.text=A.message,document.body.appendChild(e);let o=window.TRTC_ERROR_INFO,a=window.TRTC_ERROR_LINK;return document.body.removeChild(e),{TRTC_ERROR_INFO:o,TRTC_ERROR_LINK:a}}return{}};function Xo(A){let{key:e,data:o,link:a,addDocLink:l=!0}=A,d="",h="",y="";Ra(cc[e])?d=cc[e](o):Vn(cc[e])&&(d=cc[e]);let{TRTC_ERROR_INFO:S,TRTC_ERROR_LINK:k}=Nk();a?y="".concat(a.className,".html#").concat(a.fnName):k&&k[e]&&(Ra(k[e])?y=k[e](o):Vn(k[e])&&(y=k[e]));let V=d;return Wd()&&(S&&S[e]&&(Ra(S[e])?h=S[e](o):Vn(S[e])&&(h=S[e])),h&&(V=l?"".concat(h,` +请查看文档: `).concat(F2("zh-cn",y),` -`):"".concat(C,` +`):"".concat(h,` -`),V+=d)),c&&(V+=` -Refer to: `.concat(R2("en",y),` -`)),V}var Bs,Bn,vk=gc(tK(),1),Rk=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Y(this,"countMap",new Map),Y(this,"distributionMap",new Map),Y(this,"version"),Y(this,"log",QA.createLogger({id:"kv"})),A&&(F.on("102",e=>{let{track:o,cost:a}=e;this.addSuccessEvent({key:o.kind===YA.AUDIO?501700:511700,cost:a})}),F.on("103",e=>{let{track:o,error:a}=e;this.addFailedEvent({key:o.kind===YA.AUDIO?501700:511700,error:a})}),F.on("266",e=>{let{enable:o}=e;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,e){let o={msg_sdk_basic_info:{uint32_sdk_version:qb(this.version||qd),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(a=>{let[c,d]=a;return{uint32_key:c,uint32_count:d}}),stats_distribution:[...this.distributionMap.entries()].map(a=>{let[c,d]=a;return{uint32_key:c,distribution_items:[...d.entries()].map(C=>{let[y,S]=C;return{uint32_item_key:y,uint32_item_value:S}})}}),str_user_sig:A,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let e=+String(A).slice(-3);return e>=700&&e<799}isErrorCodeKey(A){let e=+String(A).slice(-3);return e>=600&&e<699}isCountKey(A){let e=+String(A).slice(-3);return e>=0&&e<599}isNumberKey(A){let e=+String(A).slice(-3);return e>=800&&e<899}addCount(A){let{key:e,useUV:o=!1}=A;this.isCountKey(e)?o&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug("".concat(e," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:e,value:o,useUV:a=!0}=A;var c;if(!this.isEnumKey(e))return this.log.debug("".concat(e," is not enum key, last 3 number should be 700~799"));if(a&&this.countMap.has(e))return;this.countMap.set(e,(this.countMap.get(e)||0)+1);let d=((c=this.distributionMap)==null?void 0:c.get(e))||new Map;d.set(o,(d.get(o)||0)+1),this.distributionMap.set(e,d)}addNumber(A){let{key:e,value:o,split:a=100,useUV:c=!1,max:d=5e3}=A;var C;if(!this.isNumberKey(e))return this.log.debug("".concat(e," is not number key, last 3 number should be 800~899"));if(c&&this.countMap.has(e))return;o>d&&(o=d),this.countMap.set(e,(this.countMap.get(e)||0)+1);let y=((C=this.distributionMap)==null?void 0:C.get(e))||new Map,S=0;if(bn(a))S=Math.floor(o/a);else for(let k=a.length-1;k>0;k--)if(o>a[k]){S=k;break}y.set(S,(y.get(S)||0)+1),this.distributionMap.set(e,y)}addSuccessEvent(A){let{key:e,cost:o,timeKey:a,split:c}=A;if(e&&(this.addEnum({key:e,value:1,useUV:!1}),o)){let d=+String(e).slice(-3);d<800&&d>=700?this.addNumber({key:a||e+100,value:o,split:c}):a||this.log.debug("time stat ignored, ".concat(e))}}addFailedEvent(A){let{key:e,error:o}=A;if(!e)return;let a=dt.UNKNOWN;o&&(bn(o)?a=o:(!Je(o.extraCode)||!Je(o.code))&&(a=o.extraCode||o.code)),this.addEnum({key:e,value:0,useUV:!1}),this.addEnum({key:e,value:Math.abs(a),useUV:!1})}},w2=((Bs=w2||{})[Bs.enterRoom=500700]="enterRoom",Bs[Bs.exitRoom=500701]="exitRoom",Bs[Bs.switchRole=500702]="switchRole",Bs[Bs.destroy=500703]="destroy",Bs[Bs.startLocalAudio=500704]="startLocalAudio",Bs[Bs.updateLocalAudio=500705]="updateLocalAudio",Bs[Bs.stopLocalAudio=500706]="stopLocalAudio",Bs[Bs.startLocalVideo=500707]="startLocalVideo",Bs[Bs.updateLocalVideo=500708]="updateLocalVideo",Bs[Bs.stopLocalVideo=500709]="stopLocalVideo",Bs[Bs.startScreenShare=500710]="startScreenShare",Bs[Bs.updateScreenShare=500711]="updateScreenShare",Bs[Bs.stopScreenShare=500712]="stopScreenShare",Bs[Bs.startRemoteVideo=500713]="startRemoteVideo",Bs[Bs.updateRemoteVideo=500714]="updateRemoteVideo",Bs[Bs.stopRemoteVideo=500715]="stopRemoteVideo",Bs[Bs.muteRemoteAudio=500716]="muteRemoteAudio",Bs[Bs.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Bs[Bs.use=500718]="use",Bs[Bs.switchRoom=500719]="switchRoom",Bs[Bs.getPermissions=500720]="getPermissions",Bs[Bs.sendSEIMessage=5e5]="sendSEIMessage",Bs[Bs.sendCustomMessage=500001]="sendCustomMessage",Bs),_2=(A=>(A[A.AudioMixer=550700]="AudioMixer",A[A.AIDenoiser=551700]="AIDenoiser",A[A.VirtualBackground=570700]="VirtualBackground",A[A.Beauty=571700]="Beauty",A[A.Watermark=572700]="Watermark",A[A.BasicBeauty=574700]="BasicBeauty",A[A.FaceDetector=575700]="FaceDetector",A[A.CDNStreaming=590700]="CDNStreaming",A[A.DeviceDetector=591700]="DeviceDetector",A[A.Debug=592700]="Debug",A[A.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",A[A.VideoMixer=594700]="VideoMixer",A[A.AudioProcessor=595700]="AudioProcessor",A[A.LEBPlayer=596700]="LEBPlayer",A[A.RealtimeTranscriber=597700]="RealtimeTranscriber",A))(_2||{}),uy=(A=>(A[A.AudioMixer=550701]="AudioMixer",A[A.AIDenoiser=551701]="AIDenoiser",A[A.VirtualBackground=570701]="VirtualBackground",A[A.Beauty=571701]="Beauty",A[A.Watermark=572701]="Watermark",A[A.BasicBeauty=574701]="BasicBeauty",A[A.FaceDetector=575701]="FaceDetector",A[A.CDNStreaming=590701]="CDNStreaming",A[A.DeviceDetector=591701]="DeviceDetector",A[A.Debug=592701]="Debug",A[A.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",A[A.VideoMixer=594701]="VideoMixer",A[A.AudioProcessor=595701]="AudioProcessor",A[A.LEBPlayer=596701]="LEBPlayer",A[A.RealtimeTranscriber=597701]="RealtimeTranscriber",A))(uy||{}),X0=(A=>(A[A.AudioMixer=550702]="AudioMixer",A[A.AIDenoiser=551702]="AIDenoiser",A[A.VirtualBackground=570702]="VirtualBackground",A[A.Beauty=571702]="Beauty",A[A.Watermark=572702]="Watermark",A[A.BasicBeauty=574702]="BasicBeauty",A[A.FaceDetector=575702]="FaceDetector",A[A.CDNStreaming=590702]="CDNStreaming",A[A.DeviceDetector=591702]="DeviceDetector",A[A.Debug=592702]="Debug",A[A.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",A[A.VideoMixer=594702]="VideoMixer",A[A.AudioProcessor=595702]="AudioProcessor",A[A.LEBPlayer=596702]="LEBPlayer",A[A.RealtimeTranscriber=597702]="RealtimeTranscriber",A))(X0||{}),Ey=((Bn=Ey||{})[Bn.DECODER_TYPE=514700]="DECODER_TYPE",Bn[Bn.DECODER_HW_SW=514701]="DECODER_HW_SW",Bn[Bn.DECODE_RESULT=514702]="DECODE_RESULT",Bn[Bn.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",Bn[Bn.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",Bn[Bn.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",Bn[Bn.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",Bn[Bn.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",Bn[Bn.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",Bn[Bn.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",Bn[Bn.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",Bn[Bn.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",Bn[Bn.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",Bn[Bn.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",Bn[Bn.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",Bn[Bn.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",Bn[Bn.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",Bn[Bn.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",Bn[Bn.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",Bn),SK=new Rk(!0),Zh=new Rk(!1),ii=SK,Qs={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},T2=new Map([[er,["Firefox",lM]],[Ay,["Edg",tk]],[J0,["Chrome",H0]],[Bg,["Safari",oQ]],[td,["TBS",ok]],[kp,["XWEB",sk]],[tQ&&bp,["WeChat",nk]],[P0,["QQ(Win)",rk]],[uM,["QQ(Mobile)",ey]],[Lp,["QQ(Mobile X5)",ey]],[EM,["QQ(Mac)",ak]],[x0,["QQ(iPad)",dM]],[Y0,["MI",Up]],[zh,["HW",uk]],[CM,["Samsung",Ek]],[hM,["OPPO",dk]],[BM,["VIVO",QM]],[$f,["EDGE",ek]],[IM,["SogouMobile",F0]],[O0,["Sogou",ik]]]);function vM(){let A=T2.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var wk=function(){return!(ck||$f||Ay&&U0<80||er&&L0<56)},$0=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},_k=function(){if(!navigator.mediaDevices)return du()||QA.error(cc.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(e=>e in navigator.mediaDevices).length===A.length},N2=!1;function du(){return location.protocol==="http:"&&!Op&&(N2||QA.error(Xo({key:Mo.NOT_SUPPORTED_HTTP})),N2=!0,!0)}var RM=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},MK=function(){return!(window==null||!window.MediaStreamTrackGenerator)},wM=function(){return KA(this,null,function*(){var A,e,o;if(Qs.detail.isH264EncodeSupported&&Qs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Qs.detail.isH264EncodeSupported,isVp8EncodeSupported:Qs.detail.isVp8EncodeSupported,isH265EncodeSupported:Qs.detail.isH265EncodeSupported};let a,c=!1,d=!1,C=!1;try{let y=new RTCPeerConnection,S=document.createElement(YA.CANVAS);S.getContext("2d");let k=S.captureStream(0);return y.addTrack(k.getVideoTracks()[0],k),a=yield y.createOffer(),c=((A=a.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,d=((e=a.sdp)==null?void 0:e.toLowerCase().indexOf("vp8"))!==-1,C=((o=a.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,y.close(),{isH264EncodeSupported:c,isVp8EncodeSupported:d,isH265EncodeSupported:C}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},Tk=function(){return KA(this,null,function*(){var A;if(Qs.detail.isH264DecodeSupported&&Qs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Qs.detail.isH264DecodeSupported,isVp8DecodeSupported:Qs.detail.isVp8DecodeSupported,isH265DecodeSupported:Qs.detail.isH265DecodeSupported};let e,o=!1,a=!1;try{let c=new RTCPeerConnection;Xd()?(c.addTransceiver(YA.VIDEO,{direction:"recvonly"}),e=yield c.createOffer()):e=yield c.createOffer({offerToReceiveVideo:!0}),e.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(a=!0);let d=((A=e.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return c.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:a,isH265DecodeSupported:d}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},Nk=Kb(A=>KA(null,null,function*(){let e=Date.now(),o=hy(),a=_k(),c=$0();if(Qs.detail.isWebRTCSupported=o,Qs.detail.isMediaDevicesSupported=a,Qs.detail.isWebCodecsSupported=c,Qs.detail.isScreenShareSupported=qp(),Qs.detail.isSmallStreamSupported=NM(),A===37)return Object.assign(Qs.detail,yield function(){return KA(this,null,function*(){return sd||(sd=new Promise(MA=>KA(null,null,function*(){let $A={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!$0())return void MA($A);let Be=null,Ye=null,ve=null,yi=()=>{ve&&clearTimeout(ve),Be=null,Ye=null};try{Be=document.createElement("canvas"),Ye=Be.getContext("2d"),Be.width=320,Be.height=240;let Ge=0,Bt=()=>{!Ye||!Be||(Ye.fillStyle="hsl(".concat(Ge%360,", 50%, 50%)"),Ye.fillRect(0,0,Be.width,Be.height),Ye.fillStyle="white",Ye.font="20px Arial",Ye.fillText("Frame ".concat(Ge),10,30),Ge++)};ve=setTimeout(()=>{yi(),MA($A)},5e3);let hi=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(hi.map(Di=>KA(null,null,function*(){let Vo,Jo={type:Di.type,encodeSupported:!1,decodeSupported:!1};try{Vo=yield new Promise((Qn,Ho)=>KA(null,null,function*(){try{let Ns=new VideoEncoder({output:ya=>{Qn(ya),Jo.encodeSupported=!0},error:Ho});Ns.configure(Di.encodeConfig),Bt();let pg=new VideoFrame(Be,{timestamp:0});Ns.encode(pg,{keyFrame:!0}),pg.close(),yield Ns.flush(),Ns.close()}catch(Ns){Ho(Ns)}}))}catch(Qn){return QA.warn("".concat(Di.type," encoder error:"),Qn),Jo}try{yield new Promise((Qn,Ho)=>KA(null,null,function*(){try{let Ns=new VideoDecoder({output:pg=>{Jo.decodeSupported=!0,Qn(0),pg.close()},error:Ho});Ns.configure(Di.decodeConfig),Ns.decode(Vo),yield Ns.flush(),Ns.close()}catch(Ns){Ho(Ns)}}))}catch(Qn){QA.warn("".concat(Di.type," decoder error:"),Qn)}return Jo})))).forEach(Di=>{Di.type==="h264"?($A.isH264EncodeSupported=Di.encodeSupported,$A.isH264DecodeSupported=Di.decodeSupported):Di.type==="vp8"&&($A.isVp8EncodeSupported=Di.encodeSupported,$A.isVp8DecodeSupported=Di.decodeSupported)}),yi(),MA($A)}catch(Ge){yi(),QA.warn("detectWebCodecsSupported failed:",Ge),MA($A)}})),sd)})}()),Qs.detail.isBrowserSupported=c,Qs.result=a&&c,Qs.result||QA.error("".concat(navigator.userAgent," ").concat(M0(Qs.detail,!1))),Vk(A),ii.addNumber({key:523800,value:Date.now()-e}),Qs;if(Qs.result&&Qs.detail.isH264EncodeSupported&&Qs.detail.isVp8EncodeSupported&&Qs.detail.isH265EncodeSupported&&Qs.detail.isH264DecodeSupported&&Qs.detail.isVp8DecodeSupported&&Qs.detail.isH265DecodeSupported)return Qs;let d=wk(),{encode:C,decode:y}=yield function(){return KA(this,null,function*(){let[MA,$A]=yield Promise.all([wM(),Tk()]);return{encode:{h264:MA.isH264EncodeSupported,vp8:MA.isVp8EncodeSupported,h265:MA.isH265EncodeSupported},decode:{h264:$A.isH264DecodeSupported,vp8:$A.isVp8DecodeSupported,h265:$A.isH265DecodeSupported}}})}(),{h264:S,vp8:k}=C,{h264:V}=y,{h265:J}=C,{vp8:gA,h265:CA}=y;if(!S||!k){let MA=yield wM();QA.warn("detect encode again h264:".concat(S," vp8:").concat(k," result: ").concat(JSON.stringify(MA))),S=MA.isH264EncodeSupported,k=MA.isVp8EncodeSupported}if(S&&V&&Ha&&IE&&!kp&&!td&&(!hM||id!==115)){let{encode:MA,decode:$A}=yield G2();S=MA,V=$A}return Qs.result=d&&o&&a&&(S||k)&&(V||gA),Qs.detail.isBrowserSupported=d,Qs.detail.isWebRTCSupported=o,Qs.detail.isH264EncodeSupported=S,Qs.detail.isVp8EncodeSupported=k,Qs.detail.isH265EncodeSupported=J,Qs.detail.isH264DecodeSupported=V,Qs.detail.isVp8DecodeSupported=gA,Qs.detail.isH265DecodeSupported=CA,Qs.result||QA.error("".concat(navigator.userAgent," ").concat(M0(Qs.detail,!1))),Vk(),ii.addNumber({key:523800,value:Date.now()-e}),Qs})),vK=function(){return Qs.result},qp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},RK=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,Gk=null;function G2(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return KA(this,null,function*(){return Gk||(Gk=new Promise(e=>KA(null,null,function*(){let o={encode:!1,decode:!1},a=()=>{};try{let c=document.createElement("canvas"),d=c.getContext("2d");c.width=640,c.height=480;let C=setInterval(()=>{d.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),y=-1,S=-1;a=()=>{clearInterval(y),clearInterval(C),clearTimeout(S),V.close(),J.close(),k.getTracks().forEach(Be=>Be.stop())},S=setTimeout(()=>{a(),e(o)},A);let k=c.captureStream(),V=new RTCPeerConnection({}),J=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});V.addEventListener("icecandidate",Be=>J.addIceCandidate(Be.candidate)),J.addEventListener("icecandidate",Be=>V.addIceCandidate(Be.candidate)),V.addTrack(k.getVideoTracks()[0],k);let gA=yield V.createOffer();yield V.setLocalDescription(gA),yield J.setRemoteDescription(gA);let CA=yield J.createAnswer(),MA=vk.default.parse(CA.sdp),$A=MA.media[0].rtp.findIndex(Be=>Be.codec==="H264");MA.media[0].rtp=[MA.media[0].rtp[$A]],MA.media[0].fmtp=MA.media[0].fmtp.filter(Be=>Be.payload===MA.media[0].rtp[0].payload),MA.media[0].rtcpFb&&(MA.media[0].rtcpFb=MA.media[0].rtcpFb.filter(Be=>Be.payload===MA.media[0].rtp[0].payload)),CA.sdp=vk.default.write(MA),yield J.setLocalDescription(CA),yield V.setRemoteDescription(CA),y=setInterval(()=>KA(null,null,function*(){o.encode&&o.decode&&(a(),e(o));let[Be,Ye]=yield Promise.all([V.getSenders()[0].getStats(),J.getReceivers()[0].getStats()]);o.encode||Be.forEach(ve=>{ve.type==="outbound-rtp"&&(ve.mediaType===YA.VIDEO||ve.kind===YA.VIDEO)&&ve.bytesSent>0&&(o.encode=!0)}),o.decode||Ye.forEach(ve=>{ve.type==="inbound-rtp"&&(ve.mediaType===YA.VIDEO||ve.kind===YA.VIDEO)&&ve.bytesReceived>0&&(o.decode=!0)})}),100)}catch(c){a(),QA.warn("detectH264Supported failed",c),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&QA.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(UC)),e)),Gk)})}var sd=null,bk=(A,e,o)=>{location.protocol==="http:"&&!Op&&(A[e]=()=>{throw new ai({code:dt.INVALID_OPERATION,message:cc.NOT_SUPPORTED_HTTP})})},_M=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(Nr(A.selected)&&!A.selected)};function nd(){let A="";if(screen.width){let e=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(e," * ").concat(o)}return A}function kk(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Lk(){let A={isSupported:!1},e=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,e_="RTCRtpScriptTransform"in window,xk=FC&&(Kp||e_),hy=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function t_(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Je(window.AudioDecoder)||(A.AudioDecoder=!0),Je(window.AudioEncoder)||(A.AudioEncoder=!0),Je(window.VideoDecoder)||(A.VideoDecoder=!0),Je(window.VideoEncoder)||(A.VideoEncoder=!0),Je(window.ImageDecoder)||(A.ImageDecoder=!0),A}function U2(){return"mediaSession"in navigator&&!Je(navigator.mediaSession.setActionHandler)}function By(){return!Je(window.WebTransport)}function bM(){return typeof WebAssembly<"u"&&WebAssembly.validate(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 F2(){let A={browser:"".concat(nQ.name,"/").concat(nQ.version),os:El(),displayResolution:nd(),isScreenShareSupported:qp(),isWebRTCSupported:hy(),isGetUserMediaSupported:kk(),isWebAudioSupported:Lk(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:t_(),isMediaSessionSupported:U2(),isWebTransportSupported:By()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var Yk="checkResult";function Vk(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;jA.setItem(Yk+A,{ua:navigator.userAgent,checkResult:Qs})}function Jk(A){du();let e=jA.getItem(Yk+A);e&&e.ua===navigator.userAgent&&e.checkResult&&function(o,a){return!!$E(o)&&Object.keys(a).every(c=>c in o)}(e.checkResult.detail,Qs.detail)&&(Qs=e.checkResult),Nk(A)}function jp(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var uQ="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function O2(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var P2=!1;function kM(){return KA(this,null,function*(){var A;try{if(P2||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let e=xp(),o=jl();if(e===0||o===0)return;P2=!0;let a=["H264","VP8","VP9","AV1","H265"],[c,d]=yield Promise.all([Hk(a),qk(a)]);c&&Object.keys(c).forEach(S=>{let k=O2(S.toLowerCase());ii.addEnum({key:513707,value:+"".concat(k).concat(+c[S].supported).concat(+c[S].powerEfficient).concat(e).concat(o),useUV:!1})}),d&&Object.keys(d).forEach(S=>{let k=O2(S.toLowerCase());ii.addEnum({key:514713,value:+"".concat(k).concat(+d[S].supported).concat(+d[S].powerEfficient).concat(e).concat(o),useUV:!1})});let{sender:C,receiver:y}=x2();ii.addEnum({key:513708,value:+"".concat(e).concat(o).concat(+C.high),useUV:!1}),ii.addEnum({key:513709,value:+"".concat(e).concat(o).concat(+C.main),useUV:!1}),ii.addEnum({key:514714,value:+"".concat(e).concat(o).concat(+y.high),useUV:!1}),ii.addEnum({key:514715,value:+"".concat(e).concat(o).concat(+y.main),useUV:!1})}catch(e){QA.info("detectVideoCodecCapabilities failed",e)}})}function Hk(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,c=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return KA(this,null,function*(){let d={};try{for(let C of A){let y=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(C),width:e,height:o,bitrate:c,framerate:a}});d[C]=y}}catch{}return d})}function qk(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,c=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return KA(this,null,function*(){let d={};try{for(let C of A){let y=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(C),width:e,height:o,bitrate:c,framerate:a}});d[C]=y}}catch{}return d})}function x2(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let e=RTCRtpSender.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.sender.base=!0;break;case"4d":A.sender.main=!0;break;case"64":A.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let e=RTCRtpReceiver.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.receiver.base=!0;break;case"4d":A.receiver.main=!0;break;case"64":A.receiver.high=!0}}})}}catch(e){QA.warn("get H264 profile levelId failed",e)}return A}var wK=gc(Kl(),1),LM=Symbol("instance"),UM=Symbol("cacheResult"),OC=class{constructor(A,e,o){this.oldState=A,this.newState=e,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,Wp.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},i_=class extends Error{constructor(A,e,o){super(e),this.state=A,this.message=e,this.cause=o}},FM=new Map;function lc(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(a,c,d)=>{let C=o.action||c;if(!o.context){let S=FM.get(a)||[];FM.has(a)||FM.set(a,S),S.push({from:A,to:e,action:C})}let y=d.value;d.value=function(){let S=this;for(var k=arguments.length,V=new Array(k),J=0;J{if(o.fail&&o.fail.call(this,ve),o.sync){if(o.ignoreError)return ve;throw ve}return o.ignoreError?Promise.resolve(ve):Promise.reject(ve)};if(gA)return CA(gA);let MA=S.state,$A=new OC(MA,e,C);Wp.call(S,$A);let Be=ve=>{var yi;return S[UM]=ve,$A.aborted||(Wp.call(S,e),(yi=o.success)===null||yi===void 0||yi.call(this,S[UM])),ve},Ye=ve=>(Wp.call(S,MA,ve),CA(ve));try{let ve=y.apply(this,V);return function(yi){return typeof yi=="object"&&yi&&"then"in yi}(ve)?ve.then(Be).catch(Ye):o.sync?Be(ve):Promise.resolve(Be(ve))}catch(ve){return Ye(new i_(S._state,"".concat(S.name," ").concat(C," from ").concat(A," to ").concat(e," failed: ").concat(ve),ve instanceof Error?ve:new Error(String(ve))))}}}}var o_=typeof window<"u"&&window.__AFSM__?(A,e)=>{window.dispatchEvent(new CustomEvent(A,{detail:e}))}:typeof importScripts<"u"?(A,e)=>{postMessage({type:A,payload:e})}:()=>{};function Wp(A,e){let o=this._state;this._state=A;let a=A.toString();A&&this.emit(a,o),this.emit(Zs.STATECHANGED,A,o,e),this.updateDevTools({value:A,old:o,err:e instanceof Error?e.message:String(e)})}var Zs=class KC extends wK.default{constructor(e,o,a){super(),this.name=e,this.groupName=o,this._state=KC.INIT,e||(e=Date.now().toString(36)),a?Object.setPrototypeOf(this,a):a=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let c=a[LM];c?this.name=c.name+"-"+c.count++:a[LM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),o=FM.get(e)||[],a=new Set,c=[],d=[],C=new Set,y=Object.getPrototypeOf(e);FM.has(y)&&(y.stateDiagram.forEach(k=>a.add(k)),y.allStates.forEach(k=>C.add(k))),o.forEach(k=>{let{from:V,to:J,action:gA}=k;typeof V=="string"?c.push({from:V,to:J,action:gA}):V.length?V.forEach(CA=>{c.push({from:CA,to:J,action:gA})}):d.push({to:J,action:gA})}),c.forEach(k=>{let{from:V,to:J,action:gA}=k;C.add(V),C.add(J),C.add(gA+"ing"),a.add("".concat(V," --> ").concat(gA,"ing : ").concat(gA)),a.add("".concat(gA,"ing --> ").concat(J," : ").concat(gA," 🟢")),a.add("".concat(gA,"ing --> ").concat(V," : ").concat(gA," 🔴"))}),d.forEach(k=>{let{to:V,action:J}=k;a.add("".concat(J,"ing --> ").concat(V," : ").concat(J," 🟢")),C.forEach(gA=>{gA!==V&&a.add("".concat(gA," --> ").concat(J,"ing : ").concat(J))})});let S=[...a];return Object.defineProperties(e,{stateDiagram:{value:S},allStates:{value:C}}),S}static get(e){let o;return typeof e=="string"?(o=KC.instances.get(e),o||KC.instances.set(e,o=new KC(e,void 0,Object.create(KC.prototype)))):(o=KC.instances2.get(e),o||KC.instances2.set(e,o=new KC(e.constructor.name,void 0,Object.create(KC.prototype)))),o}static getState(e){var o;return(o=KC.get(e))===null||o===void 0?void 0:o.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};o_(KC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Wp.call(this,e)}};Zs.STATECHANGED="stateChanged",Zs.UPDATEAFSM="updateAFSM",Zs.INIT="[*]",Zs.ON="on",Zs.OFF="off",Zs.instances=new Map,Zs.instances2=new WeakMap;var s_=typeof window<"u",Kk=s_&&window.requestIdleCallback||function(A){let e=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1e3)},hl=s_&&window.cancelIdleCallback||function(A){clearTimeout(A)},zp=s_&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),Qy=class CE{static generateTaskID(){return this.currentTaskID++}static run(e,o,a){a!=null&&a.fps&&(a.delay=a.delay||Number((1e3/a.fps).toFixed(2))),a=mi(e==="interval"?{delay:2e3,count:0,backgroundTask:!0}:e==="ric"?{delay:1e4,count:0}:e==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},a);let c=Qo(mi({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:o},a),{delay:a.delay});return this.taskMap.set(c.taskID,c),this[e](c),c.taskID}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,CE.isBreakLoop(e)},e.delay)}static intervalInWorker(e){CE.sharedWorker||(CE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +`),V+=d)),l&&(V+=` +Refer to: `.concat(F2("en",y),` +`)),V}var Qs,Bn,Gk=gc(hK(),1),bk=class{constructor(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];Y(this,"countMap",new Map),Y(this,"distributionMap",new Map),Y(this,"version"),Y(this,"log",pA.createLogger({id:"kv"})),A&&(F.on("102",e=>{let{track:o,cost:a}=e;this.addSuccessEvent({key:o.kind===YA.AUDIO?501700:511700,cost:a})}),F.on("103",e=>{let{track:o,error:a}=e;this.addFailedEvent({key:o.kind===YA.AUDIO?501700:511700,error:a})}),F.on("266",e=>{let{enable:o}=e;this.log.info("".concat(o?"enable":"disable"," sso")),o?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(A,e){let o={msg_sdk_basic_info:{uint32_sdk_version:Xb(this.version||qd),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,uint32_count:d}}),stats_distribution:[...this.distributionMap.entries()].map(a=>{let[l,d]=a;return{uint32_key:l,distribution_items:[...d.entries()].map(h=>{let[y,S]=h;return{uint32_item_key:y,uint32_item_value:S}})}}),str_user_sig:A,bytes_report_token:e};return this.countMap.clear(),this.distributionMap.clear(),o}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(A){let e=+String(A).slice(-3);return e>=700&&e<799}isErrorCodeKey(A){let e=+String(A).slice(-3);return e>=600&&e<699}isCountKey(A){let e=+String(A).slice(-3);return e>=0&&e<599}isNumberKey(A){let e=+String(A).slice(-3);return e>=800&&e<899}addCount(A){let{key:e,useUV:o=!1}=A;this.isCountKey(e)?o&&this.countMap.has(e)||this.countMap.set(e,(this.countMap.get(e)||0)+1):this.log.debug("".concat(e," is not count key, last 3 number should be 0~599"))}addEnum(A){let{key:e,value:o,useUV:a=!0}=A;var l;if(!this.isEnumKey(e))return this.log.debug("".concat(e," is not enum key, last 3 number should be 700~799"));if(a&&this.countMap.has(e))return;this.countMap.set(e,(this.countMap.get(e)||0)+1);let d=((l=this.distributionMap)==null?void 0:l.get(e))||new Map;d.set(o,(d.get(o)||0)+1),this.distributionMap.set(e,d)}addNumber(A){let{key:e,value:o,split:a=100,useUV:l=!1,max:d=5e3}=A;var h;if(!this.isNumberKey(e))return this.log.debug("".concat(e," is not number key, last 3 number should be 800~899"));if(l&&this.countMap.has(e))return;o>d&&(o=d),this.countMap.set(e,(this.countMap.get(e)||0)+1);let y=((h=this.distributionMap)==null?void 0:h.get(e))||new Map,S=0;if(kn(a))S=Math.floor(o/a);else for(let k=a.length-1;k>0;k--)if(o>a[k]){S=k;break}y.set(S,(y.get(S)||0)+1),this.distributionMap.set(e,y)}addSuccessEvent(A){let{key:e,cost:o,timeKey:a,split:l}=A;if(e&&(this.addEnum({key:e,value:1,useUV:!1}),o)){let d=+String(e).slice(-3);d<800&&d>=700?this.addNumber({key:a||e+100,value:o,split:l}):a||this.log.debug("time stat ignored, ".concat(e))}}addFailedEvent(A){let{key:e,error:o}=A;if(!e)return;let a=Ct.UNKNOWN;o&&(kn(o)?a=o:(!Ke(o.extraCode)||!Ke(o.code))&&(a=o.extraCode||o.code)),this.addEnum({key:e,value:0,useUV:!1}),this.addEnum({key:e,value:Math.abs(a),useUV:!1})}},O2=((Qs=O2||{})[Qs.enterRoom=500700]="enterRoom",Qs[Qs.exitRoom=500701]="exitRoom",Qs[Qs.switchRole=500702]="switchRole",Qs[Qs.destroy=500703]="destroy",Qs[Qs.startLocalAudio=500704]="startLocalAudio",Qs[Qs.updateLocalAudio=500705]="updateLocalAudio",Qs[Qs.stopLocalAudio=500706]="stopLocalAudio",Qs[Qs.startLocalVideo=500707]="startLocalVideo",Qs[Qs.updateLocalVideo=500708]="updateLocalVideo",Qs[Qs.stopLocalVideo=500709]="stopLocalVideo",Qs[Qs.startScreenShare=500710]="startScreenShare",Qs[Qs.updateScreenShare=500711]="updateScreenShare",Qs[Qs.stopScreenShare=500712]="stopScreenShare",Qs[Qs.startRemoteVideo=500713]="startRemoteVideo",Qs[Qs.updateRemoteVideo=500714]="updateRemoteVideo",Qs[Qs.stopRemoteVideo=500715]="stopRemoteVideo",Qs[Qs.muteRemoteAudio=500716]="muteRemoteAudio",Qs[Qs.setRemoteAudioVolume=500717]="setRemoteAudioVolume",Qs[Qs.use=500718]="use",Qs[Qs.switchRoom=500719]="switchRoom",Qs[Qs.getPermissions=500720]="getPermissions",Qs[Qs.sendSEIMessage=5e5]="sendSEIMessage",Qs[Qs.sendCustomMessage=500001]="sendCustomMessage",Qs),P2=(A=>(A[A.AudioMixer=550700]="AudioMixer",A[A.AIDenoiser=551700]="AIDenoiser",A[A.VirtualBackground=570700]="VirtualBackground",A[A.Beauty=571700]="Beauty",A[A.Watermark=572700]="Watermark",A[A.BasicBeauty=574700]="BasicBeauty",A[A.FaceDetector=575700]="FaceDetector",A[A.CDNStreaming=590700]="CDNStreaming",A[A.DeviceDetector=591700]="DeviceDetector",A[A.Debug=592700]="Debug",A[A.SmallStreamAutoSwitcher=593700]="SmallStreamAutoSwitcher",A[A.VideoMixer=594700]="VideoMixer",A[A.AudioProcessor=595700]="AudioProcessor",A[A.LEBPlayer=596700]="LEBPlayer",A[A.RealtimeTranscriber=597700]="RealtimeTranscriber",A))(P2||{}),Cy=(A=>(A[A.AudioMixer=550701]="AudioMixer",A[A.AIDenoiser=551701]="AIDenoiser",A[A.VirtualBackground=570701]="VirtualBackground",A[A.Beauty=571701]="Beauty",A[A.Watermark=572701]="Watermark",A[A.BasicBeauty=574701]="BasicBeauty",A[A.FaceDetector=575701]="FaceDetector",A[A.CDNStreaming=590701]="CDNStreaming",A[A.DeviceDetector=591701]="DeviceDetector",A[A.Debug=592701]="Debug",A[A.SmallStreamAutoSwitcher=593701]="SmallStreamAutoSwitcher",A[A.VideoMixer=594701]="VideoMixer",A[A.AudioProcessor=595701]="AudioProcessor",A[A.LEBPlayer=596701]="LEBPlayer",A[A.RealtimeTranscriber=597701]="RealtimeTranscriber",A))(Cy||{}),e_=(A=>(A[A.AudioMixer=550702]="AudioMixer",A[A.AIDenoiser=551702]="AIDenoiser",A[A.VirtualBackground=570702]="VirtualBackground",A[A.Beauty=571702]="Beauty",A[A.Watermark=572702]="Watermark",A[A.BasicBeauty=574702]="BasicBeauty",A[A.FaceDetector=575702]="FaceDetector",A[A.CDNStreaming=590702]="CDNStreaming",A[A.DeviceDetector=591702]="DeviceDetector",A[A.Debug=592702]="Debug",A[A.SmallStreamAutoSwitcher=593702]="SmallStreamAutoSwitcher",A[A.VideoMixer=594702]="VideoMixer",A[A.AudioProcessor=595702]="AudioProcessor",A[A.LEBPlayer=596702]="LEBPlayer",A[A.RealtimeTranscriber=597702]="RealtimeTranscriber",A))(e_||{}),hy=((Bn=hy||{})[Bn.DECODER_TYPE=514700]="DECODER_TYPE",Bn[Bn.DECODER_HW_SW=514701]="DECODER_HW_SW",Bn[Bn.DECODE_RESULT=514702]="DECODE_RESULT",Bn[Bn.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",Bn[Bn.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",Bn[Bn.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",Bn[Bn.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",Bn[Bn.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",Bn[Bn.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",Bn[Bn.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",Bn[Bn.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",Bn[Bn.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",Bn[Bn.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",Bn[Bn.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",Bn[Bn.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",Bn[Bn.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",Bn[Bn.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",Bn[Bn.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",Bn[Bn.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",Bn),PK=new bk(!0),AB=new bk(!1),si=PK,ps={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},x2=new Map([[or,["Firefox",EM]],[iy,["Edg",ak]],[K0,["Chrome",j0]],[Bg,["Safari",rQ]],[ed,["TBS",ck]],[Fp,["XWEB",lk]],[sQ&&Up,["WeChat",Ik]],[V0,["QQ(Win)",uk]],[CM,["QQ(Mobile)",oy]],[Op,["QQ(Mobile X5)",oy]],[hM,["QQ(Mac)",Ek]],[J0,["QQ(iPad)",BM]],[H0,["MI",Pp]],[$h,["HW",Qk]],[QM,["Samsung",pk]],[pM,["OPPO",mk]],[mM,["VIVO",fM]],[ty,["EDGE",rk]],[dM,["SogouMobile",x0]],[Y0,["Sogou",gk]]]);function _M(){let A=x2.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var kk=function(){return!(Ck||ty||iy&&P0<80||or&&O0<56)},t_=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},Lk=function(){if(!navigator.mediaDevices)return Cu()||pA.error(cc.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(e=>e in navigator.mediaDevices).length===A.length},Y2=!1;function Cu(){return location.protocol==="http:"&&!Yp&&(Y2||pA.error(Xo({key:vo.NOT_SUPPORTED_HTTP})),Y2=!0,!0)}var TM=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},xK=function(){return!(window==null||!window.MediaStreamTrackGenerator)},NM=function(){return WA(this,null,function*(){var A,e,o;if(ps.detail.isH264EncodeSupported&&ps.detail.isVp8EncodeSupported)return{isH264EncodeSupported:ps.detail.isH264EncodeSupported,isVp8EncodeSupported:ps.detail.isVp8EncodeSupported,isH265EncodeSupported:ps.detail.isH265EncodeSupported};let a,l=!1,d=!1,h=!1;try{let y=new RTCPeerConnection,S=document.createElement(YA.CANVAS);S.getContext("2d");let k=S.captureStream(0);return y.addTrack(k.getVideoTracks()[0],k),a=yield y.createOffer(),l=((A=a.sdp)==null?void 0:A.toLowerCase().indexOf("h264"))!==-1,d=((e=a.sdp)==null?void 0:e.toLowerCase().indexOf("vp8"))!==-1,h=((o=a.sdp)==null?void 0:o.toLowerCase().indexOf("h265"))!==-1,y.close(),{isH264EncodeSupported:l,isVp8EncodeSupported:d,isH265EncodeSupported:h}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},Uk=function(){return WA(this,null,function*(){var A;if(ps.detail.isH264DecodeSupported&&ps.detail.isVp8DecodeSupported)return{isH264DecodeSupported:ps.detail.isH264DecodeSupported,isVp8DecodeSupported:ps.detail.isVp8DecodeSupported,isH265DecodeSupported:ps.detail.isH265DecodeSupported};let e,o=!1,a=!1;try{let l=new RTCPeerConnection;Xd()?(l.addTransceiver(YA.VIDEO,{direction:"recvonly"}),e=yield l.createOffer()):e=yield l.createOffer({offerToReceiveVideo:!0}),e.sdp.toLowerCase().indexOf("h264")!==-1&&(o=!0),e.sdp.toLowerCase().indexOf("vp8")!==-1&&(a=!0);let d=((A=e.sdp)==null?void 0:A.toLowerCase().indexOf("h265"))!==-1;return l.close(),{isH264DecodeSupported:o,isVp8DecodeSupported:a,isH265DecodeSupported:d}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}})},Fk=$b(A=>WA(null,null,function*(){let e=Date.now(),o=py(),a=Lk(),l=t_();if(ps.detail.isWebRTCSupported=o,ps.detail.isMediaDevicesSupported=a,ps.detail.isWebCodecsSupported=l,ps.detail.isScreenShareSupported=Wp(),ps.detail.isSmallStreamSupported=kM(),A===37)return Object.assign(ps.detail,yield function(){return WA(this,null,function*(){return od||(od=new Promise(MA=>WA(null,null,function*(){let ie={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!t_())return void MA(ie);let pe=null,qe=null,we=null,Di=()=>{we&&clearTimeout(we),pe=null,qe=null};try{pe=document.createElement("canvas"),qe=pe.getContext("2d"),pe.width=320,pe.height=240;let Le=0,Qt=()=>{!qe||!pe||(qe.fillStyle="hsl(".concat(Le%360,", 50%, 50%)"),qe.fillRect(0,0,pe.width,pe.height),qe.fillStyle="white",qe.font="20px Arial",qe.fillText("Frame ".concat(Le),10,30),Le++)};we=setTimeout(()=>{Di(),MA(ie)},5e3);let Bi=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(yield Promise.all(Bi.map(Si=>WA(null,null,function*(){let Jo,Ho={type:Si.type,encodeSupported:!1,decodeSupported:!1};try{Jo=yield new Promise((Qn,qo)=>WA(null,null,function*(){try{let Ns=new VideoEncoder({output:ya=>{Qn(ya),Ho.encodeSupported=!0},error:qo});Ns.configure(Si.encodeConfig),Qt();let pg=new VideoFrame(pe,{timestamp:0});Ns.encode(pg,{keyFrame:!0}),pg.close(),yield Ns.flush(),Ns.close()}catch(Ns){qo(Ns)}}))}catch(Qn){return pA.warn("".concat(Si.type," encoder error:"),Qn),Ho}try{yield new Promise((Qn,qo)=>WA(null,null,function*(){try{let Ns=new VideoDecoder({output:pg=>{Ho.decodeSupported=!0,Qn(0),pg.close()},error:qo});Ns.configure(Si.decodeConfig),Ns.decode(Jo),yield Ns.flush(),Ns.close()}catch(Ns){qo(Ns)}}))}catch(Qn){pA.warn("".concat(Si.type," decoder error:"),Qn)}return Ho})))).forEach(Si=>{Si.type==="h264"?(ie.isH264EncodeSupported=Si.encodeSupported,ie.isH264DecodeSupported=Si.decodeSupported):Si.type==="vp8"&&(ie.isVp8EncodeSupported=Si.encodeSupported,ie.isVp8DecodeSupported=Si.decodeSupported)}),Di(),MA(ie)}catch(Le){Di(),pA.warn("detectWebCodecsSupported failed:",Le),MA(ie)}})),od)})}()),ps.detail.isBrowserSupported=l,ps.result=a&&l,ps.result||pA.error("".concat(navigator.userAgent," ").concat(w0(ps.detail,!1))),Wk(A),si.addNumber({key:523800,value:Date.now()-e}),ps;if(ps.result&&ps.detail.isH264EncodeSupported&&ps.detail.isVp8EncodeSupported&&ps.detail.isH265EncodeSupported&&ps.detail.isH264DecodeSupported&&ps.detail.isVp8DecodeSupported&&ps.detail.isH265DecodeSupported)return ps;let d=kk(),{encode:h,decode:y}=yield function(){return WA(this,null,function*(){let[MA,ie]=yield Promise.all([NM(),Uk()]);return{encode:{h264:MA.isH264EncodeSupported,vp8:MA.isVp8EncodeSupported,h265:MA.isH265EncodeSupported},decode:{h264:ie.isH264DecodeSupported,vp8:ie.isVp8DecodeSupported,h265:ie.isH265DecodeSupported}}})}(),{h264:S,vp8:k}=h,{h264:V}=y,{h265:J}=h,{vp8:cA,h265:CA}=y;if(!S||!k){let MA=yield NM();pA.warn("detect encode again h264:".concat(S," vp8:").concat(k," result: ").concat(JSON.stringify(MA))),S=MA.isH264EncodeSupported,k=MA.isVp8EncodeSupported}if(S&&V&&Ha&&uE&&!Fp&&!ed&&(!pM||td!==115)){let{encode:MA,decode:ie}=yield V2();S=MA,V=ie}return ps.result=d&&o&&a&&(S||k)&&(V||cA),ps.detail.isBrowserSupported=d,ps.detail.isWebRTCSupported=o,ps.detail.isH264EncodeSupported=S,ps.detail.isVp8EncodeSupported=k,ps.detail.isH265EncodeSupported=J,ps.detail.isH264DecodeSupported=V,ps.detail.isVp8DecodeSupported=cA,ps.detail.isH265DecodeSupported=CA,ps.result||pA.error("".concat(navigator.userAgent," ").concat(w0(ps.detail,!1))),Wk(),si.addNumber({key:523800,value:Date.now()-e}),ps})),YK=function(){return ps.result},Wp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},VK=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,Ok=null;function V2(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return WA(this,null,function*(){return Ok||(Ok=new Promise(e=>WA(null,null,function*(){let o={encode:!1,decode:!1},a=()=>{};try{let l=document.createElement("canvas"),d=l.getContext("2d");l.width=640,l.height=480;let h=setInterval(()=>{d.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66),y=-1,S=-1;a=()=>{clearInterval(y),clearInterval(h),clearTimeout(S),V.close(),J.close(),k.getTracks().forEach(pe=>pe.stop())},S=setTimeout(()=>{a(),e(o)},A);let k=l.captureStream(),V=new RTCPeerConnection({}),J=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});V.addEventListener("icecandidate",pe=>J.addIceCandidate(pe.candidate)),J.addEventListener("icecandidate",pe=>V.addIceCandidate(pe.candidate)),V.addTrack(k.getVideoTracks()[0],k);let cA=yield V.createOffer();yield V.setLocalDescription(cA),yield J.setRemoteDescription(cA);let CA=yield J.createAnswer(),MA=Gk.default.parse(CA.sdp),ie=MA.media[0].rtp.findIndex(pe=>pe.codec==="H264");MA.media[0].rtp=[MA.media[0].rtp[ie]],MA.media[0].fmtp=MA.media[0].fmtp.filter(pe=>pe.payload===MA.media[0].rtp[0].payload),MA.media[0].rtcpFb&&(MA.media[0].rtcpFb=MA.media[0].rtcpFb.filter(pe=>pe.payload===MA.media[0].rtp[0].payload)),CA.sdp=Gk.default.write(MA),yield J.setLocalDescription(CA),yield V.setRemoteDescription(CA),y=setInterval(()=>WA(null,null,function*(){o.encode&&o.decode&&(a(),e(o));let[pe,qe]=yield Promise.all([V.getSenders()[0].getStats(),J.getReceivers()[0].getStats()]);o.encode||pe.forEach(we=>{we.type==="outbound-rtp"&&(we.mediaType===YA.VIDEO||we.kind===YA.VIDEO)&&we.bytesSent>0&&(o.encode=!0)}),o.decode||qe.forEach(we=>{we.type==="inbound-rtp"&&(we.mediaType===YA.VIDEO||we.kind===YA.VIDEO)&&we.bytesReceived>0&&(o.decode=!0)})}),100)}catch(l){a(),pA.warn("detectH264Supported failed",l),e({encode:!0,decode:!0})}})).then(e=>(e.encode||(e.decode=!0),(!e.encode||!e.decode)&&pA.warn("detectH264Supported encode: ".concat(e.encode," decode: ").concat(e.decode," ").concat(PC)),e)),Ok)})}var od=null,Pk=(A,e,o)=>{location.protocol==="http:"&&!Yp&&(A[e]=()=>{throw new gi({code:Ct.INVALID_OPERATION,message:cc.NOT_SUPPORTED_HTTP})})},GM=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(Nr(A.selected)&&!A.selected)};function sd(){let A="";if(screen.width){let e=screen.width?screen.width*window.devicePixelRatio:"",o=screen.height?screen.height*window.devicePixelRatio:"";A+="".concat(e," * ").concat(o)}return A}function xk(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function Yk(){let A={isSupported:!1},e=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,o_="RTCRtpScriptTransform"in window,Kk=xC&&(zp||o_),py=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function s_(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return Ke(window.AudioDecoder)||(A.AudioDecoder=!0),Ke(window.AudioEncoder)||(A.AudioEncoder=!0),Ke(window.VideoDecoder)||(A.VideoDecoder=!0),Ke(window.VideoEncoder)||(A.VideoEncoder=!0),Ke(window.ImageDecoder)||(A.ImageDecoder=!0),A}function K2(){return"mediaSession"in navigator&&!Ke(navigator.mediaSession.setActionHandler)}function fy(){return!Ke(window.WebTransport)}function UM(){return typeof WebAssembly<"u"&&WebAssembly.validate(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 j2(){let A={browser:"".concat(gQ.name,"/").concat(gQ.version),os:El(),displayResolution:sd(),isScreenShareSupported:Wp(),isWebRTCSupported:py(),isGetUserMediaSupported:xk(),isWebAudioSupported:Yk(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:s_(),isMediaSessionSupported:K2(),isWebTransportSupported:fy()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var jk="checkResult";function Wk(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;zA.setItem(jk+A,{ua:navigator.userAgent,checkResult:ps})}function zk(A){Cu();let e=zA.getItem(jk+A);e&&e.ua===navigator.userAgent&&e.checkResult&&function(o,a){return!!XE(o)&&Object.keys(a).every(l=>l in o)}(e.checkResult.detail,ps.detail)&&(ps=e.checkResult),Fk(A)}function Zp(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var CQ="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function W2(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var z2=!1;function FM(){return WA(this,null,function*(){var A;try{if(z2||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let e=Jp(),o=Wl();if(e===0||o===0)return;z2=!0;let a=["H264","VP8","VP9","AV1","H265"],[l,d]=yield Promise.all([Zk(a),Xk(a)]);l&&Object.keys(l).forEach(S=>{let k=W2(S.toLowerCase());si.addEnum({key:513707,value:+"".concat(k).concat(+l[S].supported).concat(+l[S].powerEfficient).concat(e).concat(o),useUV:!1})}),d&&Object.keys(d).forEach(S=>{let k=W2(S.toLowerCase());si.addEnum({key:514713,value:+"".concat(k).concat(+d[S].supported).concat(+d[S].powerEfficient).concat(e).concat(o),useUV:!1})});let{sender:h,receiver:y}=Z2();si.addEnum({key:513708,value:+"".concat(e).concat(o).concat(+h.high),useUV:!1}),si.addEnum({key:513709,value:+"".concat(e).concat(o).concat(+h.main),useUV:!1}),si.addEnum({key:514714,value:+"".concat(e).concat(o).concat(+y.high),useUV:!1}),si.addEnum({key:514715,value:+"".concat(e).concat(o).concat(+y.main),useUV:!1})}catch(e){pA.info("detectVideoCodecCapabilities failed",e)}})}function Zk(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return WA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:e,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function Xk(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1920,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1080,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:30,l=arguments.length>4&&arguments[4]!==void 0?arguments[4]:3e3;return WA(this,null,function*(){let d={};try{for(let h of A){let y=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(h),width:e,height:o,bitrate:l,framerate:a}});d[h]=y}}catch{}return d})}function Z2(){let A={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){let e=RTCRtpSender.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.sender.base=!0;break;case"4d":A.sender.main=!0;break;case"64":A.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){let e=RTCRtpReceiver.getCapabilities("video");e&&e.codecs&&e.codecs.filter(o=>o.mimeType.toLowerCase()==="video/h264").forEach(o=>{if(o.sdpFmtpLine){let a=o.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(a&&a[1])switch(a[1].slice(0,2)){case"42":A.receiver.base=!0;break;case"4d":A.receiver.main=!0;break;case"64":A.receiver.high=!0}}})}}catch(e){pA.warn("get H264 profile levelId failed",e)}return A}var JK=gc(jl(),1),OM=Symbol("instance"),PM=Symbol("cacheResult"),YC=class{constructor(A,e,o){this.oldState=A,this.newState=e,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,Xp.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},n_=class extends Error{constructor(A,e,o){super(e),this.state=A,this.message=e,this.cause=o}},xM=new Map;function lc(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return(a,l,d)=>{let h=o.action||l;if(!o.context){let S=xM.get(a)||[];xM.has(a)||xM.set(a,S),S.push({from:A,to:e,action:h})}let y=d.value;d.value=function(){let S=this;for(var k=arguments.length,V=new Array(k),J=0;J{if(o.fail&&o.fail.call(this,we),o.sync){if(o.ignoreError)return we;throw we}return o.ignoreError?Promise.resolve(we):Promise.reject(we)};if(cA)return CA(cA);let MA=S.state,ie=new YC(MA,e,h);Xp.call(S,ie);let pe=we=>{var Di;return S[PM]=we,ie.aborted||(Xp.call(S,e),(Di=o.success)===null||Di===void 0||Di.call(this,S[PM])),we},qe=we=>(Xp.call(S,MA,we),CA(we));try{let we=y.apply(this,V);return function(Di){return typeof Di=="object"&&Di&&"then"in Di}(we)?we.then(pe).catch(qe):o.sync?pe(we):Promise.resolve(pe(we))}catch(we){return qe(new n_(S._state,"".concat(S.name," ").concat(h," from ").concat(A," to ").concat(e," failed: ").concat(we),we instanceof Error?we:new Error(String(we))))}}}}var r_=typeof window<"u"&&window.__AFSM__?(A,e)=>{window.dispatchEvent(new CustomEvent(A,{detail:e}))}:typeof importScripts<"u"?(A,e)=>{postMessage({type:A,payload:e})}:()=>{};function Xp(A,e){let o=this._state;this._state=A;let a=A.toString();A&&this.emit(a,o),this.emit(Zs.STATECHANGED,A,o,e),this.updateDevTools({value:A,old:o,err:e instanceof Error?e.message:String(e)})}var Zs=class zC extends JK.default{constructor(e,o,a){super(),this.name=e,this.groupName=o,this._state=zC.INIT,e||(e=Date.now().toString(36)),a?Object.setPrototypeOf(this,a):a=Object.getPrototypeOf(this),o||(this.groupName=this.constructor.name);let l=a[OM];l?this.name=l.name+"-"+l.count++:a[OM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),o=xM.get(e)||[],a=new Set,l=[],d=[],h=new Set,y=Object.getPrototypeOf(e);xM.has(y)&&(y.stateDiagram.forEach(k=>a.add(k)),y.allStates.forEach(k=>h.add(k))),o.forEach(k=>{let{from:V,to:J,action:cA}=k;typeof V=="string"?l.push({from:V,to:J,action:cA}):V.length?V.forEach(CA=>{l.push({from:CA,to:J,action:cA})}):d.push({to:J,action:cA})}),l.forEach(k=>{let{from:V,to:J,action:cA}=k;h.add(V),h.add(J),h.add(cA+"ing"),a.add("".concat(V," --> ").concat(cA,"ing : ").concat(cA)),a.add("".concat(cA,"ing --> ").concat(J," : ").concat(cA," 🟢")),a.add("".concat(cA,"ing --> ").concat(V," : ").concat(cA," 🔴"))}),d.forEach(k=>{let{to:V,action:J}=k;a.add("".concat(J,"ing --> ").concat(V," : ").concat(J," 🟢")),h.forEach(cA=>{cA!==V&&a.add("".concat(cA," --> ").concat(J,"ing : ").concat(J))})});let S=[...a];return Object.defineProperties(e,{stateDiagram:{value:S},allStates:{value:h}}),S}static get(e){let o;return typeof e=="string"?(o=zC.instances.get(e),o||zC.instances.set(e,o=new zC(e,void 0,Object.create(zC.prototype)))):(o=zC.instances2.get(e),o||zC.instances2.set(e,o=new zC(e.constructor.name,void 0,Object.create(zC.prototype)))),o}static getState(e){var o;return(o=zC.get(e))===null||o===void 0?void 0:o.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};r_(zC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Xp.call(this,e)}};Zs.STATECHANGED="stateChanged",Zs.UPDATEAFSM="updateAFSM",Zs.INIT="[*]",Zs.ON="on",Zs.OFF="off",Zs.instances=new Map,Zs.instances2=new WeakMap;var a_=typeof window<"u",$k=a_&&window.requestIdleCallback||function(A){let e=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1e3)},hl=a_&&window.cancelIdleCallback||function(A){clearTimeout(A)},$p=a_&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),yy=class hE{static generateTaskID(){return this.currentTaskID++}static run(e,o,a){a!=null&&a.fps&&(a.delay=a.delay||Number((1e3/a.fps).toFixed(2))),a=fi(e==="interval"?{delay:2e3,count:0,backgroundTask:!0}:e==="ric"?{delay:1e4,count:0}:e==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0},a);let l=po(fi({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:e,callback:o},a),{delay:a.delay});return this.taskMap.set(l.taskID,l),this[e](l),l.taskID}static interval(e){return e.intervalID=setInterval(()=>{e.callback(),e.loopCount+=1,hE.isBreakLoop(e)},e.delay)}static intervalInWorker(e){hE.sharedWorker||(hE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -274,15 +274,15 @@ Refer to: `.concat(R2("en",y),` timers.delete(taskId); } }; - `],{type:"application/javascript"}))),CE.sharedWorker.onmessage=o=>{var a;if(o.data.type==="tick"){let c=CE.workerTasks.get(o.data.taskId);c&&(CE.isBreakLoop(c)?((a=CE.sharedWorker)==null||a.postMessage({type:"stop",taskId:c.taskID}),CE.workerTasks.delete(c.taskID)):(c.callback(),c.loopCount+=1))}}),CE.workerTasks.set(e.taskID,e),CE.sharedWorker.postMessage({taskId:e.taskID,delay:e.delay,type:"start"})}static timeout(e){let o=()=>{if(e.callback(),e.loopCount+=1,!CE.isBreakLoop(e))return e.timeoutID=setTimeout(o,e.delay)};return e.timeoutID=setTimeout(o,e.delay)}static ric(e){let o,a=ko(),c=()=>{if(o=ko()-a,o>=e.delay&&(a=ko()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),!CE.isBreakLoop(e))return e.ricID=Kk(c,{timeout:e.delay})};return e.ricID=Kk(c,{timeout:e.delay})}static raf(e){let o,a=ko(),c=()=>document.hidden&&e.backgroundTask?(o=ko()-a,a=ko(),e.callback(),e.loopCount+=1,CE.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(c,e.delay-Math.floor(o%e.delay))):(o=ko()-a,o>=e.delay&&(a=ko()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),CE.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(c));if(e.rafID=requestAnimationFrame(c),e.backgroundTask){let d=()=>{if(document.hidden){let C=ko()-a;C>=e.delay?c():e.timeoutID=setTimeout(c,e.delay-C)}};document.addEventListener("visibilitychange",d),e.onVisibilitychange=d,document.hidden&&d()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:o,timeoutID:a,rafID:c,ricID:d,onVisibilitychange:C}=this.taskMap.get(e);return o&&clearInterval(o),a&&clearTimeout(a),c&&zp&&zp(c),d&&hl(d),C&&document.removeEventListener("visibilitychange",C),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||e.count!==0&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Y(Qy,"taskMap",new Map),Y(Qy,"currentTaskID",1),Y(Qy,"sharedWorker",null),Y(Qy,"workerTasks",new Map);var Gr=Qy,fo={LOAD_START:YA.LOADSTART,LOADED_DATA:YA.LOADEDDATA,LOADED_META_DATA:YA.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:YA.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:YA.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:YA.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change",FIRST_FRAME_RENDER:"first-frame-render"},jk={};Hh(jk,{create:()=>rd,remove:()=>kn});var Xh=new WeakMap;function rd(A,e){Xh.has(A)||Xh.set(A,[]);let o=Xh.get(A),a={add:(c,d)=>("addEventListener"in e?(o.push(e.removeEventListener.bind(e,c,d)),e.addEventListener(c,d)):(o.push(e.off.bind(e,c,d)),e.on(c,d)),a)};return a}function kn(A){let e=Xh.get(A);e&&(e.forEach(o=>o()),Xh.delete(A))}var sn=new class{constructor(){Y(this,"_roomIdMap",new Map),Y(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:qd,env:jB.QCLOUD,browserVersion:nQ.name+nQ.version,ua:navigator.userAgent})}setConfig(A){let{sdkAppId:e,env:o,userId:a,roomId:c}=A;e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=o,this._configs.userId=a,this._roomIdMap.set(a,String(c))}logSuccessEvent(A){Op||!QA.isAbleToUpload||this._configs.env===jB.QCLOUD&&this.uploadEventToKibana(Qo(mi({},A),{result:"success"}))}logFailedEvent(A){if(Op||!QA.isAbleToUpload)return;let{eventType:e,code:o,error:a,userId:c}=A,d={roomId:this._roomIdMap.get(c||this._configs.userId),userId:c,eventType:e,result:"failed",code:o||a?.extraCode||a?.code||dt.UNKNOWN};this._configs.env===jB.QCLOUD&&this.uploadEventToKibana(Qo(mi({},d),{error:a}))}uploadEventToKibana(A){let e="stat-".concat(A.eventType,"-").concat(A.result);(A.eventType==="delta-join"||A.eventType==="delta-leave"||A.eventType==="delta-publish")&&(e="".concat(A.eventType,":").concat(A.delta)),this.uploadEvent({log:e,userId:A.userId}),A.result==="failed"&&(e="stat-".concat(A.eventType,"-").concat(A.result,"-").concat(A.code),this.uploadEvent({log:e,userId:A.userId,error:A.error}))}uploadEvent(A){let{log:e,userId:o,error:a}=A,c={timestamp:_x(),sdkAppId:this._configs.sdkAppId,userId:o||this._configs.userId,version:qd,log:e};a&&(c.errorInfo=a.message,a.stack&&(c.errorInfo+=` -`.concat(a.stack)));let d=_A.enable?AQ(c,2002,Number(this._configs.sdkAppId)):JSON.stringify(c);this.sendRequest(Hf(this._configs.sdkAppId,bI.LOG),d)}sendRequest(A,e){setTimeout(()=>eQ({url:A,body:e,priority:"low"}).catch(()=>{}),2e3)}},PC=new WeakMap;function $h(A){let{settings:e={retries:5,timeout:2e3},onError:o,onRetrying:a,onRetryFailed:c}=A;return function(d,C,y){let S=gM({retryFunction:y.value,settings:e,onError(k){let{error:V,retry:J,reject:gA,retryFuncArgs:CA}=k;var MA;o?o.call(this,V,()=>{var $A;($A=PC.get(d))!=null&&$A.has(C)?J():gA(V)},gA,CA):(MA=PC.get(d))!=null&&MA.has(C)?J():gA(V)},onRetrying(k,V){var J;Np(a)&&a.call(this,k,V),(J=PC.get(d))!=null&&J.has(C)&&(PC.get(d).get(C).stopRetry=V)},onRetryFailed:c});return y.value=function(){let k=PC.get(d);for(var V=arguments.length,J=new Array(V),gA=0;gA{var CA;return(CA=PC.get(d))==null?void 0:CA.delete(C)})},y}}function n_(A){let{fnName:e,callback:o,validateArgs:a=!0}=A;return function(c,d,C){let y=C.value;return C.value=function(){for(var S,k,V=arguments.length,J=new Array(V),gA=0;gAYe===Be)){$A=!1;break}}$A&&(o&&o.apply(this,J),CA&&CA(),(k=PC.get(c))==null||k.delete(e))}return y.apply(this,J)},C}}var xC=class extends Zs{constructor(A,e){super(A.id,"".concat(e,"-player")),this.options=A,this.kind=e,Y(this,"id"),Y(this,"element",null),Y(this,"track"),Y(this,"url"),Y(this,"attr"),Y(this,"mode"),Y(this,"muted"),Y(this,"_log"),Y(this,"isPausedByUserCall",!1),Y(this,"_pausedRetryCount"),Y(this,"_isElementPlayingFired",!1),Y(this,"_interval"),Y(this,"_delayDestroyTimeoutId",0),Y(this,"_playSuccessResolve"),Y(this,"_isReplayByRecreateMediaStreamCalled",!1),Y(this,"isPlayCalled",!1),Y(this,"isInAutoPlayFailedState",!1),Y(this,"isBindAutoPlayEvent",!1),this.id=A.id,this._log=A.log,this.track=A.track,this.muted=A.muted,this._pausedRetryCount=vp,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(e,"-player ").concat(this.id))}get isPlaying(){var A;return this._state==="PLAYING"&&((A=this.element)==null?void 0:A.paused)===!1}get isPaused(){var A;return this._state==="PAUSED"||((A=this.element)==null?void 0:A.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(A){this.attr=A}setUrl(A){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),A!==this.url&&(this.url=A,A!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=A))}play(){return KA(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((A,e)=>{this._playSuccessResolve=A,this.element.play().then(A,e)})}catch(A){let e=Xo({key:Mo.PLAY_FAILED,data:{media:this.kind,error:A}});if(this._log.warn(A),e.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ai({code:dt.PLAY_NOT_ALLOWED,message:e})}})}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var e;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),A>0&&!Fp?this._delayDestroyTimeoutId||((e=this.element)==null||e.remove(),this._log.info("destroy element after 3 * ".concat(A)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*A)):this.destroyElement(),this.handleStopped(YA.ENDED),this._interval>0&&Gr.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var A;(A=this.element)==null||A.pause()}resume(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(A)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():f2?this.replay():this.play().catch(()=>{})}setMuted(A){this.element&&(this.element.muted=A),this.muted=A}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let A=this.handleElementEvent.bind(this);return rd(this.element,this.element).add(YA.PLAYING,A).add(YA.ENDED,A).add(YA.PAUSE,A).add(YA.ERROR,A).add(YA.LOADSTART,A).add(YA.LOADEDDATA,A).add(YA.LOADEDMETADATA,A)}}bindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(A){let e=this.handleTrackEvent.bind(this);jk?.create(A,A).add(YA.ENDED,e).add(YA.MUTE,e).add(YA.UNMUTE,e),A.readyState===YA.ENDED&&this.handleTrackEvent({type:YA.ENDED}),A.muted&&this.handleTrackEvent({type:YA.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),F.on(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;A&&kn(A)}unbindEvents(){this.element&&kn(this.element),this.unbindTrackEvents(),F.off(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(A){switch(A.type){case YA.PLAYING:fi()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(YA.PLAYING),this._interval&&(Gr.clearTask(this._interval),this._interval=-1);break;case YA.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(YA.ENDED);break;case YA.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(YA.PAUSE);break;case YA.ERROR:if(this.element&&this.element.error){this.handlePaused(YA.ERROR);let{code:e,message:o}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(o," userAgent: ").concat(navigator.userAgent)),sn.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Ja.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),Ik||lk?this.emit(fo.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case YA.LOADEDDATA:this.kind===YA.VIDEO&&this.emit(fo.LOADED_DATA);break;case YA.LOADEDMETADATA:this.kind===YA.VIDEO&&this.emit(fo.LOADED_META_DATA);break;case YA.LOADSTART:this.emit(fo.LOAD_START)}}replayByRecreateMediaStream(A){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),sn.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),ii.addSuccessEvent({key:this.kind===YA.AUDIO?506700:516700})}).catch(()=>{var e;this._log.error("replayByRecreateMediaStream failed"),sn.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),ii.addFailedEvent({key:this.kind===YA.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),this.emit(fo.ERROR,A)})}doReplayByRecreateMediaStream(A){return this._log.warn("delay ".concat(A,"ms to recreate mediaStream")),new Promise((e,o)=>{LC(A).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var a,c,d;this._log.warn("element onerror ".concat((c=(a=this.element)==null?void 0:a.error)==null?void 0:c.code," fired after recreated mediaStream")),o((d=this.element)==null?void 0:d.error)}),LC(5e3).then(()=>{var a,c;(!this.isPlaying||(a=this.element)!=null&&a.error)&&o((c=this.element)==null?void 0:c.error),e()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(A){return KA(this,null,function*(){let e=A.type;switch(this.options.enableLogTrackState&&this._log[e===YA.UNMUTE?"info":"warn"]("track ".concat(e)),e){case YA.ENDED:this.handleStopped(YA.ENDED);break;case YA.MUTE:this.handlePaused(YA.MUTE);break;case YA.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(YA.UNMUTE))}})}handlePlaying(A){var e;return this._log.debug("handlePlaying",A),(e=this._playSuccessResolve)==null||e.call(this,A),A}handlePaused(A){return this._log.debug("handlePaused",A),A}handleStopped(A){return this._log.debug("handleStopped",A),A}getElement(){return this.element}};Y(xC,"PlayerEvent",fo),Ci([$h({settings:{retries:2,timeout:0},onError(A,e,o,a){a[0]=(a[0]||1e3)+1e3,e()}})],xC.prototype,"doReplayByRecreateMediaStream"),Ci([lc([],"PLAYING",{sync:!0,success(A){this.emit(fo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:A})}})],xC.prototype,"handlePlaying"),Ci([lc("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(A){this.emit(fo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:A})}})],xC.prototype,"handlePaused"),Ci([lc([],"STOPPED",{sync:!0,success(A){this.emit(fo.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:A})}})],xC.prototype,"handleStopped");var AB="trtc_autoplay",Wk="".concat(AB,"_mask"),OM="".concat(AB,"_wrapper"),PM="".concat(AB,"_header"),xM="".concat(AB,"_content"),r_="".concat(AB,"_action_wrapper"),AA="".concat(AB,"_question"),Z="".concat(AB,"_collapse"),hA="".concat(AB,"_action_confirm"),bA="".concat(AB,"_detail"),Ie="#2473E8",De="dialog",Re="".concat(De,"-show"),Le="".concat(De,"-1"),st="".concat(De,"-2"),He=!1,kt=!1,fi=()=>kt,wi="".concat(qh,"/").concat(Wd()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),Ds="
").concat(Wd()?"其他方案?":"Any other solution?",""),Tn="".concat(Wd()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(Ds):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(Ds)),oa=class{constructor(){if(Y(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Y(this,"_dialogNode",null),Y(this,"_bodyPosition",""),Y(this,"_showDetail",!1),Y(this,"_isCollapseClicked",!1),Y(this,"_isQuestionClicked",!1),Wd()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!He){let A=document.createElement("style");A.innerHTML=".".concat(Wk,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(Wk," div:not(.").concat(r_,"){display:block !important;}.").concat(OM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(OM," a{color:").concat(Ie,";}.").concat(PM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(xM,"{margin:8px 0;}.").concat(r_,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Z,"{margin-right:auto;cursor:pointer}.").concat(AA,"{height:100%;line-height:16px;cursor:pointer;}.").concat(hA,"{margin-left:8px;color:#fff;background:").concat(Ie,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(hA,":hover{opacity:0.9;}.").concat(Z,",.").concat(hA,",.").concat(xM,",.").concat(AA,"{font-size:14px;}@media screen and (max-width:750px){.").concat(OM,"{width:80vw;}}"),document.head.appendChild(A),He=!0}this.addDiaLog()}createDiaLog(){let A=document.createElement("template");A.innerHTML='
").concat(location.host,"
").concat(this.content,"
").trim();let e=document.createElement("button");e.className=hA,e.innerText=Wd()?"恢复播放":"Resume",e.onclick=this.onConfirm.bind(this);let o=document.createElement("div");o.className=AA,o.innerHTML=` + `],{type:"application/javascript"}))),hE.sharedWorker.onmessage=o=>{var a;if(o.data.type==="tick"){let l=hE.workerTasks.get(o.data.taskId);l&&(hE.isBreakLoop(l)?((a=hE.sharedWorker)==null||a.postMessage({type:"stop",taskId:l.taskID}),hE.workerTasks.delete(l.taskID)):(l.callback(),l.loopCount+=1))}}),hE.workerTasks.set(e.taskID,e),hE.sharedWorker.postMessage({taskId:e.taskID,delay:e.delay,type:"start"})}static timeout(e){let o=()=>{if(e.callback(),e.loopCount+=1,!hE.isBreakLoop(e))return e.timeoutID=setTimeout(o,e.delay)};return e.timeoutID=setTimeout(o,e.delay)}static ric(e){let o,a=ko(),l=()=>{if(o=ko()-a,o>=e.delay&&(a=ko()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),!hE.isBreakLoop(e))return e.ricID=$k(l,{timeout:e.delay})};return e.ricID=$k(l,{timeout:e.delay})}static raf(e){let o,a=ko(),l=()=>document.hidden&&e.backgroundTask?(o=ko()-a,a=ko(),e.callback(),e.loopCount+=1,hE.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(l,e.delay-Math.floor(o%e.delay))):(o=ko()-a,o>=e.delay&&(a=ko()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),hE.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(l));if(e.rafID=requestAnimationFrame(l),e.backgroundTask){let d=()=>{if(document.hidden){let h=ko()-a;h>=e.delay?l():e.timeoutID=setTimeout(l,e.delay-h)}};document.addEventListener("visibilitychange",d),e.onVisibilitychange=d,document.hidden&&d()}return e.taskID}static hasTask(e){return this.taskMap.has(e)}static clearTask(e){if(!this.taskMap.has(e))return!0;let{intervalID:o,timeoutID:a,rafID:l,ricID:d,onVisibilitychange:h}=this.taskMap.get(e);return o&&clearInterval(o),a&&clearTimeout(a),l&&$p&&$p(l),d&&hl(d),h&&document.removeEventListener("visibilitychange",h),this.taskMap.delete(e),!0}static isBreakLoop(e){return!this.hasTask(e.taskID)||e.count!==0&&e.loopCount>=e.count&&(this.clearTask(e.taskID),!0)}};Y(yy,"taskMap",new Map),Y(yy,"currentTaskID",1),Y(yy,"sharedWorker",null),Y(yy,"workerTasks",new Map);var Gr=yy,yo={LOAD_START:YA.LOADSTART,LOADED_DATA:YA.LOADEDDATA,LOADED_META_DATA:YA.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:YA.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:YA.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:YA.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change",FIRST_FRAME_RENDER:"first-frame-render"},AL={};jh(AL,{create:()=>nd,remove:()=>Ln});var eB=new WeakMap;function nd(A,e){eB.has(A)||eB.set(A,[]);let o=eB.get(A),a={add:(l,d)=>("addEventListener"in e?(o.push(e.removeEventListener.bind(e,l,d)),e.addEventListener(l,d)):(o.push(e.off.bind(e,l,d)),e.on(l,d)),a)};return a}function Ln(A){let e=eB.get(A);e&&(e.forEach(o=>o()),eB.delete(A))}var sn=new class{constructor(){Y(this,"_roomIdMap",new Map),Y(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:qd,env:ZB.QCLOUD,browserVersion:gQ.name+gQ.version,ua:navigator.userAgent})}setConfig(A){let{sdkAppId:e,env:o,userId:a,roomId:l}=A;e!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(e)),this._configs.env=o,this._configs.userId=a,this._roomIdMap.set(a,String(l))}logSuccessEvent(A){Yp||!pA.isAbleToUpload||this._configs.env===ZB.QCLOUD&&this.uploadEventToKibana(po(fi({},A),{result:"success"}))}logFailedEvent(A){if(Yp||!pA.isAbleToUpload)return;let{eventType:e,code:o,error:a,userId:l}=A,d={roomId:this._roomIdMap.get(l||this._configs.userId),userId:l,eventType:e,result:"failed",code:o||a?.extraCode||a?.code||Ct.UNKNOWN};this._configs.env===ZB.QCLOUD&&this.uploadEventToKibana(po(fi({},d),{error:a}))}uploadEventToKibana(A){let e="stat-".concat(A.eventType,"-").concat(A.result);(A.eventType==="delta-join"||A.eventType==="delta-leave"||A.eventType==="delta-publish")&&(e="".concat(A.eventType,":").concat(A.delta)),this.uploadEvent({log:e,userId:A.userId}),A.result==="failed"&&(e="stat-".concat(A.eventType,"-").concat(A.result,"-").concat(A.code),this.uploadEvent({log:e,userId:A.userId,error:A.error}))}uploadEvent(A){let{log:e,userId:o,error:a}=A,l={timestamp:Px(),sdkAppId:this._configs.sdkAppId,userId:o||this._configs.userId,version:qd,log:e};a&&(l.errorInfo=a.message,a.stack&&(l.errorInfo+=` +`.concat(a.stack)));let d=TA.enable?iQ(l,2002,Number(this._configs.sdkAppId)):JSON.stringify(l);this.sendRequest(jf(this._configs.sdkAppId,kI.LOG),d)}sendRequest(A,e){setTimeout(()=>oQ({url:A,body:e,priority:"low"}).catch(()=>{}),2e3)}},VC=new WeakMap;function tB(A){let{settings:e={retries:5,timeout:2e3},onError:o,onRetrying:a,onRetryFailed:l}=A;return function(d,h,y){let S=IM({retryFunction:y.value,settings:e,onError(k){let{error:V,retry:J,reject:cA,retryFuncArgs:CA}=k;var MA;o?o.call(this,V,()=>{var ie;(ie=VC.get(d))!=null&&ie.has(h)?J():cA(V)},cA,CA):(MA=VC.get(d))!=null&&MA.has(h)?J():cA(V)},onRetrying(k,V){var J;kp(a)&&a.call(this,k,V),(J=VC.get(d))!=null&&J.has(h)&&(VC.get(d).get(h).stopRetry=V)},onRetryFailed:l});return y.value=function(){let k=VC.get(d);for(var V=arguments.length,J=new Array(V),cA=0;cA{var CA;return(CA=VC.get(d))==null?void 0:CA.delete(h)})},y}}function g_(A){let{fnName:e,callback:o,validateArgs:a=!0}=A;return function(l,d,h){let y=h.value;return h.value=function(){for(var S,k,V=arguments.length,J=new Array(V),cA=0;cAqe===pe)){ie=!1;break}}ie&&(o&&o.apply(this,J),CA&&CA(),(k=VC.get(l))==null||k.delete(e))}return y.apply(this,J)},h}}var JC=class extends Zs{constructor(A,e){super(A.id,"".concat(e,"-player")),this.options=A,this.kind=e,Y(this,"id"),Y(this,"element",null),Y(this,"track"),Y(this,"url"),Y(this,"attr"),Y(this,"mode"),Y(this,"muted"),Y(this,"_log"),Y(this,"isPausedByUserCall",!1),Y(this,"_pausedRetryCount"),Y(this,"_isElementPlayingFired",!1),Y(this,"_interval"),Y(this,"_delayDestroyTimeoutId",0),Y(this,"_playSuccessResolve"),Y(this,"_isReplayByRecreateMediaStreamCalled",!1),Y(this,"isPlayCalled",!1),Y(this,"isInAutoPlayFailedState",!1),Y(this,"isBindAutoPlayEvent",!1),this.id=A.id,this._log=A.log,this.track=A.track,this.muted=A.muted,this._pausedRetryCount=_p,this._state="STOPPED",this.bindTrackEvents(),this._log.info("create ".concat(e,"-player ").concat(this.id))}get isPlaying(){var A;return this._state==="PLAYING"&&((A=this.element)==null?void 0:A.paused)===!1}get isPaused(){var A;return this._state==="PAUSED"||((A=this.element)==null?void 0:A.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(A){this.attr=A}setUrl(A){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),A!==this.url&&(this.url=A,A!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=A))}play(){return WA(this,null,function*(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),yield new Promise((A,e)=>{this._playSuccessResolve=A,this.element.play().then(A,e)})}catch(A){let e=Xo({key:vo.PLAY_FAILED,data:{media:this.kind,error:A}});if(this._log.warn(A),e.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new gi({code:Ct.PLAY_NOT_ALLOWED,message:e})}})}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var e;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),A>0&&!xp?this._delayDestroyTimeoutId||((e=this.element)==null||e.remove(),this._log.info("destroy element after 3 * ".concat(A)),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*A)):this.destroyElement(),this.handleStopped(YA.ENDED),this._interval>0&&Gr.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var A;(A=this.element)==null||A.pause()}resume(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPausedByUserCall=!1,this.doResume(A)}doResume(){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():N2?this.replay():this.play().catch(()=>{})}setMuted(A){this.element&&(this.element.muted=A),this.muted=A}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){let A=this.handleElementEvent.bind(this);return nd(this.element,this.element).add(YA.PLAYING,A).add(YA.ENDED,A).add(YA.PAUSE,A).add(YA.ERROR,A).add(YA.LOADSTART,A).add(YA.LOADEDDATA,A).add(YA.LOADEDMETADATA,A)}}bindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(A){let e=this.handleTrackEvent.bind(this);AL?.create(A,A).add(YA.ENDED,e).add(YA.MUTE,e).add(YA.UNMUTE,e),A.readyState===YA.ENDED&&this.handleTrackEvent({type:YA.ENDED}),A.muted&&this.handleTrackEvent({type:YA.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),F.on(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;A&&Ln(A)}unbindEvents(){this.element&&Ln(this.element),this.unbindTrackEvents(),F.off(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(A){switch(A.type){case YA.PLAYING:yi()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(YA.PLAYING),this._interval&&(Gr.clearTask(this._interval),this._interval=-1);break;case YA.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(YA.ENDED);break;case YA.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(YA.PAUSE);break;case YA.ERROR:if(this.element&&this.element.error){this.handlePaused(YA.ERROR);let{code:e,message:o}=this.element.error;this._log.error("".concat(this.kind," ").concat(this._log.isLocal?"local":"remote"," MediaError code: ").concat(e," message: ").concat(o," userAgent: ").concat(navigator.userAgent)),sn.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Ja.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),Bk||hk?this.emit(yo.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case YA.LOADEDDATA:this.kind===YA.VIDEO&&this.emit(yo.LOADED_DATA);break;case YA.LOADEDMETADATA:this.kind===YA.VIDEO&&this.emit(yo.LOADED_META_DATA);break;case YA.LOADSTART:this.emit(yo.LOAD_START)}}replayByRecreateMediaStream(A){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),sn.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),si.addSuccessEvent({key:this.kind===YA.AUDIO?506700:516700})}).catch(()=>{var e;this._log.error("replayByRecreateMediaStream failed"),sn.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),si.addFailedEvent({key:this.kind===YA.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),this.emit(yo.ERROR,A)})}doReplayByRecreateMediaStream(A){return this._log.warn("delay ".concat(A,"ms to recreate mediaStream")),new Promise((e,o)=>{OC(A).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var a,l,d;this._log.warn("element onerror ".concat((l=(a=this.element)==null?void 0:a.error)==null?void 0:l.code," fired after recreated mediaStream")),o((d=this.element)==null?void 0:d.error)}),OC(5e3).then(()=>{var a,l;(!this.isPlaying||(a=this.element)!=null&&a.error)&&o((l=this.element)==null?void 0:l.error),e()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}handleTrackEvent(A){return WA(this,null,function*(){let e=A.type;switch(this.options.enableLogTrackState&&this._log[e===YA.UNMUTE?"info":"warn"]("track ".concat(e)),e){case YA.ENDED:this.handleStopped(YA.ENDED);break;case YA.MUTE:this.handlePaused(YA.MUTE);break;case YA.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),yield this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(YA.UNMUTE))}})}handlePlaying(A){var e;return this._log.debug("handlePlaying",A),(e=this._playSuccessResolve)==null||e.call(this,A),A}handlePaused(A){return this._log.debug("handlePaused",A),A}handleStopped(A){return this._log.debug("handleStopped",A),A}getElement(){return this.element}};Y(JC,"PlayerEvent",yo),hi([tB({settings:{retries:2,timeout:0},onError(A,e,o,a){a[0]=(a[0]||1e3)+1e3,e()}})],JC.prototype,"doReplayByRecreateMediaStream"),hi([lc([],"PLAYING",{sync:!0,success(A){this.emit(yo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:A})}})],JC.prototype,"handlePlaying"),hi([lc("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(A){this.emit(yo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:A})}})],JC.prototype,"handlePaused"),hi([lc([],"STOPPED",{sync:!0,success(A){this.emit(yo.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:A})}})],JC.prototype,"handleStopped");var iB="trtc_autoplay",eL="".concat(iB,"_mask"),YM="".concat(iB,"_wrapper"),VM="".concat(iB,"_header"),JM="".concat(iB,"_content"),c_="".concat(iB,"_action_wrapper"),AA="".concat(iB,"_question"),Z="".concat(iB,"_collapse"),hA="".concat(iB,"_action_confirm"),bA="".concat(iB,"_detail"),Ce="#2473E8",Me="dialog",_e="".concat(Me,"-show"),Fe="".concat(Me,"-1"),nt="".concat(Me,"-2"),je=!1,bt=!1,yi=()=>bt,Ti="".concat(Wh,"/").concat(Wd()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),Ss="
").concat(Wd()?"其他方案?":"Any other solution?",""),Tn="".concat(Wd()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(Ss):"Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ".concat(Ss)),sa=class{constructor(){if(Y(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Y(this,"_dialogNode",null),Y(this,"_bodyPosition",""),Y(this,"_showDetail",!1),Y(this,"_isCollapseClicked",!1),Y(this,"_isQuestionClicked",!1),Wd()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!je){let A=document.createElement("style");A.innerHTML=".".concat(eL,"{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.").concat(eL," div:not(.").concat(c_,"){display:block !important;}.").concat(YM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(YM," a{color:").concat(Ce,";}.").concat(VM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(JM,"{margin:8px 0;}.").concat(c_,"{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.").concat(Z,"{margin-right:auto;cursor:pointer}.").concat(AA,"{height:100%;line-height:16px;cursor:pointer;}.").concat(hA,"{margin-left:8px;color:#fff;background:").concat(Ce,";padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.").concat(hA,":hover{opacity:0.9;}.").concat(Z,",.").concat(hA,",.").concat(JM,",.").concat(AA,"{font-size:14px;}@media screen and (max-width:750px){.").concat(YM,"{width:80vw;}}"),document.head.appendChild(A),je=!0}this.addDiaLog()}createDiaLog(){let A=document.createElement("template");A.innerHTML='
").concat(location.host,"
").concat(this.content,"
").trim();let e=document.createElement("button");e.className=hA,e.innerText=Wd()?"恢复播放":"Resume",e.onclick=this.onConfirm.bind(this);let o=document.createElement("div");o.className=AA,o.innerHTML=` - `,o.onclick=this.onQuestionClick.bind(this);let a=document.createElement("div");a.className=Z,a.innerText="".concat(Wd()?"详情 >":"Detail >"),a.onclick=this.onCollapseClick.bind(this);let c=A.content.firstChild,d=c.querySelector(".".concat(r_));return d.appendChild(a),d.appendChild(o),d.appendChild(e),c}addDiaLog(){fi()||(kt=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(OM)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",QA.info("show autoplay dialog"),sn.uploadEvent({log:Re}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,kt=!1),Oc=null}onConfirm(){QA.warn("confirm clicked, try resume stream"),F.emit(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(bA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||sn.uploadEvent({log:Le}),this._isCollapseClicked=!0}onQuestionClick(){window.open(wi,"_blank"),this._isQuestionClicked||sn.uploadEvent({log:st}),this._isQuestionClicked=!0}},Oc=null;function YC(){Oc||(Oc=new oa)}var di,vo=class G9 extends xC{constructor(e){super(e,YA.VIDEO),Y(this,"stat",{}),Y(this,"_calculateTimeout",-1),Y(this,"viewMirror",!1),Y(this,"objectFit","cover"),Y(this,"container"),Y(this,"canvas"),Y(this,"shouldRenderAlpha",!1),Y(this,"_preSize",{width:0,height:0}),Y(this,"posterImg"),Y(this,"pipWindow"),Y(this,"enterPIPPromise"),Y(this,"_originContainerPosition"),Y(this,"_isResettingSrcObject",!1),Y(this,"_wrapper",null),Y(this,"_useWrapper",!1),Y(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,Je(e.viewMirror)||(this.viewMirror=e.viewMirror),Je(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!(this._state!=="PLAYING"||this.element&&this.element.paused)&&((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){let e=document.createElement(YA.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id","video_".concat(this.id)),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,Ha&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let a=e.videoWidth||0,c=e.videoHeight||0;this._log.info("first frame render: ".concat(a,"x").concat(c)),this.emit(fo.FIRST_FRAME_RENDER,{width:a,height:c})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(o):e.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let e=this._useWrapper?"grid-area:1/1;width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";"):"width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setLiveMode(e){if(this._useWrapper!==e&&(this._useWrapper=e,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(e){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;let o=this._wrapper,a=this.container;this.container=e,this._pausedRetryCount=vp,this.track&&this.elementToRender&&this._appendToWrapper(),o&&a&&a!==this.container&&o.isConnected&&o.children.length===0&&o.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let e=this.container.querySelector("[data-trtc-video-wrapper]");return e||(e=document.createElement("div"),e.setAttribute("data-trtc-video-wrapper","true"),e.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(e)),this._wrapper=e,e}_appendToWrapper(e){let o=e??this.elementToRender;if(this.container&&o)if(this._useWrapper){let a=this._getOrCreateWrapper();a.insertBefore(o,a.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(YA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(YA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(YA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(YA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var o;return e.type===YA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(fo.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(fo.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(fo.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var o,a,c,d,C,y;if(this.mode===2)return;super.handleElementEvent(e);let S=e.type,k=this.isPictureInPicture(),V=this.isFullscreen(),J=e.isTrusted&&(k&&Bg||V);if(S===YA.PLAYING&&J&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(V?"fullscreen":"pip")),this.emit(fo.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),S===YA.PAUSE&&(J&&(this._log.warn("user pause in ".concat(V?"fullscreen":"pip")),this.emit(fo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),LC(500).then(()=>{var gA;(gA=this.container)!=null&&gA.isConnected&&(this._pausedRetryCount=vp,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!fi()&&!this.isPausedByUserCall&&!J&&(this._log.info("[".concat(vp-this._pausedRetryCount+1,"/").concat(vp,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),eg&&!J&&(this._interval=Gr.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let gA=this.element.style.transform;S===YA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=gA.replace("scaleX(-1)",""):S===YA.LEAVE_PICTURE_IN_PICTURE&&!gA.includes("scaleX")&&(this.element.style.transform="".concat(gA," scaleX(-1)"))}S===YA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info("video size changed to ".concat((c=this.element)==null?void 0:c.videoWidth,"x").concat((d=this.element)==null?void 0:d.videoHeight)),this._preSize.height=((C=this.element)==null?void 0:C.videoHeight)||0,this._preSize.width=((y=this.element)==null?void 0:y.videoWidth)||0,this.emit(fo.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),S===YA.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(fo.LEAVE_PICTURE_IN_PICTURE)),S===YA.ENTER_PICTURE_IN_PICTURE&&this.emit(fo.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Ha&&sy&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var a,c;this.canvas!==e&&((a=this.canvas)==null||a.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?o:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((c=this.element)==null||c.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(e,o){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new Promise(a=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),e===""?this.element.removeAttribute("poster"):this.element.poster=e,!o||!Bg&&!er))return a();if(e==="")return this.removePosterImg(),a();if(this.posterImg)return a();let c=document.createElement("img");c.src=e;let d=window.getComputedStyle(this.element),C=d.objectFit||this.objectFit,y=1;if(this._useWrapper){let S=parseInt(d.zIndex,10);isNaN(S)||(y=S+1)}c.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(y,";width:100%;height:100%;object-fit:").concat(C,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(C,";"),c.onload=()=>KA(this,null,function*(){try{c.decode&&(yield c.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=c;let S=this._useWrapper?this._wrapper:this.container;S?.appendChild(c),cM()&&Zd<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(S){this._log.warn("decode poster image error",S)}return a()}),c.onerror=()=>(this._log.warn("load poster image error"),a())})}removePosterImg(){this.posterImg&&(cM()&&Zd<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!Je(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!((e=this.element)==null||!e.getAttribute("poster"))}pause(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return KA(this,null,function*(){NI(G9.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(sy||e&&(er||Bg))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(e).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&sy&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(a=>{}),this.isFullscreen()&&this.exitFullscreen().catch(a=>{}),this.element&&(this.element.removeEventListener(YA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(e),(o=this.canvas)==null||o.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(e){if(Je(e?.isLiveStream)||this.setLiveMode(e.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){let o=this._getOrCreateWrapper();this.elementToRender.parentElement!==o&&o.insertBefore(this.elementToRender,o.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(fo.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(jp()&&this.element&&this._calculateTimeout<0){let e=0,o=null,a=(c,d)=>{this.stat.width=d.width,this.stat.height=d.height,o&&(this.stat.fps=Math.round((d.presentedFrames-o.presentedFrames)/(c-e)*1e3)),e=c,o=d,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var C;return(C=this.element)==null?void 0:C.requestVideoFrameCallback(a)},2e3))};this.element.requestVideoFrameCallback(a)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return KA(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(eg&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(o){this._log.warn("exit pip failed before fullscreen:",o)}}try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return KA(this,null,function*(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return KA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return KA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return KA(this,null,function*(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield e.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(e){throw this._log.error("failed to enter pip:",e.name,e.message),e}})}exitPictureInPicture(){return KA(this,null,function*(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=vp,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(o){throw this._log.error("failed to exit pip:",o),o}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return KA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Vg(A,e){return KA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(e),QA.info("worklet addModule success")}catch(o){throw QA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?di=AudioContext:typeof webkitAudioContext<"u"?di=webkitAudioContext:typeof mozAudioContext<"u"&&(di=mozAudioContext);var Ln,Cu=1500,$d=-1,Zp=0,ad=-1,UI=!1,Y2=0,a_=-1,zk=-1;(function A(){try{if(Ln)return;(Ln=new di({sampleRate:48e3})).onstatechange=()=>{QA.info("context state: ".concat(Ln.state).concat(Ln.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),g_()},clearTimeout($d)}catch(e){QA.error("initAudioContext failed: ".concat(e," typeof AudioContextClass: ").concat(typeof di)),$d=setTimeout(A,1e3)}})();var g_=()=>{Ln.state==="suspended"?(Zp=ko(),ad===-1&&(ad=setTimeout(()=>{Ln.state==="suspended"&&(UI=!0,F.emit("155",{isSuspended:!0}))},Cu)),Zk(),document.addEventListener("click",g_)):Ln.state==="interrupted"?Zk():(Zp&&(ii.addNumber({key:507800,value:ko()-Zp,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Zp=0),ad!==-1&&(clearTimeout(ad),ad=-1,UI&&(UI=!1,F.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",g_),document.removeEventListener("click",g_))},_K=0,TK=-1;function Zk(){return new Promise((A,e)=>{if(Ln.state==="running")return A();Date.now()-_K<1e3?(clearTimeout(TK),TK=setTimeout(()=>{_K=Date.now(),Ln.resume().then(A,e)},1e3)):(clearTimeout(TK),_K=Date.now(),Ln.resume().then(A,e))}).catch(A=>{QA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",g_)})}document.addEventListener("click",g_);var FI=A=>Ln,OI=class{constructor(A){this.name=A,Y(this,"node"),Y(this,"node2"),Y(this,"pre",new Set),Y(this,"next",new Set),Y(this,"context"),Y(this,"connectedNodes",new Set),Y(this,"nextInputChannelMap",new Map),Y(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(A){this._channelCount=A,this.setChannelCount(this.node,A),this.setChannelCount(this.node2,A),this.next.forEach(e=>e.channelCount=A)}setChannelCount(A,e){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=e||this.channelCount||1)}setContext(A){this.context=A,this.node&&A.addMixWeight()}removeContext(){var A;this.node&&((A=this.context)==null||A.reduceMixWeight()),delete this.context}replaceNode(A){var e;if(A!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){QA.error(o)}}setNode(A,e){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),ii.addSuccessEvent({key:502701})}catch(a){QA.error(a),ii.addFailedEvent({key:502701,error:a})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),ii.addSuccessEvent({key:502702})}catch(e){QA.error(e),ii.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(e=>{let o=this.nextInputChannelMap.get(e);A._connect(e.node,o)||e.connectNext(A)})}_connect(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,e),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,e),A}},BeA=class extends OI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,Y(this,"dataArray",new Uint8Array(0))}setNode(A){A.fftSize=this.fftSize,this.dataArray=new Uint8Array(A.frequencyBinCount),super.setNode(A)}getByteTimeDomainData(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let A=this.getByteTimeDomainData(),e=0,o=0,a="M".concat(e,",").concat(o);for(let c=0;c0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=A,this.mixWeight-1==A+1>>1&&this.mixOnChange()}reduceMixWeight(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-A)}close(){this.inputs.forEach(A=>A.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},X4=new WeakMap;function V2(A){try{let e=X4.get(A);if(e)return e;let o=FI();if(A instanceof HTMLAudioElement)e=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;e=o.createMediaStreamSource(new MediaStream([A]))}return X4.set(A,e),e}catch(e){if(!(er&&e instanceof Error&&e.name==="NotSupportedError"))throw e;QA.warn(e)}}var J2=class sm{constructor(e){Y(this,"_volume",0),Y(this,"_volumeDb",0),Y(this,"_log"),Y(this,"_scriptProcessorNode",null),Y(this,"_audioWorkletNode",null),Y(this,"_interval",200),Y(this,"ready",this.preload());let{log:o}=e;this._log=o,F.on(nA.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-sm.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!sm.workletReady){let e='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(it+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';sm.workletReady=Vg(sm.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return sm.workletReady.then(()=>this.initAudioWorklet()).catch(e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(sm.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=o=>{sm.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!e&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){this._log.error("volumeMeter init audio worklet error: ".concat(e)),sn.logFailedEvent({userId:this._log.userId,eventType:Ja.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=FI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{sm.lastMessageTime=Date.now();let o=e.inputBuffer.getChannelData(0),a=0;for(let c=0;c>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},H2=$4,peA=gc(Kl(),1),e5=A=>e=>e.deviceId===A,NK=class{constructor(A,e){Y(this,"kind"),Y(this,"type"),Y(this,"devices",[]),this.kind=A,this.type=e}update(A,e){let o=A.filter(a=>a.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&Xk(this.devices[0])||e&&(o.forEach(a=>{if(a.deviceId&&!this.devices.find(e5(a.deviceId))){let c="".concat(this.kind).concat(this.type,"Added");QA.warn("".concat(c,": ").concat(JSON.stringify(a))),e.emit(c,a)}}),this.devices.forEach(a=>{if(a.deviceId&&!o.find(e5(a.deviceId))){let c="".concat(this.kind).concat(this.type,"Removed");QA.warn("".concat(c,": ").concat(JSON.stringify(a))),e.emit(c,a)}})),this.devices=o}hasDevice(A){return!!this.devices.find(e=>e.deviceId===A)}},meA=class extends peA.EventEmitter{constructor(){super(),Y(this,"audioInputs",new NK(YA.AUDIO,"Input")),Y(this,"videoInputs",new NK(YA.VIDEO,"Input")),Y(this,"audioOutputs",new NK(YA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Gr.run("interval",()=>{this.update()},{delay:1e4}))}init(){q2().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return KA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield q2(e);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=FI())==null?void 0:A.outputLatency)>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(a=>o.label.toLowerCase().includes(a)))||this.audioInputs.devices.some(o=>e.some(a=>o.label.toLowerCase().includes(a)))}},Pc=o0||i0?null:new meA;function Xk(A){return A.deviceId===A.groupId&&A.groupId===""}function q2(){return KA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(du()||!_k())return[];let e=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(e.forEach(a=>{Xk(a)&&(a.kind===YA.AUDIO_INPUT?o.audio=!0:a.kind===YA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let a;try{a=yield navigator.mediaDevices.getUserMedia(o),o.audio&&Zk()}catch(c){QA.debug("capture before getDevices failed: ",c)}e=yield navigator.mediaDevices.enumerateDevices(),a?.getTracks().forEach(c=>c.stop())}}return e.map((o,a)=>{let c={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(a)};return o.deviceId.length>0&&GK.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(c.getCapabilities=()=>o.getCapabilities()),c})}()})}function Xp(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Pc.update(A?1:0).then(e=>e.audioInputs.devices)}function $p(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Pc.update(A?2:0).then(e=>e.videoInputs.devices)}var t5=!1;function YM(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return KA(this,null,function*(){return(eg||Bg)&&(A=!1),Pc.update(A?1:0).then(e=>e.audioOutputs.devices)})}var GK=new Set;function i5(A,e){return KA(this,null,function*(){let o=(yield Xp()).find(a=>a.deviceId===ZS);return!e&&o?.groupId===A||o?.groupId===A&&o.label===e})}var K2,feA=class extends z4{constructor(A){super(),this.log=A,Y(this,"volumeMeter"),Y(this,"volumeMeterAfter3A"),Y(this,"volumeDestination"),Y(this,"analyser",new BeA),this.volumeMeter=new A5({log:this.log}),this.volumeMeterAfter3A=new A5({log:this.log}),this.volumeDestination=new OI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},bK=class b9 extends xC{constructor(e){super(e,YA.AUDIO),Y(this,"_outputDeviceId"),Y(this,"_floatVolume",1),Y(this,"_destination"),Y(this,"pipeline"),Y(this,"volumeMeterMode","worklet"),Y(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new feA(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((kI==="15.2"||kI==="15.3"||kI==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=K2||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,this.setVolume(bn(e)?e/100:this._floatVolume),o===K2&&(K2=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(fo.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return KA(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e?.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(FI().createAnalyser()),function(){KA(this,null,function*(){try{t5||(t5=!0,QA.info("speakers:".concat((yield YM()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),ny(kI,"18.7",!0)&&this.bindAutoPlayEvent(),o}return NI(b9.prototype,this,"play").call(this)}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return KA(this,null,function*(){var o,a;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(a=(o=this.element).setSinkId)==null?void 0:a.call(o,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},yeA=class extends bK{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(fo.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},o5=class extends bK{constructor(A){super(A),Y(this,"_sourceElement"),Y(this,"_output",new OI),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(FI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var e,o,a;((o=(e=this.element)==null?void 0:e.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(fo.MEDIA_TRACK_CHANGED,A),A?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([A]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([A])),this.pipeline.source.channelCount=((a=A.getSettings())==null?void 0:a.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var e;let o=A<=1&&!cM();if(this._floatVolume!==A||!(o&&((e=this.element)==null?void 0:e.volume)===A||!o&&this.pipeline.volume===A))if(this._floatVolume=A,this.useDestination)this.pipeline.setVolume(A),this._log.info("set pipeline volume: ".concat(A));else if(o)this.element?(this._log.info("set element volume: ".concat(A)),this.element.volume=A):this._log.info("set element volume: no element");else{if(cM()){if(!this.enableVolumeControlInIOS)return;(function(){if(!eg||zk!==-1)return;let a=()=>{ko()-Y2<500||(Ln&&Ln.state==="running"&&Ln.currentTime===a_&&(QA.warn("context is fake running, auto resume"),Ln.suspend().catch(c=>{QA.warn("context suspend failed: ".concat(c))})),a_=Ln.currentTime,Y2=ko())};zk=setInterval(()=>{a()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})})()}if(er&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(A)),this.pipeline.setVolume(A),this.element&&!this._sourceElement&&(this._destination||(this._destination=FI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),kn(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(a=>{this.emit(fo.AUTOPLAY_FAILED,a)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let e=this._sourceElement||this.element;e&&Fp&&(K2=e),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},kK=class extends Zs{constructor(A){let{userId:e,sdkAppId:o,mediaType:a,room:c,PlayerClass:d=a===1?o5:vo}=A;var C;super(),Y(this,"id",PA()),Y(this,"userId",""),Y(this,"isRemote"),Y(this,"mediaType"),Y(this,"room"),Y(this,"user"),Y(this,"_log"),Y(this,"_inputTrack"),Y(this,"_outputTrack"),Y(this,"isPlayCalled"),Y(this,"container",null),Y(this,"player"),Y(this,"subVideoPlayerMap"),Y(this,"muted",!1),Y(this,"abortCtrl"),Y(this,"objectFit","cover"),Y(this,"mirror"),Y(this,"rotation"),Y(this,"isScreen",!1),Y(this,"manager"),Y(this,"trackSettings"),Y(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=a,this._log=QA.createLogger({parent:c?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(C=c||this.room)==null?void 0:C.userId,remoteUserId:this instanceof sL?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof sL}),this.player=new d({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:c?.enableVolumeControlInIOS}),this.player.on(fo.PLAYER_STATE_CHANGED,y=>{if(F.emit(nA.PLAYER_STATE_CHANGED,mi({track:this},y)),this.emit("player-state-changed",y),y.state==="PLAYING"&&this.room){let S=!0;for(let{remoteAudioTrack:k,remoteVideoTrack:V,remoteAuxiliaryTrack:J}of[...this.room.remotePublishedUserMap.values()])if(k.isAvailable&&!k.player.isPlaying||V.isAvailable&&!V.player.isPlaying||J.isAvailable&&!J.player.isPlaying){S=!1;break}S&&fi()&&Oc&&Oc.deleteDialog()}}),this.kind===YA.VIDEO&&(this.player.on(fo.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(fo.LOADED_DATA),F.emit(nA.VIDEO_LOADED_DATA,{track:this})}),this.player.on(fo.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(fo.LOADED_META_DATA)}),this.player.on(fo.MEDIA_TRACK_CHANGED,y=>{var S;(S=this.subVideoPlayerMap)==null||S.forEach(k=>k.setTrack(y))}),this.player.on(fo.RESIZE,y=>{this.emitFirstVideoFrameEvent(fo.RESIZE),this.emit("video-size-changed",mi({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},y))}),this.player.on(fo.FIRST_FRAME_RENDER,y=>{this.emit("first-frame-render",Qo(mi({},y),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(fo.ERROR,this.onPlayerError.bind(this)),this.player.on(fo.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||QA}get kind(){return this.mediaType===1?YA.AUDIO:YA.VIDEO}get isAudio(){return this.kind===YA.AUDIO}get strMediaType(){return this.mediaType===4?YA.VIDEO:this.mediaType===2?YA.SCREEN:YA.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}play(A,e){return KA(this,null,function*(){let o=wa(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(e))),e&&!Je(e.muted)&&this.setPlayerMute(e.muted),e&&!Je(e.objectFit)&&(this.objectFit=e.objectFit),void(this.player instanceof vo&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(wa(A)&&A.length>=1&&this.container&&A.includes(this.container)&&this.container.contains(this.player.elementToRender)?(A.splice(A.indexOf(this.container),1),A.unshift(this.container)):(this.container=o,this.player.setContainer(o))),wa(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),e))));if(e&&!Je(e.muted)?this.setPlayerMute(e.muted):(!this.isRemote||this.kind===YA.VIDEO)&&this.setPlayerMute(!0),e&&!Je(e.objectFit)&&(this.objectFit=e.objectFit),this.player instanceof vo&&(Je(e?.isLiveStream)||this.player.setLiveMode(e.isLiveStream),this.player.setObjectFit(this.objectFit),e&&!Je(e.poster)&&this.player.setPoster(e.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof vo&&this.player.setContainer(o)),F.emit(nA.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(e)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(e),wa(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),e))}catch(a){throw this.handleAutoPlayFailed(a),a}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,e){if(this.isScreen||this.kind!==YA.VIDEO||Je(A)||A===this.mirror)return;this.mirror=A;let o=this.player;e&&(o=e);let a=this.manager;if(Nr(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&a&&(a.mirror=!1));switch(this.mirror){case"view":a&&(a.mirror=!1),o.setViewMirror(!0);break;case"publish":a&&(a.mirror=!0),o.setViewMirror(!0);break;case"both":a&&(a.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,e){return KA(this,null,function*(){if(!this._outputTrack||this.kind===YA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((a,c)=>{var d;A.find(C=>c===C)||(a.stop(),(d=this.subVideoPlayerMap)==null||d.delete(c))});for(let[a,c]of A.entries()){let d=this.subVideoPlayerMap.get(c);d?e&&(Je(e.objectFit)||d.setObjectFit(e.objectFit)):this.subVideoPlayerMap.set(c,new vo({id:this.userId||this.id,track:this.playerMediaTrack,container:c,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(a+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let a of o)a.setViewMirror(this.player.mirror),yield a.play()})}setAudioOutput(A){return this.player.setSinkId(A)}setAudioVolume(A){this.player.setVolume(A)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var A;return((A=this.player)==null?void 0:A.getInternalAudioLevel())||0}stop(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(Xb(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return KA(this,null,function*(){var A;this.isPlayCalled&&(yield(A=this.player)==null?void 0:A.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(A){this.muted=A,this._inputTrack&&(this._inputTrack.enabled=!A),this._outputTrack&&(this._outputTrack.enabled=!A),this.emit(A?"mute":"unmute",this),F.emit(A?nA.TRACK_MUTED:nA.TRACK_UNMUTED,{track:this})}setPlayerMute(A){this.player.setMuted(A)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(A){rd(A,A).add(YA.MUTE,this.onTrackMuted).add(YA.UNMUTE,this.onTrackUnmuted).add(YA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===YA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){kn(A)}setInputMediaStreamTrack(A){var e;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(e=A.getSettings)==null?void 0:e.call(A),A.enabled=!this.muted,o&&this.uninstallTrackEvent(o),this.installTrackEvent(A),this.emit("input-media-track-changed",A||null,o||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(A)}setOutputMediaStreamTrack(A){var e;let o=this._outputTrack;this instanceof dQ&&_p(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(e=A.getSettings)==null?void 0:e.call(A).deviceId,A.label),this._outputTrack=A,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!A),this.emit("output-media-track-changed",A))}setMediaType(A){this.mediaType=A}updatePlayingState(A){var e,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(a=>this.handleAutoPlayFailed(a)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return Xb(this)&&this.isAudio&&(e=this.user)!=null&&e.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(Xb(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind)))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(A," ").concat(this.player.isStopped))}handleAutoPlayFailed(A){return KA(this,null,function*(){var e;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((kp||tQ)&&(yield LC(100),(e=this.player)!=null&&e.isPlaying))return;YC()}else document.addEventListener("click",o,!0);F.once(nA.LOCAL_TRACK_CAPTURE_SUCCESS,a=>{let{track:c}=a;c.kind==="audio"&&fi()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof vo?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var e,o,a;if(this.isFirstVideoFrameEmitted)return;let c=(e=this.mediaTrack)==null?void 0:e.getSettings(),d=c?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,C=c?.height||((a=this.player.element)==null?void 0:a.videoHeight)||0;A===fo.RESIZE&&!d&&!C||A===fo.LOADED_META_DATA&&!d&&!C||(A===fo.LOADED_DATA&&!d&&!C&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,$B(this.rotation)&&([d,C]=[C,d]),this.emit("first-video-frame",{width:d,height:C,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};Ci([lc([],Zs.INIT,{sync:!0})],kK.prototype,"_toInitState");var DeA=Object.prototype.hasOwnProperty,Am=function(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(lE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let e in A)if(DeA.call(A,e))return!1;return!0}return!1},SeA=gM({retryFunction:function(A){return KA(this,null,function*(){let e=function(d){return{audio:MeA(d),video:veA(d)}}(A);QA.info("getUserMedia with constraints: ".concat(JSON.stringify(e)));let o=[],a=[],c=["label","deviceId","groupId"];if(e.audio&&(o=yield Xp(),QA.info("microphones: ".concat(zd(o.map(d=>Qo(mi({},d),{groupId:d.groupId.substring(0,8)})),{keysToInclude:c})))),e.video&&(a=yield $p(),QA.info("cameras: ".concat(zd(a,{keysToInclude:c}))),!Nr(e.video)&&e.video.facingMode==="user"&&!e.video.deviceId)){let d=a.filter(C=>!C.label.includes("infrared")).find(C=>C.label.includes("facing front"));d&&(e.video.deviceId=d.deviceId,QA.info("exclude infrared camera: ".concat(JSON.stringify(e))))}try{let d=yield navigator.mediaDevices.getUserMedia(e);return k2&&d.getTracks().forEach(C=>{var y;let S=C.getCapabilities();QA.info("".concat(C.kind," capabilities: ").concat(zd(S,{keysToInclude:Gb}))),!Je(A.echoCancellation)&&((y=S.echoCancellation)==null?void 0:y.indexOf(A.echoCancellation))===-1&&QA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(S.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),e.audio&&Zk(),d}catch(d){let{message:C}=d;throw d.name==="NotFoundError"&&(A.video&&a&&a.length===0&&(C=Xo({key:Mo.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(C=Xo({key:Mo.MICROPHONE_NOT_FOUND}))),new ai({code:dt.INITIALIZE_FAILED,name:d.name,message:C,constraint:d.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:e,retry:o,reject:a,retryFuncArgs:c,retriedCount:d}=A,C=d+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(C===1?(c[0].video&&(c[0].maxResolution=!1,(!Bg||c[0].width*c[0].height<=2073600)&&c[0].frameRate&&(c[0].frameRate=c[0].frameRate>10?10:5)),c[0].retryWhenExactFailed&&c[0].useExactDeviceId&&(c[0].useExactDeviceId=!1)):C===2?c[0].useDeviceIdOnly=!0:C===3&&!c[0].useExactDeviceId&&(c[0].useTrueAsConstraint=!0),o()):a(e),c[0].microphoneId&&s5(c[0].microphoneId,!1),c[0].cameraId&&s5(c[0].cameraId,!0)},onRetrying:A=>{QA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{sn.logFailedEvent({eventType:Ja.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{sn.logSuccessEvent({eventType:Ja.GET_USER_MEDIA_RETRY}),sn.uploadEvent({log:"stat-".concat(Ja.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function s5(A,e){return KA(this,null,function*(){let o=(e?yield $p():yield Xp()).find(a=>a.deviceId===A);o&&Ra(o.getCapabilities)&&QA.warn(zd(o.getCapabilities(),{keysToInclude:Gb}))})}function MeA(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let e={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!Am(A.microphoneId)&&(e.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?e:(bn(A.channelCount)&&(e.channelCount=A.channelCount),(Nr(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(e.echoCancellation=A.echoCancellation),Nr(A.noiseSuppression)&&!A.noiseSuppression&&(e.noiseSuppression=!1),Nr(A.autoGainControl)&&!A.autoGainControl&&(e.autoGainControl=!1),!!Am(e)||e)}function veA(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:e=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!Am(o)?o:(A.width&&(o.width={ideal:A.width},e&&!er&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},e&&!er&&(o.height.max=A.height)),er&&iQ&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!Am(o)||o)}var ReA=SeA;function n5(A){return jr((e,o)=>function(){for(var a=arguments.length,c=new Array(a),d=0;dfunction(){for(var a=arguments.length,c=new Array(a),d=0;dfunction(){for(var a=arguments.length,c=new Array(a),d=0;d{let A=!1,e=document.visibilityState;return()=>{document.visibilityState!==e&&QA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{QA.info("visibility change: ".concat(document.visibilityState)),e=document.visibilityState}),A=!0)}})(),_eA=0,a5=class{constructor(A){Y(this,"log"),Y(this,"isRunning",!1),Y(this,"queue",[]);let e="fq".concat(++_eA);A&&(e+="|".concat(A)),this.log=QA.createLogger({id:e})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;let c=mi({},A),d=new Promise((C,y)=>{c.resolve=C,c.reject=y});return c.promise=d,e?this.length<=1?this.queue.push(c):(a=(o=this.lastQueueItem)==null?void 0:o.promise)==null||a.then(c.resolve,c.reject):this.queue.push(c),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),d}shift(){let A=this.queue.shift();return this.log.debug("shift ".concat(this.length),A?.funcName,A?.args),A}callNext(){if(this.isRunning||this.length===0)return;let{fn:A,args:e,context:o,resolve:a,reject:c,funcName:d}=this.queue[0];this.log.debug("callNext",this.length,d,e),this.isRunning=!0,A.apply(o,e).then(a,c).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},j2=new WeakMap,W2=new WeakMap;function $k(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(e,o,a){let c=a.value;return a.value=function(){let d=j2.get(this)||new a5;for(var C=arguments.length,y=new Array(C),S=0;SS.push(gA)),(y=W2.get(this))==null||y.forEach(gA=>gA?.queue.forEach(CA=>S.push(CA))),S.forEach(gA=>{gA.reject(new ai({code:dt.API_CALL_ABORTED,message:A}))}),j2.delete(this),W2.delete(this),c.apply(this,V)},a}}function py(A,e){return function(o,a,c){let d=c.value,C=y=>A(...y);return c.value=function(){for(var y=arguments.length,S=new Array(y),k=0;kfunction(){let c=A;try{for(var d=arguments.length,C=new Array(d),y=0;y(e?ii.addSuccessEvent({key:c,cost:ko()-k}):ii.addSuccessEvent({key:c}),V)).catch(V=>{throw ii.addFailedEvent({key:c,error:V}),V}):(ii.addSuccessEvent({key:c}),S)}catch(S){throw ii.addFailedEvent({key:c,error:S}),S}})}var c5={};function tg(){}Hh(c5,{Events:()=>Ic,Inspect:()=>yy,LastSink:()=>z2,Sink:()=>Os,Subscribe:()=>Z2,TimeoutError:()=>u5,audit:()=>dtA,bindCallback:()=>XeA,bindNodeCallback:()=>$eA,buffer:()=>PeA,bufferCount:()=>OeA,bufferTime:()=>FtA,call:()=>l5,catchError:()=>N5,combineLatest:()=>C5,concat:()=>beA,concatMap:()=>RtA,concatMapTo:()=>wtA,count:()=>ttA,create:()=>lr,debounce:()=>htA,debounceTime:()=>BtA,defer:()=>h5,delay:()=>OtA,deliver:()=>Ps,dispose:()=>LK,elementAt:()=>QtA,empty:()=>xK,every:()=>DtA,exhaustMap:()=>btA,exhaustMapTo:()=>ktA,expand:()=>xtA,filter:()=>JM,find:()=>ptA,findIndex:()=>mtA,first:()=>ftA,fromAnimationFrame:()=>zeA,fromArray:()=>JeA,fromEvent:()=>ca,fromEventPattern:()=>HeA,fromFetch:()=>qeA,fromIterable:()=>KeA,fromPromise:()=>m5,fromReadableStream:()=>WeA,fromReader:()=>jeA,groupBy:()=>LtA,identity:()=>TeA,ignoreElements:()=>ntA,iif:()=>LeA,inspect:()=>I5,interval:()=>p5,last:()=>ytA,map:()=>VK,mapTo:()=>MtA,max:()=>itA,merge:()=>UK,mergeMap:()=>TtA,mergeMapTo:()=>NtA,min:()=>otA,never:()=>AtA,nothing:()=>tg,of:()=>VeA,pairwise:()=>StA,pipe:()=>ma,race:()=>d5,range:()=>ZeA,reduce:()=>f5,retry:()=>HtA,scan:()=>S5,setAsapScheduler:()=>YeA,share:()=>AL,shareReplay:()=>keA,skip:()=>gtA,skipUntil:()=>ctA,skipWhile:()=>YK,startWith:()=>FK,subject:()=>EQ,subscribe:()=>Bl,sum:()=>stA,switchMap:()=>$2,switchMapTo:()=>e1,take:()=>l_,takeLast:()=>atA,takeUntil:()=>EE,takeWhile:()=>rtA,tap:()=>JK,throttle:()=>utA,throwError:()=>etA,timeInterval:()=>UtA,timeout:()=>JtA,timer:()=>PK,toPromise:()=>YtA,toReadableStream:()=>VtA,withLatestFrom:()=>FeA,zip:()=>UeA});var l5=A=>A(),TeA=A=>A;function LK(){this.dispose()}var I5=()=>typeof __FASTRX_DEVTOOLS__<"u",NeA=1,yy=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let e=new GeA(A,this,this.streamId++);return Ic.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},z2=class{constructor(){this.defers=new Set,this.disposed=!1}next(A){}complete(){this.dispose()}error(A){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=tg,this.error=tg,this.next=tg,this.dispose=tg,this.subscribe=tg,this.doDefer()}subscribe(A){return A instanceof yy?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(l5),this.defers.clear()}defer(A){this.defers.add(A)}removeDefer(A){this.defers.delete(A)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Os=class extends z2{constructor(A){super(),this.sink=A,A.defer(this.bindDispose)}next(A){this.sink.next(A)}complete(){this.sink.complete()}error(A){this.sink.error(A)}},Z2=class extends z2{constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:tg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:tg;if(super(),this._next=e,this._error=o,this._complete=a,this.then=tg,A instanceof yy){let c={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{Ic.defer(c,0)}),Ic.create(c),Ic.pipe(c),this.sourceId=c.id,this.subscribe(A),Ic.subscribe({id:c.id,end:!0}),e==tg?this._next=d=>Ic.next(c,0,d):this.next=d=>{Ic.next(c,0,d),e(d)},a==tg?this._complete=()=>Ic.complete(c,0):this.complete=()=>{this.dispose(),Ic.complete(c,0),a()},o==tg?this._error=d=>Ic.complete(c,0,d):this.error=d=>{this.dispose(),Ic.complete(c,0,d),o(d)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function ma(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;ad(c),A)}function lr(A,e,o){if(I5()){let a=Object.defineProperties(Object.setPrototypeOf(A,yy.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:e,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ic.create(a);for(let c=0;c{if(d instanceof yy){let C=lr(y=>{let S=new A(y,...a);S.sourceId=C.id,S.subscribe(d)},e,arguments);return C.source=d,Ic.pipe(C),C}return C=>d(new A(C,...a))}}}function Dy(A,e){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:e}})}var GeA=class extends Os{constructor(A,e,o){super(A),this.source=e,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{Ic.defer(this.source,this.id)})}next(A){Ic.next(this.source,this.id,A),this.sink.next(A)}complete(){Ic.complete(this.source,this.id),this.sink.complete()}error(A){Ic.complete(this.source,this.id,A),this.sink.error(A)}},Ic={addSource(A,e){Dy("addSource",{id:A.id,name:A.toString(),source:{id:e.id,name:e.toString()}})},next(A,e,o){Dy("next",{id:A.id,streamId:e,data:o&&o.toString()})},subscribe(A,e){let{id:o,end:a}=A;Dy("subscribe",{id:o,end:a,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(A,e,o){Dy("complete",{id:A.id,streamId:e,err:o?o.toString():null})},defer(A,e){Dy("defer",{id:A.id,streamId:e})},pipe(A){Dy("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){Dy("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=NeA++),Dy("create",{name:A.toString(),id:A.id})}},u5=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},E5=class extends z2{constructor(A){super(),this.source=A,this.sinks=new Set}add(A){A.defer(()=>this.remove(A)),this.sinks.add(A).size===1&&(this.reset(),this.subscribe(this.source))}remove(A){this.sinks.delete(A),this.sinks.size===0&&this.dispose()}next(A){this.sinks.forEach(e=>e.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(e=>e.error(A)),this.sinks.clear()}};function AL(){return A=>{let e=new E5(A);if(A instanceof yy){let o=lr(a=>{e.add(a)},"share",arguments);return e.sourceId=o.id,o.source=A,Ic.pipe(o),o}return lr(e.add.bind(e),"share",arguments)}}function UK(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=new Os(a),d=e.length;c.complete=()=>{--d===0&&a.complete()},e.forEach(c.bindSubscribe)},"merge",arguments)}function d5(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=new Map;e.forEach(d=>{let C=new Os(a);c.set(d,C),C.complete=()=>{c.delete(d),c.size===0?a.complete():C.dispose()},C.next=y=>{c.delete(d),c.forEach(S=>S.dispose()),C.resetNext(),C.resetComplete(),C.next(y)}}),e.forEach(d=>c.get(d).subscribe(d))},"race",arguments)}function beA(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=0,d=e.length,C=new Os(a);C.complete=()=>{c{let o=new E5(e),a=[];return o.next=function(c){a.push(c),a.length>A&&a.shift(),this.sinks.forEach(d=>d.next(c))},lr(c=>{c.defer(()=>o.remove(c)),a.forEach(d=>c.next(d)),o.add(c)},"shareReplay",arguments)}}function LeA(A,e,o){return lr(a=>A()?e(a):o(a),"iif",arguments)}function C5(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=e.length,d=c,C=c,y=new Array(c),S=()=>{--C===0&&a.complete()};e.forEach((k,V)=>{let J=new Os(a);J.next=gA=>{d--,J.next=CA=>{y[V]=CA,d===0&&a.next(y)},J.next(gA)},J.complete=S,J.subscribe(k)})},"combineLatest",arguments)}function UeA(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=e.length,d=c,C=new Array(c),y=()=>{--d===0&&a.complete()};e.forEach((S,k)=>{let V=new Os(a),J=[];C[k]=J,V.next=gA=>{J.push(gA),C.every(CA=>CA.length)&&a.next(C.map(CA=>CA.shift()))},V.complete=y,V.subscribe(S)})},"zip",arguments)}function FK(){for(var A=arguments.length,e=new Array(A),o=0;olr(function(c){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,C=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length;for(;d1?o-1:0),c=1;cthis.buffer=d,e.complete=tg,e.subscribe(C5(...a))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),OeA=Ps(class extends Os{constructor(A,e,o){super(A),this.bufferSize=e,this.startBufferEvery=o,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(A){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(A)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(A),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(A=>this.sink.next(A)),super.complete()}},"bufferCount"),PeA=Ps(class extends Os{constructor(A,e){super(A),this.buffer=[];let o=new Os(A);o.next=a=>{A.next(this.buffer),this.buffer=[]},o.complete=tg,o.subscribe(e)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),xeA=function(A,e,o,a){return new(o||(o=Promise))(function(c,d){function C(k){try{S(a.next(k))}catch(V){d(V)}}function y(k){try{S(a.throw(k))}catch(V){d(V)}}function S(k){k.done?c(k.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(k.value).then(C,y)}S((a=a.apply(A,[])).next())})};function EQ(A){let e=arguments,o=AL()(lr(a=>{o.next=c=>a.next(c),o.complete=()=>a.complete(),o.error=c=>a.error(c),A&&a.subscribe(A)},"subject",e));return o.next=tg,o.complete=tg,o.error=tg,o}function h5(A){return lr(e=>e.subscribe(A()),"defer",arguments)}var c_={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},OK=typeof Promise<"u"?c_.promise:c_.setImmediate?c_.setImmediate:c_.setTimeout,B5=A=>e=>{OK(()=>A(e))},YeA=A=>{typeof A=="function"?OK=A:c_[A]&&(OK=c_[A])},Q5=A=>B5(e=>{for(let o=0;!e.disposed&&o{let o=0,a=setInterval(()=>e.next(o++),A);return e.defer(()=>{clearInterval(a)}),"interval"},"interval",arguments)}function PK(A,e){return lr(o=>{let a=0,c=setTimeout(()=>{if(o.removeDefer(d),o.next(a++),e){let C=setInterval(()=>o.next(a++),e);o.defer(()=>{clearInterval(C)})}else o.complete()},A),d=()=>clearTimeout(c);o.defer(d)},"timer",arguments)}function X2(A,e){return o=>{let a=c=>o.next(c);o.defer(()=>e(a)),A(a)}}function HeA(A,e){return lr(X2(A,e),"fromEventPattern",arguments)}function ca(A,e){if("on"in A&&"off"in A)return lr(X2(o=>A.on(e,o),o=>A.off(e,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return lr(X2(o=>A.addListener(e,o),o=>A.removeListener(e,o)),"fromEvent",arguments);if("addEventListener"in A)return lr(X2(o=>A.addEventListener(e,o),o=>A.removeEventListener(e,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function m5(A){return lr(e=>{A.then(o=>{e.next(o),e.complete()},e.error.bind(e))},"fromPromise",arguments)}function qeA(A,e){return lr(h5(()=>m5(fetch(A,e))),"fromFetch",arguments)}function KeA(A){return lr(B5(e=>{try{for(let o of A){if(e.disposed)return;e.next(o)}e.complete()}catch(o){e.error(o)}}),"fromIterable",arguments)}function jeA(A){let e=o=>xeA(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:a,value:c}=yield A.read();if(a)return void o.complete();o.next(c),e(o)}catch(a){o.error(a)}});return lr(o=>{e(o)},"fromReader",arguments)}function WeA(A){return lr(e=>{let o=new AbortController,a=o.signal;e.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(c){e.next(c)},close(){e.complete()},abort(c){e.error(c)}}),{signal:a}).then(()=>e.complete(),c=>e.error(c))},"fromReadableStream",arguments)}function zeA(){return lr(A=>{let e=requestAnimationFrame(function o(a){A.disposed||(A.next(a),e=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(e))},"fromAnimationFrame",arguments)}function ZeA(A,e){return lr(function(o){let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e+A;for(;a2?o-2:0),c=2;c{let C=a.concat(y=>(d.next(y),d.complete()));A.apply(e,C)},"bindCallback",arguments)}function $eA(A,e){for(var o=arguments.length,a=new Array(o>2?o-2:0),c=2;c{let C=a.concat((y,S)=>y?d.error(y):(d.next(S),d.complete()));A.apply(e,C)},"bindNodeCallback",arguments)}function AtA(){return lr(()=>{},"never",arguments)}function etA(A){return lr(e=>e.error(A),"throwError",arguments)}function xK(){return lr(A=>A.complete(),"empty",arguments)}var eL=class extends Os{constructor(A,e,o){super(A),this.f=e;let a=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=c=>{this.acc=c,this.complete=a,this.resetNext()}:(this.acc=o,this.complete=a)}next(A){this.acc=this.f(this.acc,A)}},f5=Ps(eL,"reduce"),ttA=A=>Ps(eL,"count")((e,o)=>A(o)?e+1:e,0),itA=()=>Ps(eL,"max")(Math.max),otA=()=>Ps(eL,"min")(Math.min),stA=()=>Ps(eL,"sum")((A,e)=>A+e,0),JM=Ps(class extends Os{constructor(A,e,o){super(A),this.filter=e,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),ntA=Ps(class extends Os{next(A){}},"ignoreElements"),l_=Ps(class extends Os{constructor(A,e){super(A),this.count=e}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),EE=Ps(class extends Os{constructor(A,e){super(A);let o=new Os(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=LK,o.subscribe(e)}},"takeUntil"),rtA=Ps(class extends Os{constructor(A,e){super(A),this.f=e}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),atA=A=>f5((e,o)=>(e.push(o),e.length>A&&e.shift(),e),[]),gtA=Ps(class extends Os{constructor(A,e){super(A),this.count=e}next(A){--this.count===0&&(this.next=super.next)}},"skip"),ctA=Ps(class extends Os{constructor(A,e){super(A),A.next=tg;let o=new Os(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=LK,o.subscribe(e)}},"skipUntil"),YK=Ps(class extends Os{constructor(A,e){super(A),this.f=e}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),ltA={leading:!0,trailing:!1},ItA=class extends Os{constructor(A,e,o){super(A),this.durationSelector=e,this.trailing=o}cacheValue(A){this.last=A,this.disposed&&this.throttle(A)}send(A){this.sink.next(A),this.throttle(A)}throttle(A){this.reset(),this.subscribe(this.durationSelector(A))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},y5=class extends Os{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ltA;super(A),this.durationSelector=e,this.config=o,this._throttle=new ItA(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(A){this._throttle.disposed&&this.config.leading?this._throttle.send(A):this._throttle.cacheValue(A)}complete(){this._throttle.throttle=tg,this._throttle.complete(),super.complete()}},utA=Ps(y5,"throttle"),EtA={leading:!1,trailing:!0},dtA=A=>Ps(y5,"audit")(A,EtA),CtA=class extends Os{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},D5=class extends Os{constructor(A,e){super(A),this.durationSelector=e,this._debounce=new CtA(this.sink),this._debounce.dispose()}next(A){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=A,this._debounce.subscribe(this.durationSelector(A))}complete(){this._debounce.complete(),super.complete()}},htA=Ps(D5,"debounce"),BtA=A=>Ps(D5,"debounceTime")(e=>PK(A)),QtA=Ps(class extends Os{constructor(A,e,o){super(A),this.count=e,this.defaultValue=o}next(A){this.count--===0&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),ptA=A=>e=>l_(1)(YK(o=>!A(o))(e)),mtA=Ps(class extends Os{constructor(A,e){super(A),this.f=e,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),ftA=Ps(class extends Os{constructor(A,e,o){super(A),this.f=e,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),ytA=Ps(class extends Os{constructor(A,e,o){super(A),this.f=e,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A)}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),DtA=Ps(class extends Os{constructor(A,e){super(A),this.predicate=e,this.index=0}next(A){this.predicate(A,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){this.result!==void 0?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),S5=Ps(class extends Os{constructor(A,e,o){super(A),this.f=e,o===void 0?this.next=a=>{this.acc=a,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),StA=Ps(class extends Os{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),M5=class extends Os{constructor(A,e,o){super(A),this.mapper=e,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},VK=Ps(M5,"map"),MtA=A=>Ps(M5,"mapTo")(e=>A),tL=class extends Os{constructor(A,e,o){super(A),this.data=e,this.context=o}next(A){let e=this.context.combineResults;e?this.sink.next(e(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},iL=class k9 extends Os{constructor(e,o,a){super(e),this.makeSource=o,this.combineResults=a,this.index=0}subInner(e,o){let a=this.currentSink=new o(this.sink,e,this);this.complete===k9.prototype.complete&&(this.complete=this.tryComplete),a.complete=a.tryComplete,a.subscribe(this.makeSource(e,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},v5=class extends tL{},R5=class extends iL{next(A){this.subInner(A,v5),this.next=e=>{this.currentSink.dispose(),this.subInner(e,v5)}}},$2=Ps(R5,"switchMap");function A1(A){return(e,o)=>A(()=>e,o)}var e1=A1(Ps(R5,"switchMapTo")),vtA=class extends tL{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},w5=class extends iL{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(A){this.next2(A),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),vtA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},RtA=Ps(w5,"concatMap"),wtA=A1(Ps(w5,"concatMapTo")),_tA=class extends tL{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},_5=class extends iL{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,_tA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},TtA=Ps(_5,"mergeMap"),NtA=A1(Ps(_5,"mergeMapTo")),GtA=class extends tL{dispose(){this.context.resetNext(),super.dispose()}},T5=class extends iL{next(A){this.next=tg,this.subInner(A,GtA)}},btA=Ps(T5,"exhaustMap"),ktA=A1(Ps(T5,"exhaustMapTo")),LtA=Ps(class extends Os{constructor(A,e){super(A),this.f=e,this.groups=new Map}next(A){let e=this.f(A),o=this.groups.get(e);o===void 0&&(o=EQ(),o.key=e,this.groups.set(e,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(e=>e.error(A)),super.error(A)}},"groupBy"),UtA=Ps(class extends Os{constructor(){super(...arguments),this.start=new Date}next(A){this.sink.next({value:A,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),FtA=Ps(class extends Os{constructor(A,e){super(A),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(A){this.buffer.push(A)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),OtA=Ps(class extends Os{constructor(A,e){super(A),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:o,data:a}=e;super.next(a),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(o))}},A)}next(A){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:A})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},"delay"),N5=Ps(class extends Os{constructor(A,e){super(A),this.selector=e}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),PtA=class extends tL{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},xtA=Ps(class extends iL{constructor(A,e){super(A,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let e=new PtA(this.sink,A,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(A,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),YtA=()=>A=>new Promise((e,o)=>{let a;new Z2(A,c=>a=c,o,()=>e(a))}),VtA=()=>A=>{let e;return new ReadableStream({start(o){e=new Z2(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){e.dispose()}})},Bl=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tg,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:tg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg;return a=>new Z2(a,A,e,o)},JK=Ps(class extends Os{constructor(A,e){super(A),e instanceof Function?this.next=o=>{e(o),A.next(o)}:(e.next&&(this.next=o=>{e.next(o),A.next(o)}),e.complete&&(this.complete=()=>{e.complete(),A.complete()}),e.error&&(this.error=o=>{e.error(o),A.error(o)}))}},"tap"),JtA=Ps(class extends Os{constructor(A,e){super(A),this.timeout=e,this.id=setTimeout(()=>this.error(new u5(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),HtA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return e=>{if(e instanceof yy){let o=lr(a=>{let c=A,d=new Os(a);d.error=C=>{c-- >0?d.subscribe(e):a.error(C)},d.sourceId=o.id,d.subscribe(e)},"retry",[A]);return o.source=e,Ic.pipe(o),o}return o=>{let a=A,c=new Os(o);c.error=d=>{a-- >0?e(c):o.error(d)},e(c)}}},HK=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(HK||{}),oL=class L9 extends kK{constructor(e,o){super({mediaType:e,PlayerClass:o}),Y(this,"isRemote",!1),Y(this,"deviceId"),Y(this,"groupId",""),Y(this,"label",""),Y(this,"sourceTrack"),Y(this,"enableAutoSwitchWhenRecapturing",!0),Y(this,"_isRecapturing",!1),Y(this,"_lastRecaptureTime",0),Y(this,"_onMuteTimeoutId",-1),Y(this,"_encodeCheckTimeoutId",-1),Y(this,"recaptureMode",0),Y(this,"profile"),Y(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,o){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(YA.MUTE,this.onTrackMuted),e.addEventListener(YA.UNMUTE,this.onTrackUnmuted),e.addEventListener(YA.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===YA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(YA.MUTE,this.onTrackMuted),e.removeEventListener(YA.UNMUTE,this.onTrackUnmuted),e.removeEventListener(YA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return KA(this,null,function*(){var a,c;let d=this.sourceTrack;try{let C,y=ko();F.emit(nA.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(C=new MediaStream,C.addTrack(e.customSource)):(o||(a=this.sourceTrack)==null||a.stop(),C=yield ReA(e));let S=C.getTracks()[0];return yield this.setInputMediaStreamTrack(S),e.customSource||(this.sourceTrack=S,this.updateDeviceIdInUse(),this.listenDeviceChange()),F.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ko()-y,profile:this.profile,room:(c=this.manager)==null?void 0:c.room}),C}catch(C){throw F.emit(nA.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:C}),this.log.error("getUserMedia error observed ".concat(C)),C}finally{o&&d?.stop()}})}setOutputMediaStreamTrack(e){var o;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var e,o;let a=wp(((e=this.room)==null?void 0:e.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&a.hasVideo||this.mediaType===1&&a.hasAudio||this.mediaType===2&&a.hasAuxiliary}publish(e,o){return KA(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield o,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((o,a)=>KA(this,null,function*(){var c,d,C,y,S;let k=()=>a(new ai({code:dt.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===Zs.INIT||this.state==="ready")&&k(),ma(ca(e,"local-publish-flag-changed"),JM(()=>this.hasFlag),EE(UK(ca(this,Zs.INIT),ca(this,"ready"))),Bl(o,a,k))),(C=(d=(c=this.room)==null?void 0:c.networkQuality)==null?void 0:d.hadRecentBadUplink)!=null&&C.call(d,2))return o();let V=e.heartbeatCount,J=((S=(y=this.mediaTrack)==null?void 0:y.stats)==null?void 0:S.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>KA(this,null,function*(){var gA,CA,MA,$A,Be,Ye,ve,yi;if((MA=(CA=(gA=this.room)==null?void 0:gA.networkQuality)==null?void 0:CA.hadRecentBadUplink)!=null&&MA.call(CA,2)||e.heartbeatCount-V<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(($A=this.mediaTrack)!=null&&$A.stats){let hi=this.mediaTrack.stats.totalFrames||0;hi-J===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",hi)}let Ge=this.kind===YA.AUDIO,Bt=this.stat.bytesSent>0;if(ii[Bt?"addSuccessEvent":"addFailedEvent"]({key:Ge?503700:513702}),!Ge){let hi={H264:513704,H265:513705,VP8:513706}[((Ye=(Be=this.room)==null?void 0:Be.videoCodec)==null?void 0:Ye.toUpperCase())||"H264"];hi&&ii[Bt?"addSuccessEvent":"addFailedEvent"]({key:hi})}if(!Bt){if(ii.addEnum({key:Ge?503701:513703,value:xp()}),sn.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(rQ()||Yp()),userId:this.userId}),this.log.warn(Ge?"encode failed":"".concat((yi=(ve=this.room)==null?void 0:ve.videoCodec)==null?void 0:yi.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield LC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),a(new ai({message:"".concat(this.strMediaType," encode failed"),code:Ge?dt.AUDIO_ENCODE_FAILED:dt.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),F.emit(nA.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return KA(this,null,function*(){if(this.sourceTrack&&Cy){let{deviceId:e,groupId:o}=this.sourceTrack.getSettings(),{label:a}=this.sourceTrack;(yield function(c){return KA(this,arguments,function(d){let{newDeviceId:C,oldDeviceId:y,oldGroupId:S,oldLabel:k,kind:V}=d;return function*(){return C===y&&(V!==YA.AUDIO||C!==ZS||(yield i5(S,k)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=a,o&&(this.groupId=o),q2().then(c=>{let d=c.find(C=>{let y=C.deviceId===e;return o&&(y=y&&C.groupId===o),y});d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===YA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("mic")||a.includes("麦克风"))return!0;let c="".concat((o?.getSettings()||{}).deviceId,"_").concat(YA.AUDIO_INPUT);return!!GK.has(c)}(this.sourceTrack)||this.kind===YA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("camera")||a.includes("webcam"))return!0;let c="".concat((o?.getSettings()||{}).deviceId,"_").concat(YA.VIDEO_INPUT);return!!GK.has(c)}(this.sourceTrack)||this._isRecapturing||e&&iQ&&Bg)}onTrackMuted(){if(super.onTrackMuted(),weA(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTime<$S)return void setTimeout(()=>this.onTrackMuted(),$S);this._onMuteTimeoutId=setTimeout(()=>KA(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((eg||Ha)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return KA(this,null,function*(){if(NI(L9.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTime<$S)return void setTimeout(()=>this.onTrackEnded(),$S);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return KA(this,null,function*(){var a;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let c=this.sourceTrack;o||(a=this.sourceTrack)==null||a.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let d={useExactDeviceId:!0};if(e==="user"||e==="environment")d.facingMode=e;else{let C;(this.kind==="audio"?yield Xp():yield $p()).find(y=>y.deviceId===e)&&(C=e),d.deviceId=C}return this.capture(d,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),F.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(C=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(C.message)),this.emit("5",C),F.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this,error:C})}).finally(()=>{o&&c?.stop()})})}getRecoverCaptureDeviceId(){return KA(this,null,function*(){let e=this instanceof dQ;if(e&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let a=(nL.get(o)||0)+1;if(nL.set(o,a),a>=3&&this.enableAutoSwitchWhenRecapturing){let c=e?(yield $p()).find(d=>!nL.has(d.deviceId)):(yield Xp()).find(d=>!nL.has(d.deviceId));c&&(this.log.warn("".concat(o," capture fail ").concat(a," times, change new ").concat(c.deviceId)),o=c.deviceId)}}return o})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),F.emit(nA.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};Ci([lc(Zs.INIT,"ready",{ignoreError:!0,sync:!0})],oL.prototype,"setStateToReady"),Ci([$k()],oL.prototype,"capture"),Ci([lc("ready","publish",{ignoreError:!0,success(){F.emit(nA.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(A){var e;(e=this.room)==null||e.localTracks.delete(this);let o="error",a=A instanceof ai?A:A.cause instanceof ai?A.cause:A,c=!1;a instanceof ai&&(a.message.includes("timeout")?o="timeout":a.code===dt.API_CALL_ABORTED&&(c=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:a}),this.log[c?"info":"error"]("publish failed",a)}}),fy(521714,!1)],oL.prototype,"publish"),Ci([jr(A=>function(){return KA(this,null,function*(){let e=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:e,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),lc([],"ready",{sync:!0})],oL.prototype,"unpublish");var sL=oL,nL=new Map;F.on(nA.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&nL.delete(A.track.deviceId)});var HM=class NL extends sL{constructor(e){super(1,yeA),Y(this,"mediaType",1),Y(this,"volume",0),Y(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Y(this,"playerMuted",!0),Y(this,"pipeline"),Y(this,"earMonitorGainNode",new OI),Y(this,"_output",new OI),Y(this,"codecPipeline",[]),Y(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Y(this,"mixedAudioReferenceMap",new Map),Y(this,"isAudioContextLongSuspended",!1),Y(this,"after3aSilenceStartTime",0),Y(this,"_micMuted",!1),Y(this,"_volumeDetectionTrack",null),Y(this,"_volumeDetectionSource",new OI),this.manager=e,this.pipeline=new Z4(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),F.on(nA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return H2.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){Je(e)||(e!==0||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=ko())}setInputMediaStreamTrack(e){return KA(this,null,function*(){let o=this.trackSettings||{};ii.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),ii.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),ii.addEnum({key:502700,value:0});let{sampleRate:a,channelCount:c}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:a,channelCount:c}))),this.pipeline.source.channelCount=c||1,this.pipeline.replaceSource(e),yield NI(NL.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(e){return KA(this,arguments,function(o){var a=this;let{deviceId:c,customSource:d,useExactDeviceId:C=!0,retryWhenExactFailed:y}=o,S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let k=yield NI(NL.prototype,a,"capture").call(a,{video:!1,audio:!0,microphoneId:c,echoCancellation:a.profile.echoCancellation,autoGainControl:a.profile.autoGainControl,noiseSuppression:a.profile.noiseSuppression,sampleRate:a.profile.sampleRate,channelCount:a.profile.channelCount,useExactDeviceId:C,retryWhenExactFailed:y,customSource:d},S);return Zk(),k}()})}switchDevice(e){return KA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource&&(e!==ZS||(yield i5(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),F.emit(nA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(o){throw this.log.error("switch microphone failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}}})}listenDeviceChange(){Pc&&!Pc.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Pc.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return KA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(HK[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Jg(this.userId,{eventId:2003,param1:6,streamType:1});let a=yield Xp();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Pc.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Pc.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return KA(this,arguments,function(o){var a=this;let{echoCancellation:c,noiseSuppression:d,autoGainControl:C}=o;return function*(){let y=a.sourceTrack||a.mediaTrack;if(!y)return;let S=y.getConstraints(),k=!1;!Je(c)&&c!==a.profile.echoCancellation&&(a.profile.echoCancellation=c,S.echoCancellation=c,k=!0),!Je(d)&&d!==a.profile.noiseSuppression&&(a.profile.noiseSuppression=d,S.noiseSuppression=d,k=!0),!Je(C)&&C!==a.profile.autoGainControl&&(a.profile.autoGainControl=C,S.autoGainControl=C,k=!0),k&&(er||Bg?yield y.applyConstraints(S).catch(V=>a._log.warn("update3A failed: ",V)):a.deviceId&&(yield a.recapture(a.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&ii.addEnum({key:502700,value:2})}setMute(e,o){var a;this._cleanupVolumeDetectionTrack(),e==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((a=this.manager)==null?void 0:a.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),F.emit(nA.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):e===!0?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),this.emit("mute",this),F.emit(nA.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),F.emit(nA.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let o=V2(this._volumeDetectionTrack);o&&this._volumeDetectionSource.setNode(o)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(e){super.setAudioVolume(0),eg&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(FI().createGain()),this._output.setNode(FI().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!Bg&&!eg)return this.update3A({echoCancellation:e})}addDenoiser(e){var o;id<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(ii.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let a=V2(e);if(!a)return;let c=new OI,d=FI().createGain();d.gain.value=1;let C=new OI;c.pipeTo(C).pipeTo(this.pipeline.mixNode),c.setNode(a),C.setNode(d),this.mixedAudioReferenceMap.set(o,[c,C])}unMixAudioReference(e){let[o,a]=this.mixedAudioReferenceMap.get(e)||[];o&&(this.log.info("unMixAudioReference() => ".concat(e)),o.deleteNode(),a?.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,o){let[a,c]=this.mixedAudioReferenceMap.get(e)||[];c!=null&&c.node&&(c.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(c.node.gain.value)))}addAudioProcessor(e,o,a){this.pipeline.silentNode.setNode(a),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[o,a]=e;o.deleteNode(),a.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Pc.off("audioInputAdded",this.handleMicrophoneAdded,this),Pc.off("audioInputRemoved",this.handleMicrophoneRemoved,this),F.off(nA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return KA(this,null,function*(){try{yield NI(NL.prototype,this,"recapture").call(this,e,o)}catch(a){let c=(yield Xp()).find(d=>d.deviceId!==e);if(!c)throw a;yield NI(NL.prototype,this,"recapture").call(this,c.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((o,a)=>a?a({frame:o,ntp:Lf()}):o,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(e){let{isSuspended:o}=e;if(this.pipeline.isProcessEnabled)if(o){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(Fp?"":", non-Safari"));let a=this.sourceTrack||this.mediaTrack;a&&this.setOutputMediaStreamTrack(a)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(e=o)}super.setOutputMediaStreamTrack(e)}};function t1(A,e){return e+4<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===0&&A.getUint8(e+3)===1?4:e+3<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===1?3:0}function G5(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),a=[],c=0;for(;c0){C=J;break}let y=C===-1?o.byteLength:C,S=y-c,k=new ArrayBuffer(S),V=new DataView(k);for(let J=0;J1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-2,o=[],a=0;for(let d=A;d<=e;d++){let C=this.dataView.getInt8(d);switch(C){case 0:case 1:case 2:case 3:a===2&&(o.push(3),a=0),C===0?a+=1:a=0,o.push(C);break;default:a=0,o.push(C)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let c=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=c}removePreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-1,o=[],a=0;for(let d=A;d<=e;d++)switch(this.dataView.getInt8(d)){case 0:a++,o.push(this.dataView.getInt8(d));break;case 3:a!==2&&o.push(this.dataView.getInt8(d)),a=0;break;default:o.push(this.dataView.getInt8(d)),a=0}let c=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=c}get seiPayloadStartIndex(){let A=6;for(let e=6;e=this.dataView.byteLength?0:31&this.dataView.getUint8(A)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},qtA=class{constructor(){Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_seiPayloadType",243)}encodeSEINalu(A){let e=A.byteLength,o=parseInt(String(e/255),10),a=e%255,c=[];c.push(0,0,0,1,6,this._seiPayloadType);for(let C=0;C0&&A.data.byteLength>0){let a=9-this.getNaluCount(A.data);if(a<=0)return 0;let c=o.splice(0,a).reverse().map(this.encodeSEINalu.bind(this)),d=c.reduce((V,J)=>V+J.dataView.byteLength,0),C=new ArrayBuffer(d+A.data.byteLength),y=new DataView(C),S=new DataView(A.data),k=0;for(let V=0;V1&&arguments[1]!==void 0?arguments[1]:4,vo),Y(this,"profile",mi({},HS)),Y(this,"avoidCropping",!1),Y(this,"_scaleResolutionDownBy"),Y(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),Y(this,"small"),Y(this,"isNeedToSetBandwidth"),Y(this,"muteImage"),Y(this,"manager"),Y(this,"_seiCodec",new qtA),this.manager=e;let o=()=>{var a;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let c=Kd(((a=this.room)==null?void 0:a.sdkAppId)||0)?Db:s0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(c)),this.setProfile(Qo(mi({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(Cy&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!((e=this.manager)==null||!e.hasSmall)}setMute(e){return KA(this,null,function*(){var o,a,c;if(Yn(e)){if(this.muteImage===e)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(a=this.manager)==null?void 0:a.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,NI(w_.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(c=this.manager)==null?void 0:c.deleteWatermark("mute"),this.muteImage=void 0),NI(w_.prototype,this,"setMute").call(this,e)})}capture(e){return KA(this,arguments,function(o){var a=this;let{deviceId:c,facingMode:d,useExactDeviceId:C=!0,customSource:y,retryWhenExactFailed:S=!0}=o;return function*(){let k={audio:!1,video:!0,facingMode:d||a.facingMode,cameraId:c,width:a.profile.width,height:a.profile.height,frameRate:a.profile.frameRate,useExactDeviceId:C,retryWhenExactFailed:S,customSource:y};if(k.facingMode==="environment"){let V=yield a.getDeviceIdWhenUsingBackCamera();V&&(k.cameraId=V)}return NI(w_.prototype,a,"capture").call(a,k)}()})}setProfile(e){var o;let a=this.fallbackProfile(e);if(a.bitrate&&(this.isNeedToSetBandwidth=a.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(a);else{let c=Kd(((o=this.room)==null?void 0:o.sdkAppId)||0)?Db:s0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(c)),super.setProfile(Qo(mi({},this.profile),{width:1920,height:1080}))}}applyProfile(){return KA(this,null,function*(){var e,o;if(!this.mediaTrack)return;let{width:a=0,height:c=0}=(this.sourceTrack||this.mediaTrack).getSettings(),d=a*c,C=this.settings,y=C.height!==this.profile.height||C.width!==this.profile.width||C.frameRate!==this.profile.frameRate;if(y&&(Zd===16&&this.deviceId?yield this.recapture(this.deviceId):(_p(this.outMediaTrack)?yield(e=this.outMediaTrack)==null?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}):yield(o=this.sourceTrack||this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:S=0,height:k=0}=(this.sourceTrack||this.mediaTrack).getSettings(),V=S*k;return y&&V&&d&&V===d?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:YA.VIDEO,videoType:YA.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return Cy&&o&&Object.assign(e,o.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:w0(this.settings,this.profile)}isAllowed2k4k(e){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return KA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?o.facingMode=e:o.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),F.emit(nA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(o){throw this.log.error("switch camera failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}})}getDeviceIdWhenUsingBackCamera(){return KA(this,null,function*(){let e;try{if(lk&&!oy&&L2){let o=(yield $p(!0)).map(c=>{var d;return Qo(mi({},c),{capabilities:(d=c.getCapabilities)==null?void 0:d.call(c)})}).filter(c=>{var d,C;return(C=(d=c.capabilities)==null?void 0:d.facingMode)==null?void 0:C.includes("environment")}),a=o[0];o.forEach(c=>{var d,C,y,S;let{capabilities:k}=c;((d=k.width)!=null&&d.max&&(C=k.height)!=null&&C.max?k.width.max*k.height.max:0)>((y=a.capabilities.width)!=null&&y.max&&(S=a.capabilities.height)!=null&&S.max?a.capabilities.width.max*a.capabilities.height.max:0)&&(a=c)}),a!=null&&a.capabilities&&(this._log.info("use max resolution back camera",a),e=a.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return e})}updateSmallConfig(e){return KA(this,null,function*(){var o,a;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let c=!this.small;this.small=this.fallbackProfile(e,!0),yield(o=this.manager)==null?void 0:o.update(),c&&(yield(a=this.room)==null?void 0:a.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=e.width>e.height,c=mi({},e);return e.width*e.height<=19200&&Ha&&IE&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),c.width=a?240:180,c.height=a?180:240,c.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&y2&&(c.width=a?1280:720,c.height=a?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),hk(kI,"14.3")&&ny(kI,"14.0",!0)&&this.on("7",()=>{let d=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=d?640:480,this.profile.height=d?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=d?640:360,this.profile.height=d?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!o&&this.avoidCropping&&(IE||er)&&!q0()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,c.width=1280,c.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),c}stopSmall(){var e,o;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){Pc&&!Pc.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Pc.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return KA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(HK[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Jg(this.userId,{eventId:2003,param1:7,streamType:2});let a=yield $p();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Pc.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return KA(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Pc.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))})}encodeFrame(e,o){if(!this.manager)return e;let a=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((c,d)=>d?d({frame:c,mediaType:a}):c,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,o){return Je(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,o)}close(){Pc.off("videoInputAdded",this.handleCameraAdded,this),Pc.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return KA(this,null,function*(){try{yield NI(w_.prototype,this,"recapture").call(this,e)}catch(o){let a=(yield $p()).find(c=>c.deviceId!==e);if(!a)throw o;yield NI(w_.prototype,this,"recapture").call(this,a.deviceId)}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||Je(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};Ci([VM(function(A){this.setContentHint(A.contentHint||"motion")})],b5.prototype,"capture");var dQ=b5,k5={};Hh(k5,{REPORT_TYPE:()=>_0,buildSSOPackage:()=>AQ,bytes2ms:()=>y0,calculateScaleResolutionDownNumber:()=>w0,concatArrayBuffers:()=>aM,convertObjectNumberToInt:()=>R0,copyProperties:()=>A2,deepClone:()=>zf,deepCloneBasic:()=>Zf,deepMerge:()=>Wh,delay:()=>LC,fibonacci:()=>Kf,formatedTime:()=>a2,getConstructorName:()=>iM,getContainerFromElement:()=>Jb,getEnv:()=>Zx,getFirst16Bits:()=>c2,getInternalVersion:()=>n2,getLast16Bits:()=>T0,getLoggerUrl:()=>Hf,getMediaStreamTrackInfo:()=>Wb,getMuteStateFromFlag:()=>wp,getNetworkType:()=>m0,getNumNetworkType:()=>qf,getReconnectionTimeout:()=>Rp,getStringByteLength:()=>v0,getTestSignalDomain:()=>Xx,getTurnServer:()=>r2,getUint32Version:()=>qb,getValueType:()=>Cg,getViewListFromView:()=>nM,glog:()=>t2,ipv4ToUint32:()=>sM,isArray:()=>wa,isAudioWorkletSupported:()=>i2,isBoolean:()=>Nr,isConstructor:()=>Wf,isEmpty:()=>S0,isFunction:()=>Ra,isLangChinese:()=>Wd,isMediaStreamTrack:()=>Yb,isNumber:()=>bn,isObject:()=>$E,isOverseaSdkAppId:()=>Kd,isPlainObject:()=>lE,isPortrait:()=>Hb,isPromise:()=>jf,isRemoteTrack:()=>Vb,isRotate90Or270:()=>$B,isSetSinkIdSupported:()=>o2,isString:()=>Yn,isUndefined:()=>Je,isVideoMixerOutputTrack:()=>_p,loadImage:()=>rM,loadVideo:()=>g2,ms2bytes:()=>e2,ms2samples:()=>D0,normalizeUrl:()=>jb,performanceNow:()=>ko,promiseAny:()=>oM,samples2ms:()=>xb,setNetworkTypeFromWebRTC:()=>f0,stringify:()=>zd,stringifyIncludeValue:()=>M0,throttlePromise:()=>Kb});var KtA=[-1,-1,1,-1,-1,1,1,1],jtA=[0,0,1,0,0,1,1,1],rL=class k3 extends Zs{constructor(e,o){if(super(),this.context=e,Y(this,"name"),Y(this,"input"),Y(this,"output"),Y(this,"texture"),Y(this,"ctx2d",null),Y(this,"fbo"),Y(this,"width",0),Y(this,"height",0),Y(this,"x",0),Y(this,"y",0),Y(this,"program"),Y(this,"vertexShader"),Y(this,"fragmentShader"),Y(this,"totalFrames",0),Y(this,"dropFrames",0),Y(this,"matchInputSize",!0),Y(this,"texCoordBuffer"),Y(this,"positionBuffer"),Y(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Y(this,"cost",0),Y(this,"_canvas",null),Y(this,"_image"),Y(this,"log"),this.context.on("disconnect",this.close,this),this.name=o.name,this.log=o.logger,this.matchInputSize=o.matchInputSize!==!1,this.width=o.width||e.width,this.height=o.height||e.height,this._image=o.image,e instanceof CQ)e.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&Zd!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let a=e.ctx;this.texCoordBuffer=this.createBuffer(jtA),this.positionBuffer=this.createBuffer(KtA),o.createTexture!==!1&&(this.texture=a.createTexture(),this.useTexture(),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.pixelStorei(a.UNPACK_ALIGNMENT,1)),o.useFbo&&(this.fbo=a.createFramebuffer(),this.useBufferFrame(),this.useTexture(),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,this.width,this.height,0,a.RGBA,a.UNSIGNED_BYTE,null),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=e.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?e.createShader(a.VERTEX_SHADER,o.vertexShaderSource):e.defaultVShader,this.fragmentShader=o.fragmentShaderSource?e.createShader(a.FRAGMENT_SHADER,o.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(a){this.context.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let o=this.context.ctx,a=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,a),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e,0),a}connect(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),c=1;c0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(e)}disconnect(){for(var e,o=arguments.length,a=new Array(o),c=0;c{d&&(e.activeTexture(e.TEXTURE0+C),e.bindTexture(e.TEXTURE_2D,d))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let o=this.context.ctx,a=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,a),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW),a}setTexBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}setPosBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}changeBufferData(e,o){let a=this.context.ctx;a.bindBuffer(a.ARRAY_BUFFER,e),a.bufferData(a.ARRAY_BUFFER,new Float32Array(o),a.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var o=arguments.length,a=new Array(o),c=0;c{e.enableVertexAttribArray(C),e.bindBuffer(e.ARRAY_BUFFER,d),e.vertexAttribPointer(C,2,e.FLOAT,!1,0,0)})}getVertexPoint(e,o){return[e/this.width*2-1,o/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,o){if(this.width!==e||this.height!==o){if(this.width=e,this.height=o,this._canvas&&(this._canvas.width=e,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,e,o,0,a.RGBA,a.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,o)}}draw(e,o){this.setAttributes(e||this.positionBuffer,o||this.texCoordBuffer);let a=this.context.ctx;a.drawArrays(a.TRIANGLE_STRIP,0,4)}draw2d(e,o,a,c,d,C,y,S,k){let V=!(Je(C)||Je(y)||Je(S)||Je(k));return!(!this.ctx2d||!e)&&(e instanceof ImageData?(V?this.ctx2d.putImageData(e,o,a,C,y,S,k):this.ctx2d.putImageData(e,o,a),this.emit(k3.RENDER,this.ctx2d.canvas)):(V?this.ctx2d.drawImage(e,C,y,S,k,o,a,c,d):this.ctx2d.drawImage(e,o,a,c,d),this.emit(k3.RENDER,e)),typeof VideoFrame<"u"&&e instanceof VideoFrame&&e.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:o,x:a,y:c,width:d,height:C,name:y,cost:S}=this,k=Date.now(),V=(o-this.lastInfo.totalFrames)/((k-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:a,y:c,width:d,height:C,timestamp:k,fps:V,name:y,cost:S},mi({parent:(e=this.input)==null?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let o=this.context.ctx,a=o.createTexture();return this.useTextures(a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.UNPACK_ALIGNMENT,1),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,e),a}};Y(rL,"RENDER","render"),Ci([lc(Zs.INIT,"connected",{sync:!0})],rL.prototype,"connect"),Ci([lc("connected",Zs.INIT,{ignoreError:!0,sync:!0})],rL.prototype,"disconnect"),Ci([lc([],"closed",{sync:!0})],rL.prototype,"close");var AC=rL,WtA=ma(p5(250),VK(()=>performance.now()),AL()),ztA=[0,1,1,1,0,0,1,0],qK=class extends AC{constructor(A,e){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},e)),Y(this,"_intervalId",0),Y(this,"_sequence",0),Y(this,"checkGLError",!1),Y(this,"checkVisibilityChange"),A instanceof CQ?this.ctx2d=A.ctx||null:A.available&&e!=null&&e.mirrorUpAndDown&&this.setTexBuffer(ztA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),Gr.clearTask(this._intervalId),this._intervalId=Gr.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(Gr.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof VC){let e=this.context.ctx.getError();e&&this.context.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}},{fps:this.context.frameRate})}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(AC.RENDER,this.context._canvas),!0)}addInput(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(Gr.clearTask(this._intervalId),this._intervalId=0,A===1&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(A){super.removeInput(A),Gr.clearTask(this._intervalId)}resize(A,e){super.resize(A,e),this.context.setSize(A,e)}close(){super.close(),Gr.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},KK=class extends qK{constructor(A,e){super(A,e),Y(this,"_videoTrack"),Y(this,"_muteOb"),Y(this,"_closedOb",ca(this,"closed")),Y(this,"_subscription"),Y(this,"_canvasContainer"),Number(oQ)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=ca(this._videoTrack,"mute"),ma(ca(this._videoTrack,"ended"),EE(this._closedOb),Bl(()=>{this.context.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=ma(this._muteOb,EE(this._closedOb),e1((A=5e3,e=>{let o=performance.now();ma(WtA,YK(a=>a-o{var e;return!((e=this._videoTrack)==null||!e.muted||document.hidden)}),Bl(()=>{this.context.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var A;(A=this._subscription)==null||A.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(A){return this.putCanvasIntoDom(),super.render(A)}render2d(A){return this.putCanvasIntoDom(),super.render2d(A)}close(){var A,e;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(e=this._canvasContainer)==null||e.remove()}},ZtA=class extends KK{render(A){var e;let o=!((e=this.input)==null||!e.requestFrame(A));if(this.context._canvas2d){let a=this.context._canvas2d.getContext("2d");a.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),a.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(AC.RENDER,this.context._canvas2d)}else this.emit(AC.RENDER,this.context._canvas);return o}},XtA=class extends KK{constructor(A,e,o){super(A,{name:"smallDestination",logger:o}),this.resolution=e}resize(A,e){let o,a=A*e,c=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(e," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),a>c?o=a/c:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(e," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=a/19200),super.resize(A/Math.sqrt(o),e/Math.sqrt(o))}},L5=class extends AC{constructor(A,e){super(A,mi({name:"imageSource"},e)),Y(this,"_lastImage"),Y(this,"_totalFrames",0),Y(this,"_autoResize",!1),Y(this,"_canvasRendered"),Y(this,"videoCallbackId",0),Y(this,"waitingFirstFrame",!0),Y(this,"shouldUpdate",!0),this._autoResize=e?.autoResize!==!1,Zd===16&&(this._canvasRendered=EQ(),ma(this._canvasRendered,FK(this._image),$2(o=>o instanceof HTMLCanvasElement?ca(o,"rendered"):xK()),EE(ca(this,"closed")),Bl(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),jp()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((e,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,e){var o;let{width:a,height:c}=this,{image:d}=this;if(d instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:a,videoHeight:c}=d,!a||!c)return!1;d.width=a,d.height=c}else if(d instanceof HTMLImageElement||d instanceof ImageData||d instanceof ImageBitmap){if({width:a,height:c}=d,d!==this._lastImage)this._lastImage=d;else if(a===this.width&&c===this.height)return!0}else d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?({width:a,height:c}=d,this._lastImage=d):typeof VideoFrame<"u"&&d instanceof VideoFrame&&({displayWidth:a,displayHeight:c}=d,(o=this._lastImage)==null||o.close(),this._lastImage=d);if(!this._autoResize)return!0;if(this.width===a&&this.height===c&&this.totalFrames){if(e){this.useTexture();let C=this.context.ctx;C.texSubImage2D(C.TEXTURE_2D,0,0,0,C.RGBA,C.UNSIGNED_BYTE,d)}}else{if(e){this.useTexture();let C=this.context.ctx;C.texImage2D(C.TEXTURE_2D,0,C.RGBA,C.RGBA,C.UNSIGNED_BYTE,d)}this.resize(a,c)}return!0}get image(){return this._image}set image(A){var e;(e=this._canvasRendered)==null||e.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},U5=class extends L5{constructor(A,e,o){super(A,o),this._player=e,this.name="videoPlayerSource",ma(ca(this._player,fo.PLAYER_STATE_CHANGED),EE(ca(this,"closed")),JM(a=>{let{state:c}=a;return c==="PLAYING"}),Bl(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},I_=class extends U5{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,e,o){super(A,new vo({id:o.name,track:e,muted:!0,container:null,objectFit:"contain",log:o.logger}),o),this.name="videoTrackSource",this._player.play()}replaceTrack(A){this.waitingFirstFrame=!0,this._player.setTrack(A),this._player.play()}close(){super.close(),this._player.stop()}},$tA=class extends AC{constructor(A,e,o){super(A,Qo(mi({name:"textSource"},o),{create2d:!0})),Y(this,"hasChange",!0),Y(this,"content",""),this.ctx2d.textBaseline="top",this.content=e.content||"",e.font&&(this.font=e.font),e.color&&(this.color=e.color)}set font(A){this.ctx2d&&(this.ctx2d.font=A,this.hasChange=!0)}get font(){var A;return((A=this.ctx2d)==null?void 0:A.font)||""}set color(A){this.ctx2d&&(this.ctx2d.fillStyle=A,this.hasChange=!0)}get color(){var A;return((A=this.ctx2d)==null?void 0:A.fillStyle)||""}render2d(A){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(A){return!1}resize(A,e){if(!this.ctx2d)return;let{color:o,font:a}=this;super.resize(A,e),this.color=o,this.font=a}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1.2;if(!this.ctx2d)return;let a=this.ctx2d.measureText(this.content);e+=a.fontBoundingBoxAscent||a.actualBoundingBoxAscent||0;let c=this.font.match(/(\d+)px/),d=(c?parseInt(c[1],10):16)*o,C=this.content.split(` -`);for(let y=0;y0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aL._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",bb),!this.ctx)throw new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,` + `,o.onclick=this.onQuestionClick.bind(this);let a=document.createElement("div");a.className=Z,a.innerText="".concat(Wd()?"详情 >":"Detail >"),a.onclick=this.onCollapseClick.bind(this);let l=A.content.firstChild,d=l.querySelector(".".concat(c_));return d.appendChild(a),d.appendChild(o),d.appendChild(e),l}addDiaLog(){yi()||(bt=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(YM)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",pA.info("show autoplay dialog"),sn.uploadEvent({log:_e}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,bt=!1),Oc=null}onConfirm(){pA.warn("confirm clicked, try resume stream"),F.emit(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){let A=this._dialogNode.querySelector(".".concat(bA));A.style.visibility="".concat(this._showDetail?"hidden":"visible"),A.style.height="".concat(this._showDetail?0:"fit-content"),this._showDetail=!this._showDetail,this._isCollapseClicked||sn.uploadEvent({log:Fe}),this._isCollapseClicked=!0}onQuestionClick(){window.open(Ti,"_blank"),this._isQuestionClicked||sn.uploadEvent({log:nt}),this._isQuestionClicked=!0}},Oc=null;function HC(){Oc||(Oc=new sa)}var Ci,Ro=class tX extends JC{constructor(e){super(e,YA.VIDEO),Y(this,"stat",{}),Y(this,"_calculateTimeout",-1),Y(this,"viewMirror",!1),Y(this,"objectFit","cover"),Y(this,"container"),Y(this,"canvas"),Y(this,"shouldRenderAlpha",!1),Y(this,"_preSize",{width:0,height:0}),Y(this,"posterImg"),Y(this,"pipWindow"),Y(this,"enterPIPPromise"),Y(this,"_originContainerPosition"),Y(this,"_isResettingSrcObject",!1),Y(this,"_wrapper",null),Y(this,"_useWrapper",!1),Y(this,"_isFirstFrameRenderEmitted",!1),this.mode=e.canvas?1:0,this.container=e.container,this.canvas=e.canvas,Ke(e.viewMirror)||(this.viewMirror=e.viewMirror),Ke(e.objectFit)||(this.objectFit=e.objectFit),this.initializeElement()}get isPlaying(){var e;return!(this._state!=="PLAYING"||this.element&&this.element.paused)&&((e=this.track)==null?void 0:e.readyState)==="live"&&!this.track.muted}initializeElement(){let e=document.createElement(YA.VIDEO);this.track&&this.mode!==2&&(e.srcObject=new MediaStream([this.track])),e.muted=!0,e.setAttribute("id","video_".concat(this.id)),e.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),e.setAttribute("autoplay","autoplay"),e.setAttribute("playsinline","playsinline"),this.element=e,Ha&&(e.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(e)}_bindFirstFrameRenderEvent(e){let o=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;let a=e.videoWidth||0,l=e.videoHeight||0;this._log.info("first frame render: ".concat(a,"x").concat(l)),this.emit(yo.FIRST_FRAME_RENDER,{width:a,height:l})};typeof e.requestVideoFrameCallback=="function"?e.requestVideoFrameCallback(o):e.addEventListener("loadeddata",o,{once:!0})}get styleAttribute(){let e=this._useWrapper?"grid-area:1/1;width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";"):"width:100%;height:100%;object-fit:".concat(this.objectFit,";").concat(this.shouldRenderAlpha?"":"background-color:black",";");return this.viewMirror&&(e+="transform:scaleX(-1);"),e}setLiveMode(e){if(this._useWrapper!==e&&(this._useWrapper=e,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(e){let o=this._getOrCreateWrapper();o.insertBefore(this.elementToRender,o.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(e){if(this.container===e)return;let o=this._wrapper,a=this.container;this.container=e,this._pausedRetryCount=_p,this.track&&this.elementToRender&&this._appendToWrapper(),o&&a&&a!==this.container&&o.isConnected&&o.children.length===0&&o.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let e=this.container.querySelector("[data-trtc-video-wrapper]");return e||(e=document.createElement("div"),e.setAttribute("data-trtc-video-wrapper","true"),e.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(e)),this._wrapper=e,e}_appendToWrapper(e){let o=e??this.elementToRender;if(this.container&&o)if(this._useWrapper){let a=this._getOrCreateWrapper();a.insertBefore(o,a.firstChild)}else this.container.appendChild(o)}bindElementEvents(){let e=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),e&&e.add(YA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(YA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(YA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(YA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(e){var o;return e.type===YA.MUTE&&((o=this.stat)!=null&&o.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(e)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(yo.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(yo.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(yo.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var o,a,l,d,h,y;if(this.mode===2)return;super.handleElementEvent(e);let S=e.type,k=this.isPictureInPicture(),V=this.isFullscreen(),J=e.isTrusted&&(k&&Bg||V);if(S===YA.PLAYING&&J&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(V?"fullscreen":"pip")),this.emit(yo.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),S===YA.PAUSE&&(J&&(this._log.warn("user pause in ".concat(V?"fullscreen":"pip")),this.emit(yo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn("".concat(this.kind," player has been remove, element ID: ").concat(this.container.id)),OC(500).then(()=>{var cA;(cA=this.container)!=null&&cA.isConnected&&(this._pausedRetryCount=_p,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!yi()&&!this.isPausedByUserCall&&!J&&(this._log.info("[".concat(_p-this._pausedRetryCount+1,"/").concat(_p,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),eg&&!J&&(this._interval=Gr.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){let cA=this.element.style.transform;S===YA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=cA.replace("scaleX(-1)",""):S===YA.LEAVE_PICTURE_IN_PICTURE&&!cA.includes("scaleX")&&(this.element.style.transform="".concat(cA," scaleX(-1)"))}S===YA.RESIZE&&(this._preSize.height!==((o=this.element)==null?void 0:o.videoHeight)||this._preSize.width!==((a=this.element)==null?void 0:a.videoWidth))&&(this._log.info("video size changed to ".concat((l=this.element)==null?void 0:l.videoWidth,"x").concat((d=this.element)==null?void 0:d.videoHeight)),this._preSize.height=((h=this.element)==null?void 0:h.videoHeight)||0,this._preSize.width=((y=this.element)==null?void 0:y.videoWidth)||0,this.emit(yo.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),S===YA.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(yo.LEAVE_PICTURE_IN_PICTURE)),S===YA.ENTER_PICTURE_IN_PICTURE&&this.emit(yo.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Ha&&ay&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(e=>{this._log.warn("play failed after reset srcObject",e)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;var a,l;this.canvas!==e&&((a=this.canvas)==null||a.remove(),e?.setAttribute("style",this.styleAttribute),this.canvas=e,this.mode=e?o:0,this.mode===2&&this.setTrack(e.captureStream().getVideoTracks()[0]),e?((l=this.element)==null||l.remove(),this._appendToWrapper(e)):this.element&&this._appendToWrapper(this.element))}setAttr(e){let o=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},e);o.style=Object.assign({width:"100%",height:"100%"},o.style),super.setAttr(o)}get mirror(){return this.viewMirror}setRect(e,o){this.elementToRender&&(this.elementToRender.style.width="".concat(e,"px"),this.elementToRender.style.height="".concat(o,"px"))}setViewMirror(e){this.elementToRender&&(this.elementToRender.style.transform=e?"scaleX(-1)":""),this.viewMirror=e}setObjectFit(e){this.elementToRender&&(this.elementToRender.style.objectFit="".concat(e)),this.objectFit=e}setPoster(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new Promise(a=>{if(!this.element||(this._log.info("setPoster",e.slice(0,10)),e===""?this.element.removeAttribute("poster"):this.element.poster=e,!o||!Bg&&!or))return a();if(e==="")return this.removePosterImg(),a();if(this.posterImg)return a();let l=document.createElement("img");l.src=e;let d=window.getComputedStyle(this.element),h=d.objectFit||this.objectFit,y=1;if(this._useWrapper){let S=parseInt(d.zIndex,10);isNaN(S)||(y=S+1)}l.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(y,";width:100%;height:100%;object-fit:").concat(h,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(h,";"),l.onload=()=>WA(this,null,function*(){try{l.decode&&(yield l.decode()),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=l;let S=this._useWrapper?this._wrapper:this.container;S?.appendChild(l),uM()&&Zd<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(S){this._log.warn("decode poster image error",S)}return a()}),l.onerror=()=>(this._log.warn("load poster image error"),a())})}removePosterImg(){this.posterImg&&(uM()&&Zd<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!Ke(this._originContainerPosition)&&this.container.style.position==="relative"&&(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var e;return!!this.posterImg||!((e=this.element)==null||!e.getAttribute("poster"))}pause(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return WA(this,null,function*(){GI(tX.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(ay||e&&(or||Bg))&&(yield this.setPoster(this.getVideoFrame(),!0))})}resume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return super.resume(e).then(()=>{var o;(this.posterImg||(o=this.element)!=null&&o.poster)&&this.setPoster("",!0)})}doResume(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this.isPaused&&e&&this.element&&this.track&&ay&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;var o;this.isPictureInPicture()&&this.exitPictureInPicture().catch(a=>{}),this.isFullscreen()&&this.exitFullscreen().catch(a=>{}),this.element&&(this.element.removeEventListener(YA.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(e),(o=this.canvas)==null||o.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(e){if(Ke(e?.isLiveStream)||this.setLiveMode(e.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){let o=this._getOrCreateWrapper();this.elementToRender.parentElement!==o&&o.insertBefore(this.elementToRender,o.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(e){e!==this.track&&(this.unbindTrackEvents(),this.track=e,this.emit(yo.MEDIA_TRACK_CHANGED,e),e!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([e]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";let e=document.createElement("canvas");return e.width=this.element.videoWidth,e.height=this.element.videoHeight,e.getContext("2d").drawImage(this.element,0,0),e.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(Zp()&&this.element&&this._calculateTimeout<0){let e=0,o=null,a=(l,d)=>{this.stat.width=d.width,this.stat.height=d.height,o&&(this.stat.fps=Math.round((d.presentedFrames-o.presentedFrames)/(l-e)*1e3)),e=l,o=d,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var h;return(h=this.element)==null?void 0:h.requestVideoFrameCallback(a)},2e3))};this.element.requestVideoFrameCallback(a)}}catch(e){this._log.warn("init stat failed",e)}}enterFullscreen(){return WA(this,null,function*(){let e=this.elementToRender;if(!e)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(eg&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{yield this.exitPictureInPicture()}catch(o){this._log.warn("exit pip failed before fullscreen:",o)}}try{if(e.requestFullscreen)yield e.requestFullscreen();else if(e.webkitRequestFullscreen)yield e.webkitRequestFullscreen();else if(e.webkitEnterFullscreen)yield e.webkitEnterFullscreen();else if(e.mozRequestFullScreen)yield e.mozRequestFullScreen();else{if(!e.msRequestFullscreen)throw new Error("Fullscreen API not supported");yield e.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(o){throw this._log.error("failed to enter fullscreen:",o),o}})}exitFullscreen(){return WA(this,null,function*(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)yield document.exitFullscreen();else if(document.webkitExitFullscreen)yield document.webkitExitFullscreen();else if(document.mozCancelFullScreen)yield document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");yield document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(e){throw this._log.error("failed to exit fullscreen:",e),e}})}isFullscreen(){let e=this.elementToRender;return!!e&&(this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===e)}toggleFullscreen(){return WA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return WA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return WA(this,null,function*(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");let{element:e}=this;if(e.requestPictureInPicture){this._log.info("requestPictureInPicture");let o=yield e.requestPictureInPicture();return this.pipWindow=o,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),o}if(e.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),yield e.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(e){throw this._log.error("failed to enter pip:",e.name,e.message),e}})}exitPictureInPicture(){return WA(this,null,function*(){var e;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)yield document.exitPictureInPicture(),this.elementToRender===this.canvas&&((e=this.element)==null||e.remove(),this._pausedRetryCount=_p,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");yield this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(o){throw this._log.error("failed to exit pip:",o),o}})}isPictureInPicture(){if(!this.element)return!1;let{element:e}=this;return document.pictureInPictureElement?document.pictureInPictureElement===e:!!e.webkitPresentationMode&&e.webkitPresentationMode==="picture-in-picture"}togglePictureInPicture(){return WA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Vg(A,e){return WA(this,null,function*(){if(!A.audioWorklet)return Promise.reject("audioWorklet is not supported");try{yield A.audioWorklet.addModule(e),pA.info("worklet addModule success")}catch(o){throw pA.info("worklet addModule catch error. ".concat(o.message)),o}})}typeof AudioContext<"u"?Ci=AudioContext:typeof webkitAudioContext<"u"?Ci=webkitAudioContext:typeof mozAudioContext<"u"&&(Ci=mozAudioContext);var Un,hu=1500,$d=-1,Am=0,rd=-1,FI=!1,X2=0,l_=-1,tL=-1;(function A(){try{if(Un)return;(Un=new Ci({sampleRate:48e3})).onstatechange=()=>{pA.info("context state: ".concat(Un.state).concat(Un.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),I_()},clearTimeout($d)}catch(e){pA.error("initAudioContext failed: ".concat(e," typeof AudioContextClass: ").concat(typeof Ci)),$d=setTimeout(A,1e3)}})();var I_=()=>{Un.state==="suspended"?(Am=ko(),rd===-1&&(rd=setTimeout(()=>{Un.state==="suspended"&&(FI=!0,F.emit("155",{isSuspended:!0}))},hu)),iL(),document.addEventListener("click",I_)):Un.state==="interrupted"?iL():(Am&&(si.addNumber({key:507800,value:ko()-Am,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),Am=0),rd!==-1&&(clearTimeout(rd),rd=-1,FI&&(FI=!1,F.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",I_),document.removeEventListener("click",I_))},HK=0,qK=-1;function iL(){return new Promise((A,e)=>{if(Un.state==="running")return A();Date.now()-HK<1e3?(clearTimeout(qK),qK=setTimeout(()=>{HK=Date.now(),Un.resume().then(A,e)},1e3)):(clearTimeout(qK),HK=Date.now(),Un.resume().then(A,e))}).catch(A=>{pA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",I_)})}document.addEventListener("click",I_);var OI=A=>Un,PI=class{constructor(A){this.name=A,Y(this,"node"),Y(this,"node2"),Y(this,"pre",new Set),Y(this,"next",new Set),Y(this,"context"),Y(this,"connectedNodes",new Set),Y(this,"nextInputChannelMap",new Map),Y(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(A){this._channelCount=A,this.setChannelCount(this.node,A),this.setChannelCount(this.node2,A),this.next.forEach(e=>e.channelCount=A)}setChannelCount(A,e){!A||A instanceof ScriptProcessorNode||(A.channelCountMode="explicit",A.channelCount=e||this.channelCount||1)}setContext(A){this.context=A,this.node&&A.addMixWeight()}removeContext(){var A;this.node&&((A=this.context)==null||A.reduceMixWeight()),delete this.context}replaceNode(A){var e;if(A!==this.node)try{this.node?this._disconnect():(e=this.context)==null||e.addMixWeight(),this.node=A,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(o){pA.error(o)}}setNode(A,e){var o;if(!this.node)try{(o=this.context)==null||o.addMixWeight(),this.node=A,this.setChannelCount(this.node),e&&(this.node2=e,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),si.addSuccessEvent({key:502701})}catch(a){pA.error(a),si.addFailedEvent({key:502701,error:a})}}deleteNode(){var A;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(A=this.context)==null||A.reduceMixWeight(),this.preNodeReconnect(),si.addSuccessEvent({key:502702})}catch(e){pA.error(e),si.addFailedEvent({key:502702,error:e})}}preNodeReconnect(){this.pre.forEach(A=>{A.node?A.reconnect():A.preNodeReconnect()})}connectNext(A){this.next.forEach(e=>{let o=this.nextInputChannelMap.get(e);A._connect(e.node,o)||e.connectNext(A)})}_connect(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return!(!this.node||!A)&&((this.node2||this.node).connect(A,0,e),this.connectedNodes.add(A),!0)}_disconnect(){this.connectedNodes.forEach(A=>{var e;return(e=this.node2||this.node)==null?void 0:e.disconnect(A)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return this.next.add(A),A.pre.add(this),this.nextInputChannelMap.set(A,e),A}},KeA=class extends PI{constructor(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:256;super(),this.fftSize=A,Y(this,"dataArray",new Uint8Array(0))}setNode(A){A.fftSize=this.fftSize,this.dataArray=new Uint8Array(A.frequencyBinCount),super.setNode(A)}getByteTimeDomainData(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var A;return(A=this.node)==null||A.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){let A=this.getByteTimeDomainData(),e=0,o=0,a="M".concat(e,",").concat(o);for(let l=0;l0&&arguments[0]!==void 0?arguments[0]:1;this.mixWeight+=A,this.mixWeight-1==A+1>>1&&this.mixOnChange()}reduceMixWeight(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.addMixWeight(-A)}close(){this.inputs.forEach(A=>A.remove())}get mixTrack(){return this.destination.stream.getAudioTracks()[0]}},m5=new WeakMap;function $2(A){try{let e=m5.get(A);if(e)return e;let o=OI();if(A instanceof HTMLAudioElement)e=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;e=o.createMediaStreamSource(new MediaStream([A]))}return m5.set(A,e),e}catch(e){if(!(or&&e instanceof Error&&e.name==="NotSupportedError"))throw e;pA.warn(e)}}var A1=class am{constructor(e){Y(this,"_volume",0),Y(this,"_volumeDb",0),Y(this,"_log"),Y(this,"_scriptProcessorNode",null),Y(this,"_audioWorkletNode",null),Y(this,"_interval",200),Y(this,"ready",this.preload());let{log:o}=e;this._log=o,F.on(nA.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-am.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!am.workletReady){let e='class VolumeMeterWorklet extends AudioWorkletProcessor{constructor(){super(),this.volume=0,this.intervalTime=200,this.tick=200,this.isStop=!1,this.cache=[],this.sentFirstInfo1=!1,this.unmute=!1,this.port.onmessage=t=>{var e=t.data;switch(e.name){case"chunk":this.cache.push(...e.data),this.sentFirstInfo1||(this.port.postMessage({cl:e.data.length}),this.sentFirstInfo1=!0);break;case"setIntervalTime":this.intervalTime=e.intervalTime;break;case"unmute":this.unmute=!0;break;case"stop":this.isStop=!0}}}process(t,s){t=t[0],s=s[0];if(t||s){if(this.isStop)return!1;var i=s&&s[0]?s[0].length:0,h=this.cache.length,a=(it+e*e,0)/a.length;this.volume=e,this.tick-=a.length,this.tick<0&&(this.tick+=this.intervalTime/1e3*sampleRate,this.port.postMessage({volume:this.volume,volumeDb:Math.max(10*Math.log10(s)+100,0)/100,cacheLen:h,outputLen:i}))}}return!0}}registerProcessor("volume-meter",VolumeMeterWorklet);';am.workletReady=Vg(am.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return am.workletReady.then(()=>this.initAudioWorklet()).catch(e=>(this._log.error("volumeMeter preload error: ".concat(e)),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(am.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=o=>{am.lastMessageTime=Date.now(),this._volume=o.data.volume||0,this._volumeDb=o.data.volumeDb||0,!e&&o.data.cacheLen&&o.data.outputLen&&(this._log.warn("worklet play success"),e=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(e){this._log.error("volumeMeter init audio worklet error: ".concat(e)),sn.logFailedEvent({userId:this._log.userId,eventType:Ja.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=OI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{am.lastMessageTime=Date.now();let o=e.inputBuffer.getChannelData(0),a=0;for(let l=0;l>2);A.copyTo(o,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:o},[o.buffer]),A.close()}}},e1=f5,WeA=gc(jl(),1),D5=A=>e=>e.deviceId===A,KK=class{constructor(A,e){Y(this,"kind"),Y(this,"type"),Y(this,"devices",[]),this.kind=A,this.type=e}update(A,e){let o=A.filter(a=>a.kind==="".concat(this.kind).concat(this.type.toLocaleLowerCase()));this.devices.length===1&&oL(this.devices[0])||e&&(o.forEach(a=>{if(a.deviceId&&!this.devices.find(D5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Added");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),e.emit(l,a)}}),this.devices.forEach(a=>{if(a.deviceId&&!o.find(D5(a.deviceId))){let l="".concat(this.kind).concat(this.type,"Removed");pA.warn("".concat(l,": ").concat(JSON.stringify(a))),e.emit(l,a)}})),this.devices=o}hasDevice(A){return!!this.devices.find(e=>e.deviceId===A)}},zeA=class extends WeA.EventEmitter{constructor(){super(),Y(this,"audioInputs",new KK(YA.AUDIO,"Input")),Y(this,"videoInputs",new KK(YA.VIDEO,"Input")),Y(this,"audioOutputs",new KK(YA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||Gr.run("interval",()=>{this.update()},{delay:1e4}))}init(){t1().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return WA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield t1(e);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=OI())==null?void 0:A.outputLatency)>150)return!0;let e=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(o=>e.some(a=>o.label.toLowerCase().includes(a)))||this.audioInputs.devices.some(o=>e.some(a=>o.label.toLowerCase().includes(a)))}},Pc=r0||n0?null:new zeA;function oL(A){return A.deviceId===A.groupId&&A.groupId===""}function t1(){return WA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(Cu()||!Lk())return[];let e=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(e.forEach(a=>{oL(a)&&(a.kind===YA.AUDIO_INPUT?o.audio=!0:a.kind===YA.VIDEO_INPUT&&(o.video=!0))}),A===2&&(o.audio=!1),A===1&&(o.video=!1),o.audio||o.video){let a;try{a=yield navigator.mediaDevices.getUserMedia(o),o.audio&&iL()}catch(l){pA.debug("capture before getDevices failed: ",l)}e=yield navigator.mediaDevices.enumerateDevices(),a?.getTracks().forEach(l=>l.stop())}}return e.map((o,a)=>{let l={kind:o.kind,deviceId:o.deviceId,groupId:o.groupId,label:o.label||"".concat(o.kind,"_").concat(a)};return o.deviceId.length>0&&jK.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(l.getCapabilities=()=>o.getCapabilities()),l})}()})}function em(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Pc.update(A?1:0).then(e=>e.audioInputs.devices)}function tm(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Pc.update(A?2:0).then(e=>e.videoInputs.devices)}var S5=!1;function HM(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return WA(this,null,function*(){return(eg||Bg)&&(A=!1),Pc.update(A?1:0).then(e=>e.audioOutputs.devices)})}var jK=new Set;function M5(A,e){return WA(this,null,function*(){let o=(yield em()).find(a=>a.deviceId===AM);return!e&&o?.groupId===A||o?.groupId===A&&o.label===e})}var i1,ZeA=class extends Q5{constructor(A){super(),this.log=A,Y(this,"volumeMeter"),Y(this,"volumeMeterAfter3A"),Y(this,"volumeDestination"),Y(this,"analyser",new KeA),this.volumeMeter=new y5({log:this.log}),this.volumeMeterAfter3A=new y5({log:this.log}),this.volumeDestination=new PI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},WK=class iX extends JC{constructor(e){super(e,YA.AUDIO),Y(this,"_outputDeviceId"),Y(this,"_floatVolume",1),Y(this,"_destination"),Y(this,"pipeline"),Y(this,"volumeMeterMode","worklet"),Y(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=e.enableVolumeControlInIOS,this.mode=0,e.url&&(this.url=e.url),this.pipeline=new ZeA(this._log)}setTrack(e){}get duration(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.duration)||0))}get currentTime(){var e;return Math.floor(1e3*(((e=this.element)==null?void 0:e.currentTime)||0))}set currentTime(e){this.element&&(this.element.currentTime=e/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(e){if((LI==="15.2"||LI==="15.3"||LI==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=i1||new Audio;o.setAttribute("autoplay","autoplay"),o.srcObject=this.getMediaStream(),o.muted=this.muted,this.url&&(o.crossOrigin="anonymous",o.src=this.url),this.element=o,this.setVolume(kn(e)?e/100:this._floatVolume),o===i1&&(i1=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(yo.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return WA(this,null,function*(){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(e?.volume),this._outputDeviceId&&(yield this.setSinkId(this._outputDeviceId)),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(OI().createAnalyser()),function(){WA(this,null,function*(){try{S5||(S5=!0,pA.info("speakers:".concat((yield HM()).map(o=>" ".concat(o.deviceId.slice(0,8),": ").concat(o.label)))))}catch{}})}()}catch(o){throw this._log.warn("audio play error: ".concat(o)),gy(LI,"18.7",!0)&&this.bindAutoPlayEvent(),o}return GI(iX.prototype,this,"play").call(this)}})}stop(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy(),super.stop(e)}setVolume(e){this._floatVolume=e,this.element&&(this.element.volume=e)}setSinkId(e){return WA(this,null,function*(){var o,a;this._outputDeviceId!==e&&(this._outputDeviceId=e),this.element&&this.element.sinkId!==e&&(yield(a=(o=this.element).setSinkId)==null?void 0:a.call(o,e))})}get useDestination(){return!!this.pipeline.stream}setLoop(e){this.element&&(this.element.loop=e)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},XeA=class extends WK{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(yo.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},v5=class extends WK{constructor(A){super(A),Y(this,"_sourceElement"),Y(this,"_output",new PI),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(OI().destination)}write(A){this.pipeline.volumeMeter.write(A)}setTrack(A){var e,o,a;((o=(e=this.element)==null?void 0:e.error)==null?void 0:o.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(yo.MEDIA_TRACK_CHANGED,A),A?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([A]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([A])),this.pipeline.source.channelCount=((a=A.getSettings())==null?void 0:a.channelCount)||1,this.pipeline.replaceSource(A)):this.pipeline.source.deleteNode())}setVolume(A){var e;let o=A<=1&&!uM();if(this._floatVolume!==A||!(o&&((e=this.element)==null?void 0:e.volume)===A||!o&&this.pipeline.volume===A))if(this._floatVolume=A,this.useDestination)this.pipeline.setVolume(A),this._log.info("set pipeline volume: ".concat(A));else if(o)this.element?(this._log.info("set element volume: ".concat(A)),this.element.volume=A):this._log.info("set element volume: no element");else{if(uM()){if(!this.enableVolumeControlInIOS)return;(function(){if(!eg||tL!==-1)return;let a=()=>{ko()-X2<500||(Un&&Un.state==="running"&&Un.currentTime===l_&&(pA.warn("context is fake running, auto resume"),Un.suspend().catch(l=>{pA.warn("context suspend failed: ".concat(l))})),l_=Un.currentTime,X2=ko())};tL=setInterval(()=>{a()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&a()})})()}if(or&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info("start set pipeline volume: ".concat(A)),this.pipeline.setVolume(A),this.element&&!this._sourceElement&&(this._destination||(this._destination=OI().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),Ln(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(a=>{this.emit(yo.AUTOPLAY_FAILED,a)}))}}stop(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.pipeline.destroy();let e=this._sourceElement||this.element;e&&xp&&(i1=e),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},zK=class extends Zs{constructor(A){let{userId:e,sdkAppId:o,mediaType:a,room:l,PlayerClass:d=a===1?v5:Ro}=A;var h;super(),Y(this,"id",PA()),Y(this,"userId",""),Y(this,"isRemote"),Y(this,"mediaType"),Y(this,"room"),Y(this,"user"),Y(this,"_log"),Y(this,"_inputTrack"),Y(this,"_outputTrack"),Y(this,"isPlayCalled"),Y(this,"container",null),Y(this,"player"),Y(this,"subVideoPlayerMap"),Y(this,"muted",!1),Y(this,"abortCtrl"),Y(this,"objectFit","cover"),Y(this,"mirror"),Y(this,"rotation"),Y(this,"isScreen",!1),Y(this,"manager"),Y(this,"trackSettings"),Y(this,"isFirstVideoFrameEmitted",!1),this.userId=e||"",this.mediaType=a,this._log=pA.createLogger({parent:l?.getLogger(),id:"".concat(this.kind[0],"t"),userId:(h=l||this.room)==null?void 0:h.userId,remoteUserId:this instanceof lL?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof lL}),this.player=new d({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:l?.enableVolumeControlInIOS}),this.player.on(yo.PLAYER_STATE_CHANGED,y=>{if(F.emit(nA.PLAYER_STATE_CHANGED,fi({track:this},y)),this.emit("player-state-changed",y),y.state==="PLAYING"&&this.room){let S=!0;for(let{remoteAudioTrack:k,remoteVideoTrack:V,remoteAuxiliaryTrack:J}of[...this.room.remotePublishedUserMap.values()])if(k.isAvailable&&!k.player.isPlaying||V.isAvailable&&!V.player.isPlaying||J.isAvailable&&!J.player.isPlaying){S=!1;break}S&&yi()&&Oc&&Oc.deleteDialog()}}),this.kind===YA.VIDEO&&(this.player.on(yo.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(yo.LOADED_DATA),F.emit(nA.VIDEO_LOADED_DATA,{track:this})}),this.player.on(yo.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(yo.LOADED_META_DATA)}),this.player.on(yo.MEDIA_TRACK_CHANGED,y=>{var S;(S=this.subVideoPlayerMap)==null||S.forEach(k=>k.setTrack(y))}),this.player.on(yo.RESIZE,y=>{this.emitFirstVideoFrameEvent(yo.RESIZE),this.emit("video-size-changed",fi({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},y))}),this.player.on(yo.FIRST_FRAME_RENDER,y=>{this.emit("first-frame-render",po(fi({},y),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(yo.ERROR,this.onPlayerError.bind(this)),this.player.on(yo.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||pA}get kind(){return this.mediaType===1?YA.AUDIO:YA.VIDEO}get isAudio(){return this.kind===YA.AUDIO}get strMediaType(){return this.mediaType===4?YA.VIDEO:this.mediaType===2?YA.SCREEN:YA.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}play(A,e){return WA(this,null,function*(){let o=wa(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(e))),e&&!Ke(e.muted)&&this.setPlayerMute(e.muted),e&&!Ke(e.objectFit)&&(this.objectFit=e.objectFit),void(this.player instanceof Ro&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(wa(A)&&A.length>=1&&this.container&&A.includes(this.container)&&this.container.contains(this.player.elementToRender)?(A.splice(A.indexOf(this.container),1),A.unshift(this.container)):(this.container=o,this.player.setContainer(o))),wa(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),e))));if(e&&!Ke(e.muted)?this.setPlayerMute(e.muted):(!this.isRemote||this.kind===YA.VIDEO)&&this.setPlayerMute(!0),e&&!Ke(e.objectFit)&&(this.objectFit=e.objectFit),this.player instanceof Ro&&(Ke(e?.isLiveStream)||this.player.setLiveMode(e.isLiveStream),this.player.setObjectFit(this.objectFit),e&&!Ke(e.poster)&&this.player.setPoster(e.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Ro&&this.player.setContainer(o)),F.emit(nA.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info("play with options: ".concat(JSON.stringify(e)));try{this.player.setTrack(this.playerMediaTrack),yield this.player.play(e),wa(A)&&A.length>1&&(yield this.playSubContainer(A.slice(1),e))}catch(a){throw this.handleAutoPlayFailed(a),a}}else this.log.info("play has not mediaTrack, abort")})}setMirror(A,e){if(this.isScreen||this.kind!==YA.VIDEO||Ke(A)||A===this.mirror)return;this.mirror=A;let o=this.player;e&&(o=e);let a=this.manager;if(Nr(this.mirror))return o.setViewMirror(this.mirror),void(!this.isRemote&&a&&(a.mirror=!1));switch(this.mirror){case"view":a&&(a.mirror=!1),o.setViewMirror(!0);break;case"publish":a&&(a.mirror=!0),o.setViewMirror(!0);break;case"both":a&&(a.mirror=!0),o.setViewMirror(!1)}}playSubContainer(A,e){return WA(this,null,function*(){if(!this._outputTrack||this.kind===YA.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((a,l)=>{var d;A.find(h=>l===h)||(a.stop(),(d=this.subVideoPlayerMap)==null||d.delete(l))});for(let[a,l]of A.entries()){let d=this.subVideoPlayerMap.get(l);d?e&&(Ke(e.objectFit)||d.setObjectFit(e.objectFit)):this.subVideoPlayerMap.set(l,new Ro({id:this.userId||this.id,track:this.playerMediaTrack,container:l,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:"vp-sub".concat(a+1)})}))}let o=[...this.subVideoPlayerMap.values()];for(let a of o)a.setViewMirror(this.player.mirror),yield a.play()})}setAudioOutput(A){return this.player.setSinkId(A)}setAudioVolume(A){this.player.setVolume(A)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var A;return((A=this.player)==null?void 0:A.getInternalAudioLevel())||0}stop(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info("stop ".concat(this.kind," player")),this.player.stop(ok(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return WA(this,null,function*(){var A;this.isPlayCalled&&(yield(A=this.player)==null?void 0:A.resume())})}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(A){this.muted=A,this._inputTrack&&(this._inputTrack.enabled=!A),this._outputTrack&&(this._outputTrack.enabled=!A),this.emit(A?"mute":"unmute",this),F.emit(A?nA.TRACK_MUTED:nA.TRACK_UNMUTED,{track:this})}setPlayerMute(A){this.player.setMuted(A)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(A){nd(A,A).add(YA.MUTE,this.onTrackMuted).add(YA.UNMUTE,this.onTrackUnmuted).add(YA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===YA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(A){Ln(A)}setInputMediaStreamTrack(A){var e;let o=this._inputTrack;if(A!==o)return this._inputTrack=A,this.trackSettings=(e=A.getSettings)==null?void 0:e.call(A),A.enabled=!this.muted,o&&this.uninstallTrackEvent(o),this.installTrackEvent(A),this.emit("input-media-track-changed",A||null,o||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(A)}setOutputMediaStreamTrack(A){var e;let o=this._outputTrack;this instanceof BQ&&Gp(o)||A!==o&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",A.label):this.log.info("setOutputMediaStreamTrack",(e=A.getSettings)==null?void 0:e.call(A).deviceId,A.label),this._outputTrack=A,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!A),this.emit("output-media-track-changed",A))}setMediaType(A){this.mediaType=A}updatePlayingState(A){var e,o;if(this.isPlayCalled){if(A){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(a=>this.handleAutoPlayFailed(a)),void this.log.info("playing state updated, play ".concat(this.kind))}else if(!this.player.isStopped)return ok(this)&&this.isAudio&&(e=this.user)!=null&&e.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(ok(this)?this.jitterBufferDelay:0),void this.log.info("playing state updated, stop ".concat(this.kind)))}this.log.debug("updatePlayingState abort ".concat(this.isPlayCalled," ").concat(A," ").concat(this.player.isStopped))}handleAutoPlayFailed(A){return WA(this,null,function*(){var e;this.log.warn("handleAutoPlayFailed",A);let o=()=>{this.resume().then(()=>{document.removeEventListener("click",o,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((Fp||sQ)&&(yield OC(100),(e=this.player)!=null&&e.isPlaying))return;HC()}else document.addEventListener("click",o,!0);F.once(nA.LOCAL_TRACK_CAPTURE_SUCCESS,a=>{let{track:l}=a;l.kind==="audio"&&yi()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof Ro?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(A){var e,o,a;if(this.isFirstVideoFrameEmitted)return;let l=(e=this.mediaTrack)==null?void 0:e.getSettings(),d=l?.width||((o=this.player.element)==null?void 0:o.videoWidth)||0,h=l?.height||((a=this.player.element)==null?void 0:a.videoHeight)||0;A===yo.RESIZE&&!d&&!h||A===yo.LOADED_META_DATA&&!d&&!h||(A===yo.LOADED_DATA&&!d&&!h&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,tQ(this.rotation)&&([d,h]=[h,d]),this.emit("first-video-frame",{width:d,height:h,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn("".concat(this.kind," track is unable to provide media output"))}onTrackUnmuted(){this._log.info("".concat(this.kind," track is able to provide media output"))}onTrackEnded(){this._log.warn("".concat(this.kind," track ended"))}};hi([lc([],Zs.INIT,{sync:!0})],zK.prototype,"_toInitState");var $eA=Object.prototype.hasOwnProperty,im=function(A){if(A==null)return!0;if(typeof A=="boolean")return!1;if(typeof A=="number")return A===0;if(typeof A=="string"||typeof A=="function"||Array.isArray(A))return A.length===0;if(A instanceof Error)return A.message==="";if(IE(A))switch(Object.prototype.toString.call(A)){case"[object File]":case"[object Map]":case"[object Set]":return A.size===0;case"[object Object]":for(let e in A)if($eA.call(A,e))return!1;return!0}return!1},AtA=IM({retryFunction:function(A){return WA(this,null,function*(){let e=function(d){return{audio:etA(d),video:ttA(d)}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(e)));let o=[],a=[],l=["label","deviceId","groupId"];if(e.audio&&(o=yield em(),pA.info("microphones: ".concat(zd(o.map(d=>po(fi({},d),{groupId:d.groupId.substring(0,8)})),{keysToInclude:l})))),e.video&&(a=yield tm(),pA.info("cameras: ".concat(zd(a,{keysToInclude:l}))),!Nr(e.video)&&e.video.facingMode==="user"&&!e.video.deviceId)){let d=a.filter(h=>!h.label.includes("infrared")).find(h=>h.label.includes("facing front"));d&&(e.video.deviceId=d.deviceId,pA.info("exclude infrared camera: ".concat(JSON.stringify(e))))}try{let d=yield navigator.mediaDevices.getUserMedia(e);return H2&&d.getTracks().forEach(h=>{var y;let S=h.getCapabilities();pA.info("".concat(h.kind," capabilities: ").concat(zd(S,{keysToInclude:Ob}))),!Ke(A.echoCancellation)&&((y=S.echoCancellation)==null?void 0:y.indexOf(A.echoCancellation))===-1&&pA.warn("Invalid argument for 'echoCancellation'. Expected one of [".concat(JSON.stringify(S.echoCancellation),"], but received '").concat(A.echoCancellation,"'"))}),e.audio&&iL(),d}catch(d){let{message:h}=d;throw d.name==="NotFoundError"&&(A.video&&a&&a.length===0&&(h=Xo({key:vo.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(h=Xo({key:vo.MICROPHONE_NOT_FOUND}))),new gi({code:Ct.INITIALIZE_FAILED,name:d.name,message:h,constraint:d.constraint})}})},settings:{retries:3,timeout:500},onError:A=>{let{error:e,retry:o,reject:a,retryFuncArgs:l,retriedCount:d}=A,h=d+1;e.name==="NotReadableError"||e.name==="OverconstrainedError"||e.name==="AbortError"?(h===1?(l[0].video&&(l[0].maxResolution=!1,(!Bg||l[0].width*l[0].height<=2073600)&&l[0].frameRate&&(l[0].frameRate=l[0].frameRate>10?10:5)),l[0].retryWhenExactFailed&&l[0].useExactDeviceId&&(l[0].useExactDeviceId=!1)):h===2?l[0].useDeviceIdOnly=!0:h===3&&!l[0].useExactDeviceId&&(l[0].useTrueAsConstraint=!0),o()):a(e),l[0].microphoneId&&R5(l[0].microphoneId,!1),l[0].cameraId&&R5(l[0].cameraId,!0)},onRetrying:A=>{pA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{sn.logFailedEvent({eventType:Ja.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{sn.logSuccessEvent({eventType:Ja.GET_USER_MEDIA_RETRY}),sn.uploadEvent({log:"stat-".concat(Ja.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function R5(A,e){return WA(this,null,function*(){let o=(e?yield tm():yield em()).find(a=>a.deviceId===A);o&&Ra(o.getCapabilities)&&pA.warn(zd(o.getCapabilities(),{keysToInclude:Ob}))})}function etA(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let e={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!im(A.microphoneId)&&(e.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?e:(kn(A.channelCount)&&(e.channelCount=A.channelCount),(Nr(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(e.echoCancellation=A.echoCancellation),Nr(A.noiseSuppression)&&!A.noiseSuppression&&(e.noiseSuppression=!1),Nr(A.autoGainControl)&&!A.autoGainControl&&(e.autoGainControl=!1),!!im(e)||e)}function ttA(A){if(!A.video)return!1;if(A.useTrueAsConstraint)return!0;let{maxResolution:e=!0}=A,o={};return A.cameraId?o.deviceId=A.useExactDeviceId?{exact:A.cameraId}:A.cameraId:A.facingMode&&(o.facingMode=A.facingMode),A.useDeviceIdOnly&&!im(o)?o:(A.width&&(o.width={ideal:A.width},e&&!or&&(o.width.max=A.width)),A.height&&(o.height={ideal:A.height},e&&!or&&(o.height.max=A.height)),or&&nQ&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!im(o)||o)}var itA=AtA;function w5(A){return jr((e,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;dfunction(){for(var a=arguments.length,l=new Array(a),d=0;d{let A=!1,e=document.visibilityState;return()=>{document.visibilityState!==e&&pA.info("visibility change: ".concat(document.visibilityState)),!A&&(document.addEventListener("visibilitychange",()=>{pA.info("visibility change: ".concat(document.visibilityState)),e=document.visibilityState}),A=!0)}})(),stA=0,T5=class{constructor(A){Y(this,"log"),Y(this,"isRunning",!1),Y(this,"queue",[]);let e="fq".concat(++stA);A&&(e+="|".concat(A)),this.log=pA.createLogger({id:e})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;let l=fi({},A),d=new Promise((h,y)=>{l.resolve=h,l.reject=y});return l.promise=d,e?this.length<=1?this.queue.push(l):(a=(o=this.lastQueueItem)==null?void 0:o.promise)==null||a.then(l.resolve,l.reject):this.queue.push(l),this.log.debug("push ".concat(this.length),A.funcName,A.args),this.isRunning||this.callNext(),d}shift(){let A=this.queue.shift();return this.log.debug("shift ".concat(this.length),A?.funcName,A?.args),A}callNext(){if(this.isRunning||this.length===0)return;let{fn:A,args:e,context:o,resolve:a,reject:l,funcName:d}=this.queue[0];this.log.debug("callNext",this.length,d,e),this.isRunning=!0,A.apply(o,e).then(a,l).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},o1=new WeakMap,s1=new WeakMap;function sL(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return function(e,o,a){let l=a.value;return a.value=function(){let d=o1.get(this)||new T5;for(var h=arguments.length,y=new Array(h),S=0;SS.push(cA)),(y=s1.get(this))==null||y.forEach(cA=>cA?.queue.forEach(CA=>S.push(CA))),S.forEach(cA=>{cA.reject(new gi({code:Ct.API_CALL_ABORTED,message:A}))}),o1.delete(this),s1.delete(this),l.apply(this,V)},a}}function Dy(A,e){return function(o,a,l){let d=l.value,h=y=>A(...y);return l.value=function(){for(var y=arguments.length,S=new Array(y),k=0;kfunction(){let l=A;try{for(var d=arguments.length,h=new Array(d),y=0;y(e?si.addSuccessEvent({key:l,cost:ko()-k}):si.addSuccessEvent({key:l}),V)).catch(V=>{throw si.addFailedEvent({key:l,error:V}),V}):(si.addSuccessEvent({key:l}),S)}catch(S){throw si.addFailedEvent({key:l,error:S}),S}})}var G5={};function tg(){}jh(G5,{Events:()=>Ic,Inspect:()=>My,LastSink:()=>n1,Sink:()=>Ps,Subscribe:()=>r1,TimeoutError:()=>L5,audit:()=>JtA,bindCallback:()=>vtA,bindNodeCallback:()=>RtA,buffer:()=>dtA,bufferCount:()=>EtA,bufferTime:()=>uiA,call:()=>b5,catchError:()=>ez,combineLatest:()=>O5,concat:()=>gtA,concatMap:()=>iiA,concatMapTo:()=>oiA,count:()=>TtA,create:()=>Er,debounce:()=>qtA,debounceTime:()=>KtA,defer:()=>P5,delay:()=>EiA,deliver:()=>xs,dispose:()=>ZK,elementAt:()=>jtA,empty:()=>tj,every:()=>$tA,exhaustMap:()=>giA,exhaustMapTo:()=>ciA,expand:()=>CiA,filter:()=>KM,find:()=>WtA,findIndex:()=>ztA,first:()=>ZtA,fromAnimationFrame:()=>StA,fromArray:()=>QtA,fromEvent:()=>la,fromEventPattern:()=>ptA,fromFetch:()=>mtA,fromIterable:()=>ftA,fromPromise:()=>J5,fromReadableStream:()=>DtA,fromReader:()=>ytA,groupBy:()=>liA,identity:()=>ntA,ignoreElements:()=>ktA,iif:()=>ltA,inspect:()=>k5,interval:()=>V5,last:()=>XtA,map:()=>oj,mapTo:()=>eiA,max:()=>NtA,merge:()=>XK,mergeMap:()=>niA,mergeMapTo:()=>riA,min:()=>GtA,never:()=>wtA,nothing:()=>tg,of:()=>BtA,pairwise:()=>AiA,pipe:()=>ma,race:()=>F5,range:()=>MtA,reduce:()=>H5,retry:()=>piA,scan:()=>j5,setAsapScheduler:()=>htA,share:()=>nL,shareReplay:()=>ctA,skip:()=>FtA,skipUntil:()=>OtA,skipWhile:()=>ij,startWith:()=>$K,subject:()=>hQ,subscribe:()=>Bl,sum:()=>btA,switchMap:()=>g1,switchMapTo:()=>l1,take:()=>E_,takeLast:()=>UtA,takeUntil:()=>dE,takeWhile:()=>LtA,tap:()=>sj,throttle:()=>YtA,throwError:()=>_tA,timeInterval:()=>IiA,timeout:()=>QiA,timer:()=>ej,toPromise:()=>hiA,toReadableStream:()=>BiA,withLatestFrom:()=>utA,zip:()=>ItA});var b5=A=>A(),ntA=A=>A;function ZK(){this.dispose()}var k5=()=>typeof __FASTRX_DEVTOOLS__<"u",rtA=1,My=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let e=new atA(A,this,this.streamId++);return Ic.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},n1=class{constructor(){this.defers=new Set,this.disposed=!1}next(A){}complete(){this.dispose()}error(A){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=tg,this.error=tg,this.next=tg,this.dispose=tg,this.subscribe=tg,this.doDefer()}subscribe(A){return A instanceof My?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(b5),this.defers.clear()}defer(A){this.defers.add(A)}removeDefer(A){this.defers.delete(A)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},Ps=class extends n1{constructor(A){super(),this.sink=A,A.defer(this.bindDispose)}next(A){this.sink.next(A)}complete(){this.sink.complete()}error(A){this.sink.error(A)}},r1=class extends n1{constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:tg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:tg;if(super(),this._next=e,this._error=o,this._complete=a,this.then=tg,A instanceof My){let l={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{Ic.defer(l,0)}),Ic.create(l),Ic.pipe(l),this.sourceId=l.id,this.subscribe(A),Ic.subscribe({id:l.id,end:!0}),e==tg?this._next=d=>Ic.next(l,0,d):this.next=d=>{Ic.next(l,0,d),e(d)},a==tg?this._complete=()=>Ic.complete(l,0):this.complete=()=>{this.dispose(),Ic.complete(l,0),a()},o==tg?this._error=d=>Ic.complete(l,0,d):this.error=d=>{this.dispose(),Ic.complete(l,0,d),o(d)}}else this.subscribe(A)}next(A){this._next(A)}complete(){this.dispose(),this._complete()}error(A){this.dispose(),this._error(A)}};function ma(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;ad(l),A)}function Er(A,e,o){if(k5()){let a=Object.defineProperties(Object.setPrototypeOf(A,My.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:e,writable:!0,configurable:!0},args:{value:o,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ic.create(a);for(let l=0;l{if(d instanceof My){let h=Er(y=>{let S=new A(y,...a);S.sourceId=h.id,S.subscribe(d)},e,arguments);return h.source=d,Ic.pipe(h),h}return h=>d(new A(h,...a))}}}function vy(A,e){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:e}})}var atA=class extends Ps{constructor(A,e,o){super(A),this.source=e,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{Ic.defer(this.source,this.id)})}next(A){Ic.next(this.source,this.id,A),this.sink.next(A)}complete(){Ic.complete(this.source,this.id),this.sink.complete()}error(A){Ic.complete(this.source,this.id,A),this.sink.error(A)}},Ic={addSource(A,e){vy("addSource",{id:A.id,name:A.toString(),source:{id:e.id,name:e.toString()}})},next(A,e,o){vy("next",{id:A.id,streamId:e,data:o&&o.toString()})},subscribe(A,e){let{id:o,end:a}=A;vy("subscribe",{id:o,end:a,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(A,e,o){vy("complete",{id:A.id,streamId:e,err:o?o.toString():null})},defer(A,e){vy("defer",{id:A.id,streamId:e})},pipe(A){vy("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){vy("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=rtA++),vy("create",{name:A.toString(),id:A.id})}},L5=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},U5=class extends n1{constructor(A){super(),this.source=A,this.sinks=new Set}add(A){A.defer(()=>this.remove(A)),this.sinks.add(A).size===1&&(this.reset(),this.subscribe(this.source))}remove(A){this.sinks.delete(A),this.sinks.size===0&&this.dispose()}next(A){this.sinks.forEach(e=>e.next(A))}complete(){this.sinks.forEach(A=>A.complete()),this.sinks.clear()}error(A){this.sinks.forEach(e=>e.error(A)),this.sinks.clear()}};function nL(){return A=>{let e=new U5(A);if(A instanceof My){let o=Er(a=>{e.add(a)},"share",arguments);return e.sourceId=o.id,o.source=A,Ic.pipe(o),o}return Er(e.add.bind(e),"share",arguments)}}function XK(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=new Ps(a),d=e.length;l.complete=()=>{--d===0&&a.complete()},e.forEach(l.bindSubscribe)},"merge",arguments)}function F5(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=new Map;e.forEach(d=>{let h=new Ps(a);l.set(d,h),h.complete=()=>{l.delete(d),l.size===0?a.complete():h.dispose()},h.next=y=>{l.delete(d),l.forEach(S=>S.dispose()),h.resetNext(),h.resetComplete(),h.next(y)}}),e.forEach(d=>l.get(d).subscribe(d))},"race",arguments)}function gtA(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=0,d=e.length,h=new Ps(a);h.complete=()=>{l{let o=new U5(e),a=[];return o.next=function(l){a.push(l),a.length>A&&a.shift(),this.sinks.forEach(d=>d.next(l))},Er(l=>{l.defer(()=>o.remove(l)),a.forEach(d=>l.next(d)),o.add(l)},"shareReplay",arguments)}}function ltA(A,e,o){return Er(a=>A()?e(a):o(a),"iif",arguments)}function O5(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=e.length,d=l,h=l,y=new Array(l),S=()=>{--h===0&&a.complete()};e.forEach((k,V)=>{let J=new Ps(a);J.next=cA=>{d--,J.next=CA=>{y[V]=CA,d===0&&a.next(y)},J.next(cA)},J.complete=S,J.subscribe(k)})},"combineLatest",arguments)}function ItA(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=e.length,d=l,h=new Array(l),y=()=>{--d===0&&a.complete()};e.forEach((S,k)=>{let V=new Ps(a),J=[];h[k]=J,V.next=cA=>{J.push(cA),h.every(CA=>CA.length)&&a.next(h.map(CA=>CA.shift()))},V.complete=y,V.subscribe(S)})},"zip",arguments)}function $K(){for(var A=arguments.length,e=new Array(A),o=0;oEr(function(l){let d=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,h=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length;for(;d1?o-1:0),l=1;lthis.buffer=d,e.complete=tg,e.subscribe(O5(...a))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),EtA=xs(class extends Ps{constructor(A,e,o){super(A),this.bufferSize=e,this.startBufferEvery=o,this.buffer=[],this.count=0,this.startBufferEvery&&(this.buffers=[[]])}next(A){this.startBufferEvery?(this.count++===this.startBufferEvery&&(this.buffers.push([]),this.count=1),this.buffers.forEach(e=>{e.push(A)}),this.buffers[0].length===this.bufferSize&&this.sink.next(this.buffers.shift())):(this.buffer.push(A),this.buffer.length===this.bufferSize&&(this.sink.next(this.buffer),this.buffer=[]))}complete(){this.buffer.length?this.sink.next(this.buffer):this.buffers.length&&this.buffers.forEach(A=>this.sink.next(A)),super.complete()}},"bufferCount"),dtA=xs(class extends Ps{constructor(A,e){super(A),this.buffer=[];let o=new Ps(A);o.next=a=>{A.next(this.buffer),this.buffer=[]},o.complete=tg,o.subscribe(e)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),CtA=function(A,e,o,a){return new(o||(o=Promise))(function(l,d){function h(k){try{S(a.next(k))}catch(V){d(V)}}function y(k){try{S(a.throw(k))}catch(V){d(V)}}function S(k){k.done?l(k.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(k.value).then(h,y)}S((a=a.apply(A,[])).next())})};function hQ(A){let e=arguments,o=nL()(Er(a=>{o.next=l=>a.next(l),o.complete=()=>a.complete(),o.error=l=>a.error(l),A&&a.subscribe(A)},"subject",e));return o.next=tg,o.complete=tg,o.error=tg,o}function P5(A){return Er(e=>e.subscribe(A()),"defer",arguments)}var u_={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},Aj=typeof Promise<"u"?u_.promise:u_.setImmediate?u_.setImmediate:u_.setTimeout,x5=A=>e=>{Aj(()=>A(e))},htA=A=>{typeof A=="function"?Aj=A:u_[A]&&(Aj=u_[A])},Y5=A=>x5(e=>{for(let o=0;!e.disposed&&o{let o=0,a=setInterval(()=>e.next(o++),A);return e.defer(()=>{clearInterval(a)}),"interval"},"interval",arguments)}function ej(A,e){return Er(o=>{let a=0,l=setTimeout(()=>{if(o.removeDefer(d),o.next(a++),e){let h=setInterval(()=>o.next(a++),e);o.defer(()=>{clearInterval(h)})}else o.complete()},A),d=()=>clearTimeout(l);o.defer(d)},"timer",arguments)}function a1(A,e){return o=>{let a=l=>o.next(l);o.defer(()=>e(a)),A(a)}}function ptA(A,e){return Er(a1(A,e),"fromEventPattern",arguments)}function la(A,e){if("on"in A&&"off"in A)return Er(a1(o=>A.on(e,o),o=>A.off(e,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return Er(a1(o=>A.addListener(e,o),o=>A.removeListener(e,o)),"fromEvent",arguments);if("addEventListener"in A)return Er(a1(o=>A.addEventListener(e,o),o=>A.removeEventListener(e,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function J5(A){return Er(e=>{A.then(o=>{e.next(o),e.complete()},e.error.bind(e))},"fromPromise",arguments)}function mtA(A,e){return Er(P5(()=>J5(fetch(A,e))),"fromFetch",arguments)}function ftA(A){return Er(x5(e=>{try{for(let o of A){if(e.disposed)return;e.next(o)}e.complete()}catch(o){e.error(o)}}),"fromIterable",arguments)}function ytA(A){let e=o=>CtA(this,void 0,void 0,function*(){try{if(o.disposed)return;let{done:a,value:l}=yield A.read();if(a)return void o.complete();o.next(l),e(o)}catch(a){o.error(a)}});return Er(o=>{e(o)},"fromReader",arguments)}function DtA(A){return Er(e=>{let o=new AbortController,a=o.signal;e.defer(()=>o.abort("cancelled")),A.pipeTo(new WritableStream({write(l){e.next(l)},close(){e.complete()},abort(l){e.error(l)}}),{signal:a}).then(()=>e.complete(),l=>e.error(l))},"fromReadableStream",arguments)}function StA(){return Er(A=>{let e=requestAnimationFrame(function o(a){A.disposed||(A.next(a),e=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(e))},"fromAnimationFrame",arguments)}function MtA(A,e){return Er(function(o){let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:A,l=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e+A;for(;a2?o-2:0),l=2;l{let h=a.concat(y=>(d.next(y),d.complete()));A.apply(e,h)},"bindCallback",arguments)}function RtA(A,e){for(var o=arguments.length,a=new Array(o>2?o-2:0),l=2;l{let h=a.concat((y,S)=>y?d.error(y):(d.next(S),d.complete()));A.apply(e,h)},"bindNodeCallback",arguments)}function wtA(){return Er(()=>{},"never",arguments)}function _tA(A){return Er(e=>e.error(A),"throwError",arguments)}function tj(){return Er(A=>A.complete(),"empty",arguments)}var rL=class extends Ps{constructor(A,e,o){super(A),this.f=e;let a=()=>{this.sink.next(this.acc),this.sink.complete()};o===void 0?this.next=l=>{this.acc=l,this.complete=a,this.resetNext()}:(this.acc=o,this.complete=a)}next(A){this.acc=this.f(this.acc,A)}},H5=xs(rL,"reduce"),TtA=A=>xs(rL,"count")((e,o)=>A(o)?e+1:e,0),NtA=()=>xs(rL,"max")(Math.max),GtA=()=>xs(rL,"min")(Math.min),btA=()=>xs(rL,"sum")((A,e)=>A+e,0),KM=xs(class extends Ps{constructor(A,e,o){super(A),this.filter=e,this.thisArg=o}next(A){this.filter.call(this.thisArg,A)&&this.sink.next(A)}},"filter"),ktA=xs(class extends Ps{next(A){}},"ignoreElements"),E_=xs(class extends Ps{constructor(A,e){super(A),this.count=e}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),dE=xs(class extends Ps{constructor(A,e){super(A);let o=new Ps(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=ZK,o.subscribe(e)}},"takeUntil"),LtA=xs(class extends Ps{constructor(A,e){super(A),this.f=e}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),UtA=A=>H5((e,o)=>(e.push(o),e.length>A&&e.shift(),e),[]),FtA=xs(class extends Ps{constructor(A,e){super(A),this.count=e}next(A){--this.count===0&&(this.next=super.next)}},"skip"),OtA=xs(class extends Ps{constructor(A,e){super(A),A.next=tg;let o=new Ps(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=ZK,o.subscribe(e)}},"skipUntil"),ij=xs(class extends Ps{constructor(A,e){super(A),this.f=e}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),PtA={leading:!0,trailing:!1},xtA=class extends Ps{constructor(A,e,o){super(A),this.durationSelector=e,this.trailing=o}cacheValue(A){this.last=A,this.disposed&&this.throttle(A)}send(A){this.sink.next(A),this.throttle(A)}throttle(A){this.reset(),this.subscribe(this.durationSelector(A))}next(){this.complete()}complete(){this.dispose(),this.trailing&&this.send(this.last)}},q5=class extends Ps{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:PtA;super(A),this.durationSelector=e,this.config=o,this._throttle=new xtA(this.sink,this.durationSelector,this.config.trailing),this._throttle.dispose()}next(A){this._throttle.disposed&&this.config.leading?this._throttle.send(A):this._throttle.cacheValue(A)}complete(){this._throttle.throttle=tg,this._throttle.complete(),super.complete()}},YtA=xs(q5,"throttle"),VtA={leading:!1,trailing:!0},JtA=A=>xs(q5,"audit")(A,VtA),HtA=class extends Ps{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},K5=class extends Ps{constructor(A,e){super(A),this.durationSelector=e,this._debounce=new HtA(this.sink),this._debounce.dispose()}next(A){this._debounce.dispose(),this._debounce.reset(),this._debounce.last=A,this._debounce.subscribe(this.durationSelector(A))}complete(){this._debounce.complete(),super.complete()}},qtA=xs(K5,"debounce"),KtA=A=>xs(K5,"debounceTime")(e=>ej(A)),jtA=xs(class extends Ps{constructor(A,e,o){super(A),this.count=e,this.defaultValue=o}next(A){this.count--===0&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("not enough elements in sequence"))}},"elementAt"),WtA=A=>e=>E_(1)(ij(o=>!A(o))(e)),ztA=xs(class extends Ps{constructor(A,e){super(A),this.f=e,this.i=0}next(A){this.f(A)?(this.sink.next(this.i++),this.doDefer(),this.complete()):++this.i}},"findIndex"),ZtA=xs(class extends Ps{constructor(A,e,o){super(A),this.f=e,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A,this.doDefer(),this.complete())}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"first"),XtA=xs(class extends Ps{constructor(A,e,o){super(A),this.f=e,this.defaultValue=o,this.index=0}next(A){(!this.f||this.f(A,this.index++))&&(this.defaultValue=A)}complete(){this.defaultValue!==void 0?(this.sink.next(this.defaultValue),super.complete()):this.error(new Error("no elements in sequence"))}},"last"),$tA=xs(class extends Ps{constructor(A,e){super(A),this.predicate=e,this.index=0}next(A){this.predicate(A,this.index++)?this.result=!0:(this.result=!1,this.doDefer(),this.complete())}complete(){this.result!==void 0?(this.sink.next(this.result),super.complete()):this.error(new Error("no elements in sequence"))}},"every"),j5=xs(class extends Ps{constructor(A,e,o){super(A),this.f=e,o===void 0?this.next=a=>{this.acc=a,this.resetNext(),this.sink.next(this.acc)}:this.acc=o}next(A){this.sink.next(this.acc=this.f(this.acc,A))}},"scan"),AiA=xs(class extends Ps{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),W5=class extends Ps{constructor(A,e,o){super(A),this.mapper=e,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},oj=xs(W5,"map"),eiA=A=>xs(W5,"mapTo")(e=>A),aL=class extends Ps{constructor(A,e,o){super(A),this.data=e,this.context=o}next(A){let e=this.context.combineResults;e?this.sink.next(e(this.data,A)):this.sink.next(A)}tryComplete(){this.context.resetComplete(),this.dispose()}},gL=class oX extends Ps{constructor(e,o,a){super(e),this.makeSource=o,this.combineResults=a,this.index=0}subInner(e,o){let a=this.currentSink=new o(this.sink,e,this);this.complete===oX.prototype.complete&&(this.complete=this.tryComplete),a.complete=a.tryComplete,a.subscribe(this.makeSource(e,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},z5=class extends aL{},Z5=class extends gL{next(A){this.subInner(A,z5),this.next=e=>{this.currentSink.dispose(),this.subInner(e,z5)}}},g1=xs(Z5,"switchMap");function c1(A){return(e,o)=>A(()=>e,o)}var l1=c1(xs(Z5,"switchMapTo")),tiA=class extends aL{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},X5=class extends gL{constructor(){super(...arguments),this.sources=[],this.next2=this.sources.push.bind(this.sources)}next(A){this.next2(A),this.subNext()}subNext(){this.next=this.next2,this.subInner(this.sources.shift(),tiA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},iiA=xs(X5,"concatMap"),oiA=c1(xs(X5,"concatMapTo")),siA=class extends aL{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},$5=class extends gL{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,siA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},niA=xs($5,"mergeMap"),riA=c1(xs($5,"mergeMapTo")),aiA=class extends aL{dispose(){this.context.resetNext(),super.dispose()}},Az=class extends gL{next(A){this.next=tg,this.subInner(A,aiA)}},giA=xs(Az,"exhaustMap"),ciA=c1(xs(Az,"exhaustMapTo")),liA=xs(class extends Ps{constructor(A,e){super(A),this.f=e,this.groups=new Map}next(A){let e=this.f(A),o=this.groups.get(e);o===void 0&&(o=hQ(),o.key=e,this.groups.set(e,o),super.next(o)),o.next(A)}complete(){this.groups.forEach(A=>A.complete()),super.complete()}error(A){this.groups.forEach(e=>e.error(A)),super.error(A)}},"groupBy"),IiA=xs(class extends Ps{constructor(){super(...arguments),this.start=new Date}next(A){this.sink.next({value:A,interval:Number(new Date)-Number(this.start)}),this.start=new Date}},"timeInterval"),uiA=xs(class extends Ps{constructor(A,e){super(A),this.miniseconds=e,this.buffer=[],this.id=setInterval(()=>{this.sink.next(this.buffer.concat()),this.buffer.length=0},this.miniseconds)}next(A){this.buffer.push(A)}complete(){this.sink.next(this.buffer),super.complete()}dispose(){clearInterval(this.id),super.dispose()}},"bufferTime"),EiA=xs(class extends Ps{constructor(A,e){super(A),this.buffer=[],this.delayTime=e}dispose(){clearTimeout(this.timeoutId),super.dispose()}delay(A){this.timeoutId=setTimeout(()=>{let e=this.buffer.shift();if(e){let{time:o,data:a}=e;super.next(a),this.buffer.length&&this.delay(Number(this.buffer[0].time)-Number(o))}},A)}next(A){this.buffer.length||this.delay(this.delayTime),this.buffer.push({time:new Date,data:A})}complete(){this.timeoutId=setTimeout(()=>super.complete(),this.delayTime)}},"delay"),ez=xs(class extends Ps{constructor(A,e){super(A),this.selector=e}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),diA=class extends aL{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},CiA=xs(class extends gL{constructor(A,e){super(A,e),this.project=e,this.inners=new Set,this.sourceCompleted=!1}next(A){this.sink.next(A),this.expandValue(A)}expandValue(A){let e=new diA(this.sink,A,this);this.currentSink=e,this.complete=this.tryComplete,e.complete=e.tryComplete,this.inners.add(e),e.subscribe(this.makeSource(A,this.index++))}complete(){this.sourceCompleted=!0,this.checkComplete()}checkComplete(){this.sourceCompleted&&this.inners.size===0&&(this.resetComplete(),super.complete())}tryComplete(){this.sourceCompleted=!0,this.checkComplete()}},"expand"),hiA=()=>A=>new Promise((e,o)=>{let a;new r1(A,l=>a=l,o,()=>e(a))}),BiA=()=>A=>{let e;return new ReadableStream({start(o){e=new r1(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){e.dispose()}})},Bl=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tg,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:tg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:tg;return a=>new r1(a,A,e,o)},sj=xs(class extends Ps{constructor(A,e){super(A),e instanceof Function?this.next=o=>{e(o),A.next(o)}:(e.next&&(this.next=o=>{e.next(o),A.next(o)}),e.complete&&(this.complete=()=>{e.complete(),A.complete()}),e.error&&(this.error=o=>{e.error(o),A.error(o)}))}},"tap"),QiA=xs(class extends Ps{constructor(A,e){super(A),this.timeout=e,this.id=setTimeout(()=>this.error(new L5(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),piA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return e=>{if(e instanceof My){let o=Er(a=>{let l=A,d=new Ps(a);d.error=h=>{l-- >0?d.subscribe(e):a.error(h)},d.sourceId=o.id,d.subscribe(e)},"retry",[A]);return o.source=e,Ic.pipe(o),o}return o=>{let a=A,l=new Ps(o);l.error=d=>{a-- >0?e(l):o.error(d)},e(l)}}},nj=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(nj||{}),cL=class sX extends zK{constructor(e,o){super({mediaType:e,PlayerClass:o}),Y(this,"isRemote",!1),Y(this,"deviceId"),Y(this,"groupId",""),Y(this,"label",""),Y(this,"sourceTrack"),Y(this,"enableAutoSwitchWhenRecapturing",!0),Y(this,"_isRecapturing",!1),Y(this,"_lastRecaptureTime",0),Y(this,"_onMuteTimeoutId",-1),Y(this,"_encodeCheckTimeoutId",-1),Y(this,"recaptureMode",0),Y(this,"profile"),Y(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(e,o){throw new Error("Method not implemented.")}installTrackEvent(e){e.addEventListener(YA.MUTE,this.onTrackMuted),e.addEventListener(YA.UNMUTE,this.onTrackUnmuted),e.addEventListener(YA.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===YA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(YA.MUTE,this.onTrackMuted),e.removeEventListener(YA.UNMUTE,this.onTrackUnmuted),e.removeEventListener(YA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return WA(this,null,function*(){var a,l;let d=this.sourceTrack;try{let h,y=ko();F.emit(nA.LOCAL_TRACK_CAPTURE_START,{track:this}),e.customSource?(h=new MediaStream,h.addTrack(e.customSource)):(o||(a=this.sourceTrack)==null||a.stop(),h=yield itA(e));let S=h.getTracks()[0];return yield this.setInputMediaStreamTrack(S),e.customSource||(this.sourceTrack=S,this.updateDeviceIdInUse(),this.listenDeviceChange()),F.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:ko()-y,profile:this.profile,room:(l=this.manager)==null?void 0:l.room}),h}catch(h){throw F.emit(nA.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:h}),this.log.error("getUserMedia error observed ".concat(h)),h}finally{o&&d?.stop()}})}setOutputMediaStreamTrack(e){var o;if(super.setOutputMediaStreamTrack(e),this.setStateToReady(),this.isPublishing||this.isPublished)return(o=this.room)==null?void 0:o.replaceTrack(this)}get hasFlag(){var e,o;let a=Np(((e=this.room)==null?void 0:e.localPublishFlag)||0,((o=this.room)==null?void 0:o.userId)||"");return this.mediaType===4&&a.hasVideo||this.mediaType===1&&a.hasAudio||this.mediaType===2&&a.hasAuxiliary}publish(e,o){return WA(this,null,function*(){return this.room=e,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=e.userId,this._log.bindParent(e.getLogger()),yield o,this._checkPublishFlag(e)})}_checkPublishFlag(e){return new Promise((o,a)=>WA(this,null,function*(){var l,d,h,y,S;let k=()=>a(new gi({code:Ct.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===Zs.INIT||this.state==="ready")&&k(),ma(la(e,"local-publish-flag-changed"),KM(()=>this.hasFlag),dE(XK(la(this,Zs.INIT),la(this,"ready"))),Bl(o,a,k))),(h=(d=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:d.hadRecentBadUplink)!=null&&h.call(d,2))return o();let V=e.heartbeatCount,J=((S=(y=this.mediaTrack)==null?void 0:y.stats)==null?void 0:S.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>WA(this,null,function*(){var cA,CA,MA,ie,pe,qe,we,Di;if((MA=(CA=(cA=this.room)==null?void 0:cA.networkQuality)==null?void 0:CA.hadRecentBadUplink)!=null&&MA.call(CA,2)||e.heartbeatCount-V<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((ie=this.mediaTrack)!=null&&ie.stats){let Bi=this.mediaTrack.stats.totalFrames||0;Bi-J===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",Bi)}let Le=this.kind===YA.AUDIO,Qt=this.stat.bytesSent>0;if(si[Qt?"addSuccessEvent":"addFailedEvent"]({key:Le?503700:513702}),!Le){let Bi={H264:513704,H265:513705,VP8:513706}[((qe=(pe=this.room)==null?void 0:pe.videoCodec)==null?void 0:qe.toUpperCase())||"H264"];Bi&&si[Qt?"addSuccessEvent":"addFailedEvent"]({key:Bi})}if(!Qt){if(si.addEnum({key:Le?503701:513703,value:Jp()}),sn.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(cQ()||Hp()),userId:this.userId}),this.log.warn(Le?"encode failed":"".concat((Di=(we=this.room)==null?void 0:we.videoCodec)==null?void 0:Di.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield OC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),a(new gi({message:"".concat(this.strMediaType," encode failed"),code:Le?Ct.AUDIO_ENCODE_FAILED:Ct.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),F.emit(nA.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return WA(this,null,function*(){if(this.sourceTrack&&Qy){let{deviceId:e,groupId:o}=this.sourceTrack.getSettings(),{label:a}=this.sourceTrack;(yield function(l){return WA(this,arguments,function(d){let{newDeviceId:h,oldDeviceId:y,oldGroupId:S,oldLabel:k,kind:V}=d;return function*(){return h===y&&(V!==YA.AUDIO||h!==AM||(yield M5(S,k)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=a,o&&(this.groupId=o),t1().then(l=>{let d=l.find(h=>{let y=h.deviceId===e;return o&&(y=y&&h.groupId===o),y});d&&this.emit("2",d)}))}})}setProfile(e){this.log.info("setProfile",e),Object.assign(this.profile,e)}isNeedToRecapture(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return!(!this.deviceId||!this.sourceTrack||this.kind===YA.AUDIO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("mic")||a.includes("麦克风"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(YA.AUDIO_INPUT);return!!jK.has(l)}(this.sourceTrack)||this.kind===YA.VIDEO&&!function(o){if(o instanceof CanvasCaptureMediaStreamTrack||!(o instanceof MediaStreamTrack))return!1;let a=o.label.toLocaleLowerCase();if(a.includes("camera")||a.includes("webcam"))return!0;let l="".concat((o?.getSettings()||{}).deviceId,"_").concat(YA.VIDEO_INPUT);return!!jK.has(l)}(this.sourceTrack)||this._isRecapturing||e&&nQ&&Bg)}onTrackMuted(){if(super.onTrackMuted(),otA(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),tM);this._onMuteTimeoutId=setTimeout(()=>WA(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((eg||Ha)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return WA(this,null,function*(){if(GI(sX.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),tM);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return WA(this,null,function*(){var a;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");let l=this.sourceTrack;o||(a=this.sourceTrack)==null||a.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();let d={useExactDeviceId:!0};if(e==="user"||e==="environment")d.facingMode=e;else{let h;(this.kind==="audio"?yield em():yield tm()).find(y=>y.deviceId===e)&&(h=e),d.deviceId=h}return this.capture(d,o).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),F.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(h=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(h.message)),this.emit("5",h),F.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this,error:h})}).finally(()=>{o&&l?.stop()})})}getRecoverCaptureDeviceId(){return WA(this,null,function*(){let e=this instanceof BQ;if(e&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let a=(IL.get(o)||0)+1;if(IL.set(o,a),a>=3&&this.enableAutoSwitchWhenRecapturing){let l=e?(yield tm()).find(d=>!IL.has(d.deviceId)):(yield em()).find(d=>!IL.has(d.deviceId));l&&(this.log.warn("".concat(o," capture fail ").concat(a," times, change new ").concat(l.deviceId)),o=l.deviceId)}}return o})}stopCapture(){var e;this.sourceTrack&&(this.sourceTrack.stop(),F.emit(nA.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(e=this.manager)==null||e.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};hi([lc(Zs.INIT,"ready",{ignoreError:!0,sync:!0})],cL.prototype,"setStateToReady"),hi([sL()],cL.prototype,"capture"),hi([lc("ready","publish",{ignoreError:!0,success(){F.emit(nA.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(A){var e;(e=this.room)==null||e.localTracks.delete(this);let o="error",a=A instanceof gi?A:A.cause instanceof gi?A.cause:A,l=!1;a instanceof gi&&(a.message.includes("timeout")?o="timeout":a.code===Ct.API_CALL_ABORTED&&(l=!0,o="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:o,error:a}),this.log[l?"info":"error"]("publish failed",a)}}),Sy(521714,!1)],cL.prototype,"publish"),hi([jr(A=>function(){return WA(this,null,function*(){let e=this.state==="publish"?"started":"starting";A.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:e,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)})}),lc([],"ready",{sync:!0})],cL.prototype,"unpublish");var lL=cL,IL=new Map;F.on(nA.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&IL.delete(A.track.deviceId)});var jM=class FL extends lL{constructor(e){super(1,XeA),Y(this,"mediaType",1),Y(this,"volume",0),Y(this,"profile",{echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:48e3,channelCount:1,bitrate:40}),Y(this,"playerMuted",!0),Y(this,"pipeline"),Y(this,"earMonitorGainNode",new PI),Y(this,"_output",new PI),Y(this,"codecPipeline",[]),Y(this,"stat",{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0}),Y(this,"mixedAudioReferenceMap",new Map),Y(this,"isAudioContextLongSuspended",!1),Y(this,"after3aSilenceStartTime",0),Y(this,"_micMuted",!1),Y(this,"_volumeDetectionTrack",null),Y(this,"_volumeDetectionSource",new PI),this.manager=e,this.pipeline=new p5(e),this.pipeline.source.pipeTo(this.player.pipeline.volumeMeter),this.pipeline.gain.pipeTo(this.earMonitorGainNode).pipeTo(this._output),this.pipeline.gain.pipeTo(this.player.pipeline.volumeMeterAfter3A),this._volumeDetectionSource.pipeTo(this.player.pipeline.volumeMeter),this.handleMicrophoneAdded=this.handleMicrophoneAdded.bind(this),this.handleMicrophoneRemoved=this.handleMicrophoneRemoved.bind(this),F.on(nA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return e1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}getAudioLevel(){let e=(this.volume||super.getAudioLevel())*this.captureVolume;return e>1?1:e}getInternalAudioLevelAfter3A(){if(this.pipeline.isProcessEnabled)return this.player.getInternalAudioLevelAfter3A()}updateAfter3aSilenceStartTime(e){Ke(e)||(e!==0||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=ko())}setInputMediaStreamTrack(e){return WA(this,null,function*(){let o=this.trackSettings||{};si.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),si.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),si.addEnum({key:502700,value:0});let{sampleRate:a,channelCount:l}=o;this._log.info("local audio track input ".concat(JSON.stringify({sampleRate:a,channelCount:l}))),this.pipeline.source.channelCount=l||1,this.pipeline.replaceSource(e),yield GI(FL.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(e){return WA(this,arguments,function(o){var a=this;let{deviceId:l,customSource:d,useExactDeviceId:h=!0,retryWhenExactFailed:y}=o,S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let k=yield GI(FL.prototype,a,"capture").call(a,{video:!1,audio:!0,microphoneId:l,echoCancellation:a.profile.echoCancellation,autoGainControl:a.profile.autoGainControl,noiseSuppression:a.profile.noiseSuppression,sampleRate:a.profile.sampleRate,channelCount:a.profile.channelCount,useExactDeviceId:h,retryWhenExactFailed:y,customSource:d},S);return iL(),k}()})}switchDevice(e){return WA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource&&(e!==AM||(yield M5(this.groupId,this.label))))return;try{this.log.info("switchDevice audio to: ".concat(e)),this.sourceTrack&&this.sourceTrack.stop(),yield this.capture({deviceId:e,useExactDeviceId:!0,retryWhenExactFailed:!1}),F.emit(nA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch microphone success")}catch(o){throw this.log.error("switch microphone failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}}})}listenDeviceChange(){Pc&&!Pc.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Pc.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return WA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(nj[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Jg(this.userId,{eventId:2003,param1:6,streamType:1});let a=yield em();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Pc.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Pc.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return WA(this,arguments,function(o){var a=this;let{echoCancellation:l,noiseSuppression:d,autoGainControl:h}=o;return function*(){let y=a.sourceTrack||a.mediaTrack;if(!y)return;let S=y.getConstraints(),k=!1;!Ke(l)&&l!==a.profile.echoCancellation&&(a.profile.echoCancellation=l,S.echoCancellation=l,k=!0),!Ke(d)&&d!==a.profile.noiseSuppression&&(a.profile.noiseSuppression=d,S.noiseSuppression=d,k=!0),!Ke(h)&&h!==a.profile.autoGainControl&&(a.profile.autoGainControl=h,S.autoGainControl=h,k=!0),k&&(or||Bg?yield y.applyConstraints(S).catch(V=>a._log.warn("update3A failed: ",V)):a.deviceId&&(yield a.recapture(a.deviceId,!0)))}()})}get captureVolume(){return this.pipeline.volume}setCaptureVolume(e){this.pipeline.setVolume(e/100),this.pipeline.gain.node&&si.addEnum({key:502700,value:2})}setMute(e,o){var a;this._cleanupVolumeDetectionTrack(),e==="microphone"?(this._micMuted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),((a=this.manager)==null?void 0:a.mixWeight)<=1?(this.muted=!0,this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),this.emit("mute",this),F.emit(nA.TRACK_MUTED,{track:this})):this._outputTrack&&(this._outputTrack.enabled=!0)):e===!0?(this._micMuted=!1,this.muted=!0,this.sourceTrack&&(this.sourceTrack.enabled=!1),this._inputTrack&&(this._inputTrack.enabled=!1),this._outputTrack&&(this._outputTrack.enabled=!1),o&&this._setupVolumeDetectionTrack(),this.emit("mute",this),F.emit(nA.TRACK_MUTED,{track:this})):(this._micMuted=!1,this.muted=!1,this.sourceTrack&&(this.sourceTrack.enabled=!0),this._inputTrack&&(this._inputTrack.enabled=!0),this._outputTrack&&(this._outputTrack.enabled=!0),this.emit("unmute",this),F.emit(nA.TRACK_UNMUTED,{track:this}))}_setupVolumeDetectionTrack(){let e=this.sourceTrack||this.mediaTrack;if(!e)return;this._volumeDetectionTrack=e.clone(),this._volumeDetectionTrack.enabled=!0;let o=$2(this._volumeDetectionTrack);o&&this._volumeDetectionSource.setNode(o)}_cleanupVolumeDetectionTrack(){this._volumeDetectionTrack&&(this._volumeDetectionTrack.stop(),this._volumeDetectionTrack=null),this._volumeDetectionSource.deleteNode()}get isMicMuted(){return this._micMuted}setAudioVolume(e){super.setAudioVolume(0),eg&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(OI().createGain()),this._output.setNode(OI().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!Bg&&!eg)return this.update3A({echoCancellation:e})}addDenoiser(e){var o;td<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(si.addEnum({key:502700,value:1}),this.pipeline.denoiser.setNode(e),this.enableTrackANS(!1))}mixAudioReference(e,o){if(this.mixedAudioReferenceMap.has(o))return;this.log.info("mixAudioReference() => ".concat(o));let a=$2(e);if(!a)return;let l=new PI,d=OI().createGain();d.gain.value=1;let h=new PI;l.pipeTo(h).pipeTo(this.pipeline.mixNode),l.setNode(a),h.setNode(d),this.mixedAudioReferenceMap.set(o,[l,h])}unMixAudioReference(e){let[o,a]=this.mixedAudioReferenceMap.get(e)||[];o&&(this.log.info("unMixAudioReference() => ".concat(e)),o.deleteNode(),a?.deleteNode(),this.mixedAudioReferenceMap.delete(e))}setAudioReferenceVolume(e,o){let[a,l]=this.mixedAudioReferenceMap.get(e)||[];l!=null&&l.node&&(l.node.gain.value=o/100,this.log.info("setAudioReferenceVolume() => ".concat(e," ").concat(l.node.gain.value)))}addAudioProcessor(e,o,a){this.pipeline.silentNode.setNode(a),this.pipeline.mixNode.setNode(o),this.pipeline.aec.setNode(e)}removeDenoiser(e){if(this.pipeline.denoiser.node===e)return this.pipeline.denoiser.deleteNode(),this.enableTrackANS(!0)}removeAudioProcessor(e){this.pipeline.aec.node===e&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode())}close(){this._cleanupVolumeDetectionTrack(),this.mixedAudioReferenceMap.forEach(e=>{let[o,a]=e;o.deleteNode(),a.deleteNode()}),this.mixedAudioReferenceMap.clear(),this.pipeline.remove(),this.earMonitorGainNode.deleteNode(),this._output.deleteNode(),Pc.off("audioInputAdded",this.handleMicrophoneAdded,this),Pc.off("audioInputRemoved",this.handleMicrophoneRemoved,this),F.off(nA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this),super.close()}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return WA(this,null,function*(){try{yield GI(FL.prototype,this,"recapture").call(this,e,o)}catch(a){let l=(yield em()).find(d=>d.deviceId!==e);if(!l)throw a;yield GI(FL.prototype,this,"recapture").call(this,l.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((o,a)=>a?a({frame:o,ntp:Of()}):o,e):e}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}get enableEncryptFrame(){return this.manager&&!!this.manager.encodePipeline[0]}handleAudioContextLongSuspended(e){let{isSuspended:o}=e;if(this.pipeline.isProcessEnabled)if(o){this.isAudioContextLongSuspended=!0,this.log.warn("context has suspended for ".concat(1.5," seconds, change to source audio").concat(xp?"":", non-Safari"));let a=this.sourceTrack||this.mediaTrack;a&&this.setOutputMediaStreamTrack(a)}else this.isAudioContextLongSuspended=!1,this.log.warn("context has resumed, change to processed audio"),this.pipeline.track&&this.setOutputMediaStreamTrack(this.pipeline.track)}setOutputMediaStreamTrack(e){if(this.isAudioContextLongSuspended){let o=this.sourceTrack||this.mediaTrack;o&&(e=o)}super.setOutputMediaStreamTrack(e)}};function I1(A,e){return e+4<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===0&&A.getUint8(e+3)===1?4:e+3<=A.byteLength&&A.getUint8(e)===0&&A.getUint8(e+1)===0&&A.getUint8(e+2)===1?3:0}function tz(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1],o=new DataView(A),a=[],l=0;for(;l0){h=J;break}let y=h===-1?o.byteLength:h,S=y-l,k=new ArrayBuffer(S),V=new DataView(k);for(let J=0;J1&&arguments[1]!==void 0&&arguments[1];this.dataView=A,this.isSEI&&(e?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-2,o=[],a=0;for(let d=A;d<=e;d++){let h=this.dataView.getInt8(d);switch(h){case 0:case 1:case 2:case 3:a===2&&(o.push(3),a=0),h===0?a+=1:a=0,o.push(h);break;default:a=0,o.push(h)}}o.push(this.dataView.getInt8(this.dataView.byteLength-1));let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}removePreventionByte(){let{seiPayloadStartIndex:A}=this,e=this.dataView.byteLength-1,o=[],a=0;for(let d=A;d<=e;d++)switch(this.dataView.getInt8(d)){case 0:a++,o.push(this.dataView.getInt8(d));break;case 3:a!==2&&o.push(this.dataView.getInt8(d)),a=0;break;default:o.push(this.dataView.getInt8(d)),a=0}let l=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,A),...o]).buffer);this.dataView=l}get seiPayloadStartIndex(){let A=6;for(let e=6;e=this.dataView.byteLength?0:31&this.dataView.getUint8(A)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},miA=class{constructor(){Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_seiPayloadType",243)}encodeSEINalu(A){let e=A.byteLength,o=parseInt(String(e/255),10),a=e%255,l=[];l.push(0,0,0,1,6,this._seiPayloadType);for(let h=0;h0&&A.data.byteLength>0){let a=9-this.getNaluCount(A.data);if(a<=0)return 0;let l=o.splice(0,a).reverse().map(this.encodeSEINalu.bind(this)),d=l.reduce((V,J)=>V+J.dataView.byteLength,0),h=new ArrayBuffer(d+A.data.byteLength),y=new DataView(h),S=new DataView(A.data),k=0;for(let V=0;V1&&arguments[1]!==void 0?arguments[1]:4,Ro),Y(this,"profile",fi({},jS)),Y(this,"avoidCropping",!1),Y(this,"_scaleResolutionDownBy"),Y(this,"stat",{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0,framesCaptured:0}),Y(this,"small"),Y(this,"isNeedToSetBandwidth"),Y(this,"muteImage"),Y(this,"manager"),Y(this,"_seiCodec",new miA),this.manager=e;let o=()=>{var a;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{let l=Kd(((a=this.room)==null?void 0:a.sdkAppId)||0)?_b:a0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),this.setProfile(po(fi({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",o),this.on("publish",o),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(Qy&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)||""}get isQosClearFirst(){var e;return((e=this._inputTrack)==null?void 0:e.contentHint)==="detail"}get hasSmall(){var e;return!((e=this.manager)==null||!e.hasSmall)}setMute(e){return WA(this,null,function*(){var o,a,l;if(Vn(e)){if(this.muteImage===e)return;yield(o=this.manager)==null?void 0:o.deleteWatermark("mute"),yield(a=this.manager)==null?void 0:a.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:e,fillVideo:!0}),this.muteImage=e,GI(N_.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(l=this.manager)==null?void 0:l.deleteWatermark("mute"),this.muteImage=void 0),GI(N_.prototype,this,"setMute").call(this,e)})}capture(e){return WA(this,arguments,function(o){var a=this;let{deviceId:l,facingMode:d,useExactDeviceId:h=!0,customSource:y,retryWhenExactFailed:S=!0}=o;return function*(){let k={audio:!1,video:!0,facingMode:d||a.facingMode,cameraId:l,width:a.profile.width,height:a.profile.height,frameRate:a.profile.frameRate,useExactDeviceId:h,retryWhenExactFailed:S,customSource:y};if(k.facingMode==="environment"){let V=yield a.getDeviceIdWhenUsingBackCamera();V&&(k.cameraId=V)}return GI(N_.prototype,a,"capture").call(a,k)}()})}setProfile(e){var o;let a=this.fallbackProfile(e);if(a.bitrate&&(this.isNeedToSetBandwidth=a.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(a);else{let l=Kd(((o=this.room)==null?void 0:o.sdkAppId)||0)?_b:a0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(l)),super.setProfile(po(fi({},this.profile),{width:1920,height:1080}))}}applyProfile(){return WA(this,null,function*(){var e,o;if(!this.mediaTrack)return;let{width:a=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),d=a*l,h=this.settings,y=h.height!==this.profile.height||h.width!==this.profile.width||h.frameRate!==this.profile.frameRate;if(y&&(Zd===16&&this.deviceId?yield this.recapture(this.deviceId):(Gp(this.outMediaTrack)?yield(e=this.outMediaTrack)==null?void 0:e.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}):yield(o=this.sourceTrack||this.mediaTrack)==null?void 0:o.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate}),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;let{width:S=0,height:k=0}=(this.sourceTrack||this.mediaTrack).getSettings(),V=S*k;return y&&V&&d&&V===d?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:YA.VIDEO,videoType:YA.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return Qy&&o&&Object.assign(e,o.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:N0(this.settings,this.profile)}isAllowed2k4k(e){var o;return!(this.room&&this.room.scheduleResult&&!this.isScreen&&!(e.height*e.width<3686400))||((o=this.room.scheduleResult.trtcAutoConf)==null?void 0:o["2k4k"])===1}isNeedToSwitchDevice(e){return!(!this.mediaTrack||this.deviceId===e||this.facingMode===e)}switchDevice(e){return WA(this,null,function*(){try{if(!this.isNeedToSwitchDevice(e)&&!this.isUseCustomSource)return;let o={useExactDeviceId:!0,retryWhenExactFailed:!1};e==="user"||e==="environment"?o.facingMode=e:o.deviceId=e,this.sourceTrack&&this.sourceTrack.stop(),yield this.capture(o),F.emit(nA.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(o){throw this.log.error("switch camera failed ".concat(o)),this.deviceId&&this.recapture(this.deviceId),o}})}getDeviceIdWhenUsingBackCamera(){return WA(this,null,function*(){let e;try{if(hk&&!ry&&q2){let o=(yield tm(!0)).map(l=>{var d;return po(fi({},l),{capabilities:(d=l.getCapabilities)==null?void 0:d.call(l)})}).filter(l=>{var d,h;return(h=(d=l.capabilities)==null?void 0:d.facingMode)==null?void 0:h.includes("environment")}),a=o[0];o.forEach(l=>{var d,h,y,S;let{capabilities:k}=l;((d=k.width)!=null&&d.max&&(h=k.height)!=null&&h.max?k.width.max*k.height.max:0)>((y=a.capabilities.width)!=null&&y.max&&(S=a.capabilities.height)!=null&&S.max?a.capabilities.width.max*a.capabilities.height.max:0)&&(a=l)}),a!=null&&a.capabilities&&(this._log.info("use max resolution back camera",a),e=a.deviceId)}}catch(o){this._log.warn("get max res camera failed",o)}return e})}updateSmallConfig(e){return WA(this,null,function*(){var o,a;this._log.info("update small stream config: ".concat(JSON.stringify(e)));let l=!this.small;this.small=this.fallbackProfile(e,!0),yield(o=this.manager)==null?void 0:o.update(),l&&(yield(a=this.room)==null?void 0:a.enableSmall(!0)),this.log.info("update small stream config success")})}fallbackProfile(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1],a=e.width>e.height,l=fi({},e);return e.width*e.height<=19200&&Ha&&uE&&(this.log.warn("".concat(o?"small ":"","resolution is ").concat(e.width,"*").concat(e.height,", fallback to 240*180 for android chrome")),l.width=a?240:180,l.height=a?180:240,l.bitrate=Math.max(e.bitrate,150)),e.width*e.height>921600&&G2&&(l.width=a?1280:720,l.height=a?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),yk(LI,"14.3")&&gy(LI,"14.0",!0)&&this.on("7",()=>{let d=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=d?640:480,this.profile.height=d?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=d?640:360,this.profile.height=d?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!o&&this.avoidCropping&&(uE||or)&&!W0()&&e.width*e.height<=230400&&e.width/e.height===16/9&&(this._scaleResolutionDownBy=1280/e.width,l.width=1280,l.height=720,this.log.warn("capture 720p, scale: ".concat(this._scaleResolutionDownBy))),l}stopSmall(){var e,o;this.small&&(delete this.small,(e=this.manager)==null||e.update(),(o=this.room)==null||o.enableSmall(!1))}listenDeviceChange(){Pc&&!Pc.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Pc.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return WA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(nj[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Jg(this.userId,{eventId:2003,param1:7,streamType:2});let a=yield tm();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Pc.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return WA(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Pc.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn("camera added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))})}encodeFrame(e,o){if(!this.manager)return e;let a=o?8:this.mediaType;return this.manager.encodePipeline.reduceRight((l,d)=>d?d({frame:l,mediaType:a}):l,e)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(e=>e)}play(e,o){return Ke(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,o)}close(){Pc.off("videoInputAdded",this.handleCameraAdded,this),Pc.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return WA(this,null,function*(){try{yield GI(N_.prototype,this,"recapture").call(this,e)}catch(o){let a=(yield tm()).find(l=>l.deviceId!==e);if(!a)throw o;yield GI(N_.prototype,this,"recapture").call(this,a.deviceId)}})}setContentHint(e){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==e&&(this.log.info("setContentHint ".concat(e)),this.mediaTrack.contentHint=e),this.outMediaTrack&&this.outMediaTrack.contentHint!==e&&(this.outMediaTrack.contentHint=e))}setRotation(e){this.manager&&(this.isScreen||Ke(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};hi([qM(function(A){this.setContentHint(A.contentHint||"motion")})],iz.prototype,"capture");var BQ=iz,oz={};jh(oz,{REPORT_TYPE:()=>G0,buildSSOPackage:()=>iQ,bytes2ms:()=>M0,calculateScaleResolutionDownNumber:()=>N0,concatArrayBuffers:()=>lM,convertObjectNumberToInt:()=>T0,copyProperties:()=>c2,deepClone:()=>$f,deepCloneBasic:()=>Ay,deepMerge:()=>Xh,delay:()=>OC,fibonacci:()=>zf,formatedTime:()=>B2,getConstructorName:()=>nM,getContainerFromElement:()=>zb,getEnv:()=>r2,getFirst16Bits:()=>p2,getInternalVersion:()=>C2,getLast16Bits:()=>b0,getLoggerUrl:()=>jf,getMediaStreamTrackInfo:()=>ek,getMuteStateFromFlag:()=>Np,getNetworkType:()=>D0,getNumNetworkType:()=>Wf,getReconnectionTimeout:()=>Tp,getStringByteLength:()=>_0,getTestSignalDomain:()=>a2,getTurnServer:()=>h2,getUint32Version:()=>Xb,getValueType:()=>Cg,getViewListFromView:()=>gM,glog:()=>I2,ipv4ToUint32:()=>aM,isArray:()=>wa,isAudioWorkletSupported:()=>u2,isBoolean:()=>Nr,isConstructor:()=>Xf,isEmpty:()=>R0,isFunction:()=>Ra,isLangChinese:()=>Wd,isMediaStreamTrack:()=>jb,isNumber:()=>kn,isObject:()=>XE,isOverseaSdkAppId:()=>Kd,isPlainObject:()=>IE,isPortrait:()=>Zb,isPromise:()=>Zf,isRemoteTrack:()=>Wb,isRotate90Or270:()=>tQ,isSetSinkIdSupported:()=>E2,isString:()=>Vn,isUndefined:()=>Ke,isVideoMixerOutputTrack:()=>Gp,loadImage:()=>cM,loadVideo:()=>Q2,ms2bytes:()=>l2,ms2samples:()=>v0,normalizeUrl:()=>Ak,performanceNow:()=>ko,promiseAny:()=>rM,samples2ms:()=>Kb,setNetworkTypeFromWebRTC:()=>S0,stringify:()=>zd,stringifyIncludeValue:()=>w0,throttlePromise:()=>$b});var fiA=[-1,-1,1,-1,-1,1,1,1],yiA=[0,0,1,0,0,1,1,1],uL=class Z3 extends Zs{constructor(e,o){if(super(),this.context=e,Y(this,"name"),Y(this,"input"),Y(this,"output"),Y(this,"texture"),Y(this,"ctx2d",null),Y(this,"fbo"),Y(this,"width",0),Y(this,"height",0),Y(this,"x",0),Y(this,"y",0),Y(this,"program"),Y(this,"vertexShader"),Y(this,"fragmentShader"),Y(this,"totalFrames",0),Y(this,"dropFrames",0),Y(this,"matchInputSize",!0),Y(this,"texCoordBuffer"),Y(this,"positionBuffer"),Y(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Y(this,"cost",0),Y(this,"_canvas",null),Y(this,"_image"),Y(this,"log"),this.context.on("disconnect",this.close,this),this.name=o.name,this.log=o.logger,this.matchInputSize=o.matchInputSize!==!1,this.width=o.width||e.width,this.height=o.height||e.height,this._image=o.image,e instanceof QQ)e.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&Zd!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{let a=e.ctx;this.texCoordBuffer=this.createBuffer(yiA),this.positionBuffer=this.createBuffer(fiA),o.createTexture!==!1&&(this.texture=a.createTexture(),this.useTexture(),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),a.pixelStorei(a.UNPACK_ALIGNMENT,1)),o.useFbo&&(this.fbo=a.createFramebuffer(),this.useBufferFrame(),this.useTexture(),a.texImage2D(a.TEXTURE_2D,0,a.RGBA,this.width,this.height,0,a.RGBA,a.UNSIGNED_BYTE,null),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,this.texture,0)),o.useDefaultProgram?this.program=e.defaultProgam:(o.vertexShaderSource||o.fragmentShaderSource)&&(this.vertexShader=o.vertexShaderSource?e.createShader(a.VERTEX_SHADER,o.vertexShaderSource):e.defaultVShader,this.fragmentShader=o.fragmentShaderSource?e.createShader(a.FRAGMENT_SHADER,o.fragmentShaderSource):e.defaultFShader,this.program=e.createProgram(this.vertexShader,this.fragmentShader))}catch(a){this.context.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(a.message||a)}))}}get image(){return this._image}set image(e){this._image=e}createFramebuffer(e){let o=this.context.ctx,a=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,a),o.framebufferTexture2D(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,e,0),a}connect(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l0&&arguments[0]!==void 0?arguments[0]:0;var o;(o=this.output)==null||o.update(e)}disconnect(){for(var e,o=arguments.length,a=new Array(o),l=0;l{d&&(e.activeTexture(e.TEXTURE0+h),e.bindTexture(e.TEXTURE_2D,d))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){let e=this.context.ctx;e.bindFramebuffer(e.FRAMEBUFFER,this.fbo||null)}createBuffer(e){let o=this.context.ctx,a=o.createBuffer();return o.bindBuffer(o.ARRAY_BUFFER,a),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW),a}setTexBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.texCoordBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}setPosBuffer(e){let o=this.context.ctx;o.bindBuffer(o.ARRAY_BUFFER,this.positionBuffer),o.bufferData(o.ARRAY_BUFFER,new Float32Array(e),o.STATIC_DRAW)}changeBufferData(e,o){let a=this.context.ctx;a.bindBuffer(a.ARRAY_BUFFER,e),a.bufferData(a.ARRAY_BUFFER,new Float32Array(o),a.STATIC_DRAW)}setAttributes(){let e=this.context.ctx;for(var o=arguments.length,a=new Array(o),l=0;l{e.enableVertexAttribArray(h),e.bindBuffer(e.ARRAY_BUFFER,d),e.vertexAttribPointer(h,2,e.FLOAT,!1,0,0)})}getVertexPoint(e,o){return[e/this.width*2-1,o/this.height*2-1]}layout2texCoords(e){return[...this.getVertexPoint(e.x,e.y),...this.getVertexPoint(e.x+e.width,e.y),...this.getVertexPoint(e.x,e.y+e.height),...this.getVertexPoint(e.x+e.width,e.y+e.height)]}resize(e,o){if(this.width!==e||this.height!==o){if(this.width=e,this.height=o,this._canvas&&(this._canvas.width=e,this._canvas.height=o),this.texture&&this.fbo){this.useTexture();let a=this.context.ctx;a.texImage2D(a.TEXTURE_2D,0,a.RGBA,e,o,0,a.RGBA,a.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(e,o)}}draw(e,o){this.setAttributes(e||this.positionBuffer,o||this.texCoordBuffer);let a=this.context.ctx;a.drawArrays(a.TRIANGLE_STRIP,0,4)}draw2d(e,o,a,l,d,h,y,S,k){let V=!(Ke(h)||Ke(y)||Ke(S)||Ke(k));return!(!this.ctx2d||!e)&&(e instanceof ImageData?(V?this.ctx2d.putImageData(e,o,a,h,y,S,k):this.ctx2d.putImageData(e,o,a),this.emit(Z3.RENDER,this.ctx2d.canvas)):(V?this.ctx2d.drawImage(e,h,y,S,k,o,a,l,d):this.ctx2d.drawImage(e,o,a,l,d),this.emit(Z3.RENDER,e)),typeof VideoFrame<"u"&&e instanceof VideoFrame&&e.close(),!0)}drawBackGround2d(e){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=e,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var e;let{totalFrames:o,x:a,y:l,width:d,height:h,name:y,cost:S}=this,k=Date.now(),V=(o-this.lastInfo.totalFrames)/((k-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:a,y:l,width:d,height:h,timestamp:k,fps:V,name:y,cost:S},fi({parent:(e=this.input)==null?void 0:e.getInfo()},this.lastInfo)}createTexture(e){let o=this.context.ctx,a=o.createTexture();return this.useTextures(a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.pixelStorei(o.UNPACK_ALIGNMENT,1),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,o.RGBA,o.UNSIGNED_BYTE,e),a}};Y(uL,"RENDER","render"),hi([lc(Zs.INIT,"connected",{sync:!0})],uL.prototype,"connect"),hi([lc("connected",Zs.INIT,{ignoreError:!0,sync:!0})],uL.prototype,"disconnect"),hi([lc([],"closed",{sync:!0})],uL.prototype,"close");var AC=uL,DiA=ma(V5(250),oj(()=>performance.now()),nL()),SiA=[0,1,1,1,0,0,1,0],rj=class extends AC{constructor(A,e){super(A,Object.assign({useDefaultProgram:!0,createTexture:!1,name:"destination"},e)),Y(this,"_intervalId",0),Y(this,"_sequence",0),Y(this,"checkGLError",!1),Y(this,"checkVisibilityChange"),A instanceof QQ?this.ctx2d=A.ctx||null:A.available&&e!=null&&e.mirrorUpAndDown&&this.setTexBuffer(SiA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),Gr.clearTask(this._intervalId),this._intervalId=Gr.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(Gr.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof qC){let e=this.context.ctx.getError();e&&this.context.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:5,message:"".concat(this.name," req ").concat(this._sequence," render ").concat(this.totalFrames," faild ").concat(e)}))}},{fps:this.context.frameRate})}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(AC.RENDER,this.context._canvas),!0)}addInput(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;a0&&arguments[0]!==void 0?arguments[0]:0;this.state!=="closed"&&(this._intervalId&&(Gr.clearTask(this._intervalId),this._intervalId=0,A===1&&(this.log.info("".concat(this.name," use requestVideoFrameCallback")),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info("".concat(this.name," use timer")),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(A){super.removeInput(A),Gr.clearTask(this._intervalId)}resize(A,e){super.resize(A,e),this.context.setSize(A,e)}close(){super.close(),Gr.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},aj=class extends rj{constructor(A,e){super(A,e),Y(this,"_videoTrack"),Y(this,"_muteOb"),Y(this,"_closedOb",la(this,"closed")),Y(this,"_subscription"),Y(this,"_canvasContainer"),Number(rQ)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=la(this._videoTrack,"mute"),ma(la(this._videoTrack,"ended"),dE(this._closedOb),Bl(()=>{this.context.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=ma(this._muteOb,dE(this._closedOb),l1((A=5e3,e=>{let o=performance.now();ma(DiA,ij(a=>a-o{var e;return!((e=this._videoTrack)==null||!e.muted||document.hidden)}),Bl(()=>{this.context.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var A;(A=this._subscription)==null||A.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){!this.context._canvas||!this._canvasContainer||document.getElementById(this.context._canvas.id)||(this.log.info("".concat(this.name," put canvas to body")),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas))}render(A){return this.putCanvasIntoDom(),super.render(A)}render2d(A){return this.putCanvasIntoDom(),super.render2d(A)}close(){var A,e;super.close(),(A=this._videoTrack)==null||A.stop(),delete this._videoTrack,(e=this._canvasContainer)==null||e.remove()}},MiA=class extends aj{render(A){var e;let o=!((e=this.input)==null||!e.requestFrame(A));if(this.context._canvas2d){let a=this.context._canvas2d.getContext("2d");a.clearRect(0,0,this.context._canvas2d.width,this.context._canvas2d.height),a.drawImage(this.context._canvas,0,0,this.context._canvas2d.width,this.context._canvas2d.height),this.emit(AC.RENDER,this.context._canvas2d)}else this.emit(AC.RENDER,this.context._canvas);return o}},viA=class extends aj{constructor(A,e,o){super(A,{name:"smallDestination",logger:o}),this.resolution=e}resize(A,e){let o,a=A*e,l=this.resolution.width*this.resolution.height;this.log.info("big res: ".concat(A,"*").concat(e," small res: ").concat(this.resolution.width,"*").concat(this.resolution.height," ")),a>l?o=a/l:(this.log.warn("Small stream resolution is not smaller than big stream, which is invalid. big: ".concat(A," * ").concat(e," small: ").concat(this.resolution.width," * ").concat(this.resolution.height)),o=a/19200),super.resize(A/Math.sqrt(o),e/Math.sqrt(o))}},sz=class extends AC{constructor(A,e){super(A,fi({name:"imageSource"},e)),Y(this,"_lastImage"),Y(this,"_totalFrames",0),Y(this,"_autoResize",!1),Y(this,"_canvasRendered"),Y(this,"videoCallbackId",0),Y(this,"waitingFirstFrame",!0),Y(this,"shouldUpdate",!0),this._autoResize=e?.autoResize!==!1,Zd===16&&(this._canvasRendered=hQ(),ma(this._canvasRendered,$K(this._image),g1(o=>o instanceof HTMLCanvasElement?la(o,"rendered"):tj()),dE(la(this,"closed")),Bl(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),Zp()&&!document.hidden&&(this.videoCallbackId=A.requestVideoFrameCallback((e,o)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=o.presentedFrames,this.update(1))}))}_render(A,e){var o;let{width:a,height:l}=this,{image:d}=this;if(d instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:a,videoHeight:l}=d,!a||!l)return!1;d.width=a,d.height=l}else if(d instanceof HTMLImageElement||d instanceof ImageData||d instanceof ImageBitmap){if({width:a,height:l}=d,d!==this._lastImage)this._lastImage=d;else if(a===this.width&&l===this.height)return!0}else d instanceof HTMLCanvasElement||d instanceof OffscreenCanvas?({width:a,height:l}=d,this._lastImage=d):typeof VideoFrame<"u"&&d instanceof VideoFrame&&({displayWidth:a,displayHeight:l}=d,(o=this._lastImage)==null||o.close(),this._lastImage=d);if(!this._autoResize)return!0;if(this.width===a&&this.height===l&&this.totalFrames){if(e){this.useTexture();let h=this.context.ctx;h.texSubImage2D(h.TEXTURE_2D,0,0,0,h.RGBA,h.UNSIGNED_BYTE,d)}}else{if(e){this.useTexture();let h=this.context.ctx;h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.UNSIGNED_BYTE,d)}this.resize(a,l)}return!0}get image(){return this._image}set image(A){var e;(e=this._canvasRendered)==null||e.next(A),this._image=A}render(A){return this._render(A,!0)}render2d(A){return this._render(A,!1)}},nz=class extends sz{constructor(A,e,o){super(A,o),this._player=e,this.name="videoPlayerSource",ma(la(this._player,yo.PLAYER_STATE_CHANGED),dE(la(this,"closed")),KM(a=>{let{state:l}=a;return l==="PLAYING"}),Bl(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},d_=class extends nz{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,e,o){super(A,new Ro({id:o.name,track:e,muted:!0,container:null,objectFit:"contain",log:o.logger}),o),this.name="videoTrackSource",this._player.play()}replaceTrack(A){this.waitingFirstFrame=!0,this._player.setTrack(A),this._player.play()}close(){super.close(),this._player.stop()}},RiA=class extends AC{constructor(A,e,o){super(A,po(fi({name:"textSource"},o),{create2d:!0})),Y(this,"hasChange",!0),Y(this,"content",""),this.ctx2d.textBaseline="top",this.content=e.content||"",e.font&&(this.font=e.font),e.color&&(this.color=e.color)}set font(A){this.ctx2d&&(this.ctx2d.font=A,this.hasChange=!0)}get font(){var A;return((A=this.ctx2d)==null?void 0:A.font)||""}set color(A){this.ctx2d&&(this.ctx2d.fillStyle=A,this.hasChange=!0)}get color(){var A;return((A=this.ctx2d)==null?void 0:A.fillStyle)||""}render2d(A){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(A){return!1}resize(A,e){if(!this.ctx2d)return;let{color:o,font:a}=this;super.resize(A,e),this.color=o,this.font=a}drawMultilineText(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1.2;if(!this.ctx2d)return;let a=this.ctx2d.measureText(this.content);e+=a.fontBoundingBoxAscent||a.actualBoundingBoxAscent||0;let l=this.font.match(/(\d+)px/),d=(l?parseInt(l[1],10):16)*o,h=this.content.split(` +`);for(let y=0;y0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(EL._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",Pb),!this.ctx)throw new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:2,message:"webgl2 not supported"});this.defaultVShader=this.createShader(this.ctx.VERTEX_SHADER,` // 顶点着色器 attribute vec4 a_position; attribute vec2 a_texCoord; @@ -300,27 +300,27 @@ uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, v_texCoord); -} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let e="";return A&&(e=A.message,this.error=A,ii.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(e)?": ".concat(e):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),A}set width(A){var e;(e=this.ctx)==null||e.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var e;(e=this.ctx)==null||e.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,e){var o;(o=this.ctx)==null||o.viewport(0,0,A,e),super.setSize(A,e),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=e)}createShader(A,e){let o=this.ctx,a=o.createShader(A);return o.shaderSource(a,e),o.compileShader(a),a}createProgram(A,e){let o=this.ctx,a=o.createProgram();return o.attachShader(a,A),o.attachShader(a,e),o.linkProgram(a),o.getProgramParameter(a,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(a)),a}};Y(gL,"UNAVAILABLE","unavailable"),Ci([lc(Zs.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),ii.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),ii.addSuccessEvent({key:512700})}})],gL.prototype,"create"),Ci([lc("created",Zs.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(gL.UNAVAILABLE,A),this.removeAllListeners()}})],gL.prototype,"destroy");var VC=gL,CQ=class extends aL{constructor(){super(...arguments),Y(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(aL._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(A){let e="";A&&(e=A.message,this.error=A,ii.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),ii.addSuccessEvent({key:512703})}};function AiA(A,e,o,a,c){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,a]=[a,o]);let d={sWidth:A,sHeight:e,dWidth:o,dHeight:a,sx:0,sy:0,dx:0,dy:0};if(A===0||e===0)return d;switch(c){case void 0:case"fill":break;case"contain":{let C=Math.min(o/A,a/e);d.dWidth=A*C,d.dHeight=e*C,d.dx=(o-d.dWidth)/2,d.dy=(a-d.dHeight)/2;break}case"cover":{let C=Math.max(o/A,a/e),y=o/C,S=a/C;d.sx=(A-y)/2,d.sy=(e-S)/2,d.sWidth=y,d.sHeight=S;break}}return d}Ci([lc(Zs.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),ii.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),ii.addSuccessEvent({key:512701})}})],CQ.prototype,"create"),Ci([lc("created",Zs.INIT,{ignoreError:!0,sync:!0})],CQ.prototype,"destroy");var eiA=class{constructor(A,e){this.node=A,this.layout=e,Y(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},F5=class extends AC{constructor(A,e){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:e}),Y(this,"inputs",[]),Y(this,"backgroundColor","black")}addInput(A,e){let o=0,a=this.inputs.length;for(;oe.zIndex))throw new Error("input already exists at zIndex ".concat(e.zIndex));a=d}}let c=new eiA(A,e);this.inputs.splice(o,0,c)}changeInputLayout(A,e){let o=this.inputs.findIndex(gA=>gA.node===A);if(o<0)return;let{x:a,y:c,width:d,height:C,zIndex:y,fillMode:S,rotation:k,hidden:V}=e;if(!Je(y)&&this.inputs.some(gA=>gA.layout.zIndex===y&&gA.node!==A))throw new Error("input already exists at zIndex ".concat(e.zIndex));let J=this.inputs[o];Je(a)||(J.layout.x=a),Je(c)||(J.layout.y=c),Je(d)||(J.layout.width=d),Je(C)||(J.layout.height=C),Je(k)||(J.layout.rotation=k),Je(V)||(J.layout.hidden=V),S&&(J.layout.fillMode=S),!Je(y)&&y!==J.layout.zIndex&&(J.layout.zIndex=y,this.inputs.sort((gA,CA)=>gA.layout.zIndex-CA.layout.zIndex))}hasInput(A){return this.inputs.some(e=>e.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,e){if(!this.matchInputSize)return void super.resize(A,e);let o=this.inputs.reduce((a,c)=>c?Object.assign(a,{width:Math.max(a.width,c.right),height:Math.max(a.height,c.bottom)}):a,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof VC&&this.inputs.forEach(a=>{if(a){let c=this.layout2texCoords(a);a.positionBuffer?this.changeBufferData(a.positionBuffer,c):a.positionBuffer=this.createBuffer(c)}})}connect(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;ae.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let e=this.context.ctx;if(e.clearColor(0,0,0,0),this.inputs.reduce((o,a)=>a.node.requestFrame(A)||o,!1)&&e){this.useProgram(),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;oe.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(c&&([o,a]=[a,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,e,o,a),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:e,y:o,width:a,height:c,name:d}=this,C=Date.now(),y=(A-this.lastInfo.totalFrames)/((C-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:e,y:o,width:a,height:c,timestamp:C,fps:y,name:d},mi({parent:this.inputs.filter(S=>S).map(S=>S.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var e;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof VC)try{(e=this.context.ctx)==null||e.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},tiA=[1,0,0,0,1,1,0,1],Sy=class extends AC{constructor(A,e,o,a){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:e}),Y(this,"mirror",!1),Y(this,"rotation",0),o&&(this.mirror=o),a&&(this.rotation=a),A instanceof VC)try{this.setTexBuffer(tiA)}catch(c){A.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(c.message||c)}))}}draw2d(A,e,o,a,c){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(a,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(c/a,a/c)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,c),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(c/a,a/c));let d=super.draw2d(A,e,o,a,c);return this.ctx2d.restore(),d}return!1}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,e){$B(this.rotation)&&([A,e]=[e,A]),super.resize(A,e)}},jK=class extends sL{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,vo),Y(this,"inputLocalVideoTracks",new Map),Y(this,"inputLocalScreenTracks",new Map),Y(this,"cameraNodeMap",new Map),Y(this,"screenNodeMap",new Map),Y(this,"textNodeMap",new Map),Y(this,"imageNodeMap",new Map),Y(this,"videoNodeMap",new Map),Y(this,"endedIds",new Set),Y(this,"videoContext"),Y(this,"mixNode"),Y(this,"destination"),Y(this,"manager"),Y(this,"stat"),Y(this,"_checkId",0),Y(this,"autoSetFps",!0),this.manager=A,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(AC.RENDER,e=>{this.emit("render",e)}),this.mixNode=new F5(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=Gr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new CQ({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let e of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])e.shouldUpdate=!1;setTimeout(()=>{var e;return(e=this.destination)==null?void 0:e.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let c of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])c.shouldUpdate=!1;let e=null,o=0,a=!0;for(let[c,d]of this.inputLocalVideoTracks)if(d.profile.frameRate>o){if(this.endedIds.has(c)){let C=this.cameraNodeMap.get(c);C&&C.image.cancelVideoFrameCallback(C.videoCallbackId);continue}o=d.profile.frameRate,e=c}for(let[c,d]of this.inputLocalScreenTracks)if(d.profile.frameRate>o){if(this.endedIds.has(c)){let C=this.screenNodeMap.get(c);C&&C.image.cancelVideoFrameCallback(C.videoCallbackId);continue}o=d.profile.frameRate,e=c,a=!1}if(e!==null){let c=a?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);c&&(c.shouldUpdate=!0,c.tryVideoFrameCallback()),this.log.info("set mix fps: ",o)}else(A=this.destination)==null||A.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(A){this.mixNode&&(this.mixNode.backgroundColor=A)}resizeMixCanvas(A,e){var o;(o=this.mixNode)==null||o.resize(A,e)}startMix(){return KA(this,null,function*(){var A;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),Fp&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,e,o){if(this.inputLocalVideoTracks.has(A)||this.cameraNodeMap.has(A))throw new Error("There is already a cameraSource with the same ID: ".concat(A));let a,{mediaTrack:c}=e;if(!c)throw new Error("no mediaTrack, add cameraSource failed");e.recaptureMode=1,rd(this,Pc).add("videoInputRemoved",d=>{d.deviceId===e.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),e.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,e.mediaTrack)}),a=Zd===16&&c instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(c.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(c,"cameraNodeSource"),a.resize(e.settings.width,e.settings.height),a.shouldUpdate=!1,this._connectMix(a,o,"cover"),this.inputLocalVideoTracks.set(A,e),this.cameraNodeMap.set(A,a),this.setFpsAuto()}addScreenSource(A,e,o){if(this.inputLocalScreenTracks.has(A)||this.screenNodeMap.has(A))throw new Error("There is already a screenSource with the same ID: ".concat(A));let{mediaTrack:a}=e;if(!a)throw new Error("no mediaTrack, add screenSource failed");e.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,e.mediaTrack)});let c=this.videoContext.createVideoTrackSource(a,"screenNodeSource");c.resize(e.settings.width,e.settings.height),c.shouldUpdate=!1,this._connectMix(c,o),this.inputLocalScreenTracks.set(A,e),this.screenNodeMap.set(A,c),this.setFpsAuto()}addTextSource(A){let{id:e,content:o="",font:a,color:c,layout:d}=A;if(this.textNodeMap.has(e))throw new Error("There is already a textSource with the same ID: ".concat(e));let C=this.videoContext.createTextSource({content:o,font:a,color:c});C.resize(d.width,d.height),this._connectMix(C,d),this.textNodeMap.set(e,C)}addImageSource(A,e,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});a.resize(e.width,e.height),this._connectMix(a,o),this.imageNodeMap.set(A,a)}addVideoSource(A,e,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});a.resize(e.videoWidth,e.videoHeight),a.shouldUpdate=!1,this._connectMix(a,o),this.videoNodeMap.set(A,a)}updateCameraSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0,c=this.inputLocalVideoTracks.get(A);c&&o&&o!==c.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",c.mediaTrack),c.setInputMediaStreamTrack(o));let d=this.cameraNodeMap.get(A);if(d){if(o){if(Zd===16&&o instanceof CanvasCaptureMediaStreamTrack)if(d instanceof I_){let S=d.output;d.close(),d=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),d.connect(S),this.cameraNodeMap.set(A,d)}else d.image=o.canvas;else if(d instanceof I_)d.replaceTrack(o);else{let S=d.output;d.close(),d=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),d.connect(S),this.cameraNodeMap.set(A,d)}let{width:C,height:y}=o.getSettings();C&&y&&d.resize(C,y)}a&&d.resize(a.width,a.height),(a||o)&&this.setFpsAuto(),this._changeMixLayout(d,e)}}updateScreenSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",a,o),a&&o&&o!==a.mediaTrack&&a.setInputMediaStreamTrack(o);let c=this.screenNodeMap.get(A);c&&(o&&c.replaceTrack(o),this._changeMixLayout(c,e))}updateTextSource(A){let{id:e,content:o,font:a,color:c,layout:d}=A,C=this.textNodeMap.get(e);C&&(Je(o)||(C.content=o),Je(a)||(C.font=a),Je(c)||(C.color=c),C.resize(d.width,d.height),this._changeMixLayout(C,d))}updateImageSource(A,e,o){let a=this.imageNodeMap.get(A);a&&(o&&(a.image=o,a.resize(o.width,o.height)),this._changeMixLayout(a,e))}updateVideoSource(A,e,o){let a=this.videoNodeMap.get(A);if(a){if(o){let c=a.image;c instanceof HTMLVideoElement&&this.stopVideoElement(c),a.image=o,a.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(a,e)}}_connectMix(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:a,rotation:c}=e;A.disconnect();let d=new Sy(this.videoContext,this.log,a,c);d=A.connect(d),e.fillMode||(e.fillMode=o),d.connect(this.mixNode,e)}_changeMixLayout(A,e){if(!this.mixNode)return;let{mirror:o,rotation:a}=e,c=A.output||A;c instanceof Sy&&(Je(o)||(c.mirror=o),Je(a)||(c.rotation=a),c.resize(A.width,A.height)),this.mixNode.changeInputLayout(c,e)}removeCameraSource(A){let e=this.inputLocalVideoTracks.get(A);if(!e)return;e.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Sy&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let e=this.inputLocalScreenTracks.get(A);if(!e)return;e.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Sy&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let e=this.textNodeMap.get(A);e&&(e.output instanceof Sy&&e.output.close(),e.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let e=this.imageNodeMap.get(A);e&&(e.output instanceof Sy&&e.output.close(),e.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let e=this.videoNodeMap.get(A);e&&(e.output instanceof Sy&&e.output.close(),e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image),e.close(),this.videoNodeMap.delete(A)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&arguments[0]!==void 0&&arguments[0]&&this.setFpsAuto()}stopVideoElement(A){A.pause(),A.src="",A.srcObject=null,A.remove()}close(){var A;super.close(),Gr.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let e of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])e.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),kn(this);for(let e of this.videoNodeMap.values())e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},WK=PA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:WK,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var iiA=function(A){return KA(this,null,function*(){let e=null,o=function(d){let C={preferCurrentTab:d.preferDisplaySurface==="current-tab"||!!d.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},y={width:Bg?{max:d.width}:{ideal:d.width,max:d.width},height:Bg?{max:d.height}:{ideal:d.height,max:d.height},frameRate:d.frameRate,displaySurface:d.preferDisplaySurface||"monitor"};if(C.video=y,d.systemAudio){let{echoCancellation:S=!0,noiseSuppression:k=!1,autoGainControl:V=!1}=d;C.audio={echoCancellation:S,noiseSuppression:k,autoGainControl:V,sampleRate:48e3}}return C}(A);QA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let a=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&a.getAudioTracks().length===0&&(J0&&id<74||Bg||er)&&QA.warn("Your browser not support capture system audio");let c=a.getVideoTracks()[0];if(c){if(A.frameRate)try{yield c.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(d){QA.warn("screen applyConstraints failed: ".concat(d))}A.captureElement&&(yield function(d,C){return KA(this,null,function*(){var y;if("CropTarget"in window&&"fromElement"in CropTarget&&Ra(d.cropTo))try{if(((y=d.getCaptureHandle())==null?void 0:y.handle)!==WK)return;let S=yield CropTarget.fromElement(C);yield d.cropTo(S)}catch(S){QA.warn("cropTo target failed ".concat(S))}})}(c,A.captureElement))}if(A.audio){let d=function(C){let y={echoCancellation:C.echoCancellation,autoGainControl:C.autoGainControl,noiseSuppression:C.noiseSuppression,sampleRate:C.sampleRate,channelCount:C.channelCount};return Je(C.microphoneId)||(y.deviceId=C.microphoneId),{audio:y,video:!1}}(A);QA.info("getUserMedia with constraints: ".concat(JSON.stringify(d))),e=yield navigator.mediaDevices.getUserMedia(d),a.addTrack(e.getAudioTracks()[0])}return a})},qM=class extends dQ{constructor(A){super(A,2),Y(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Y(this,"objectFit","contain"),Y(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,e;try{return WK===((e=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:e.handle)}catch{return}}capture(A){return KA(this,arguments,function(e){var o=this;let{systemAudio:a=!1,autoGainControl:c,echoCancellation:d,noiseSuppression:C,audioTrack:y,videoTrack:S,captureElement:k,preferDisplaySurface:V}=e;return function*(){var J;try{let gA,CA=ko();return S||y?(gA=new MediaStream,S&&gA.addTrack(S),y&&gA.addTrack(y)):(gA=yield iiA({audio:!1,systemAudio:a,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:c,echoCancellation:d,noiseSuppression:C,captureElement:k,preferDisplaySurface:V}),o.sourceTrack=gA.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(gA.getVideoTracks()[0]),F.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:ko()-CA,profile:o.profile,room:(J=o.manager)==null?void 0:J.room}),gA}catch(gA){throw o.log.error("getDisplayMedia error observed ".concat(gA)),gA instanceof ai?gA:new ai({code:dt.INITIALIZE_FAILED,name:gA.name,message:gA.message})}}()})}switchDevice(A){return KA(this,null,function*(){throw new Error("Method not implemented.")})}};Ci([VM(function(A){this.setContentHint(A.contentHint||"detail")})],qM.prototype,"capture");var zK,ZK=class extends HM{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,e,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(A),this.enableTrackAEC(!1)}removeAudioProcessor(A){this.pipeline.aec.node===A&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function XK(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3?arguments[3]:void 0;return KA(this,null,function*(){let c=FI();zK||(zK=Vg(c,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;ty.connect(C,0,S)),new ReadableStream({start(y){C.port.onmessage=S=>{y.enqueue(S.data)}},cancel(){A.forEach(y=>y.disconnect(C)),C.port.close()}})})}var oiA=class extends QeA{constructor(A){super(),this.room=A,Y(this,"_localAudioTrack"),Y(this,"_localScreenAudioTrack"),Y(this,"log"),Y(this,"denoiser"),Y(this,"voiceChanger"),Y(this,"mixChangedDebounce"),Y(this,"audioProcessor"),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"getPCMAbortCtrlMap",new Map),Y(this,"audioFrameEventConfigMap",new Map),Y(this,"audioReferenceMap",new Map),Y(this,"isLocalAudioNeedAudioProcess",!1),Y(this,"isScreenAudioNeedAudioProcess",!1),this.log=QA.createLogger({parent:A?.getLogger(),id:"am",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var A;return(A=this._localAudioTrack)==null?void 0:A.pipeline}get _localScreenAudioPipeline(){var A;return(A=this._localScreenAudioTrack)==null?void 0:A.pipeline}dump(A){var e,o;if(!this._localAudioTrack)return;let a=[],c=[];(e=this._localAudioPipline)!=null&&e.source.node&&(a.push(this._localAudioPipline.source.node),c.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(a.push(this._localAudioPipline.denoiser.node),c.push("mic-processed")),this.mixWeight>1&&(a.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),c.push("mix")),this.log.info("dump audio track ".concat(c,", duration: ").concat(A));let d=new AbortController,C=[],y=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),d.abort("timeout")},1e3*A),S=()=>{for(let V=0;VV.pipeTo(new WritableStream({write(J){J.forEach((gA,CA)=>C[CA]=C[CA]?C[CA].concat(gA[0]):[gA[0]])}}),d).catch(J=>S));return{then:k.then.bind(k),download:S}}getPCM(A,e){var o,a,c;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:d,sampleRate:C=48e3,channelCount:y=1,port:S}=(e===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(e)||this.audioFrameEventConfigMap.get("*"))||{};if(!d)return;this.log.info("getPCM ".concat(e||"local"));let k,V,J=Math.floor(.04*C),gA=new Float32Array(J),CA=new Float32Array(J),MA=0,$A=new AbortController,Be=e===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(c=(a=this.room)==null?void 0:a.remotePublishedUserMap.get(e))==null?void 0:c.remoteAudioTrack.mediaTrack;if(Be)return XK([FI().createMediaStreamSource(new MediaStream([Be]))],C,y,S).then(Ye=>Ye.pipeTo(new WritableStream({write(ve){ve[0][0]&&(MA+ve[0][0].length>J?(gA.set(ve[0][0].subarray(0,J-MA),MA),k=ve[0][0].subarray(J-MA),ve[0][1]&&(CA.set(ve[0][1].subarray(0,J-MA),MA),V=ve[0][1].subarray(J-MA)),MA+=J-MA):(k&&(gA.set(k,MA),MA+=k.length,k=void 0),V&&(CA.set(V,MA),V=void 0),gA.set(ve[0][0],MA),ve[0][1]&&CA.set(ve[0][1],MA),MA+=ve[0][0].length),MA>=J&&(MA=0,A({userId:e,sampleRate:C,channelCount:y,data:y===1?gA:[gA,CA]}),gA=new Float32Array(J),CA=new Float32Array(J)))}}),$A).catch(ve=>this.log.warn("stop getPCM reason:".concat(ve)))),$A;this.log.info("getPCM failed: ".concat(e||"local"," has no audio track"))}get hasScreenAudioTrack(){return!Je(this._localScreenAudioTrack)}get hasAudioTrack(){return!Je(this._localAudioTrack)}changeInput(A){var e,o;return A instanceof ZK?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(e=this.audioProcessor)!=null&&e.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,c)=>{A.mixAudioReference(a,c)})),A.pipeline.connect(),this.mixOnChange()):A instanceof HM?(this._localAudioTrack=A,this.denoiser&&A.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&(o=this.audioProcessor)!=null&&o.localAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,c)=>{A.mixAudioReference(a,c)})),A.pipeline.connect(),this.mixOnChange()):A instanceof s1?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,e){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,e)}unMixAudioReference(A){var e;(e=this._localAudioTrack)==null||e.unMixAudioReference(A)}setAudioReferenceVolume(A,e){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,e;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(e=this._localScreenAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof ZK?delete this._localScreenAudioTrack:A instanceof HM&&delete this._localAudioTrack}addDenoiser(A){var e;this.denoiser=A,(e=this._localAudioTrack)==null||e.addDenoiser(A)}addAudioProcessor(A,e,o,a){var c;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:e,screenAudioWorkletNode:a},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,e),this.audioReferenceMap.forEach((d,C)=>{var y;(y=this._localAudioTrack)==null||y.mixAudioReference(d,C)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&a&&((c=this._localScreenAudioTrack)==null||c.addAudioProcessor(a,A,e),this.audioReferenceMap.forEach((d,C)=>{var y;(y=this._localScreenAudioTrack)==null||y.mixAudioReference(d,C)}))}removeDenoiser(A){var e;return delete this.denoiser,(e=this._localAudioTrack)==null?void 0:e.removeDenoiser(A)}addVoiceChanger(A,e){var o;this.voiceChanger=[A,e],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,e)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,e){var o,a;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(a=this._localScreenAudioTrack)==null||a.removeAudioProcessor(e)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(A=>A?.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(A){let{processor:e,type:o}=A;var a;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var a;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}handleLocalTrackStarted(A){let{room:e,userId:o}=A;var a;if(e!==this.room||this.getPCMAbortCtrlMap.get(o))return;let c=this.getPCM(d=>{var C;(C=this.room)==null||C.emit("audio-frame",d)},"");this.getPCMAbortCtrlMap.set(o,c),this.getPCMAbortCtrlMap.get(o)&&((a=this._localAudioTrack)==null||a.on("input-media-track-changed",()=>{let d=this.getPCMAbortCtrlMap.get(o);d&&(d.abort("inputMediaTrackChanged"),d=this.getPCM(C=>{var y;(y=this.room)==null||y.emit("audio-frame",C)},""),this.getPCMAbortCtrlMap.set(o,d))}))}handleLocalTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:e,userId:o}=A;if(e===this.room&&!this.getPCMAbortCtrlMap.get(o)){let a=this.room.audioManager.getPCM(c=>{var d;(d=this.room)==null||d.emit("audio-frame",c)},o);this.getPCMAbortCtrlMap.set(o,a)}}handleRemoteTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){F.on("113",this.handleLocalTrackStarted,this),F.on("114",this.handleLocalTrackStopped,this),F.on("115",this.handleRemoteTrackStarted,this),F.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){F.off("113",this.handleLocalTrackStarted),F.off("114",this.handleLocalTrackStopped),F.off("115",this.handleRemoteTrackStarted),F.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:e,audioReference:o,refId:a,volume:c}=A;if(e==="add"){if(this.audioReferenceMap.get(a)||!o||(this.audioReferenceMap.set(a,o),!this.audioProcessor))return;this.mixAudioReference(o,a)}else if(e==="remove")this.audioReferenceMap.get(a)&&(this.audioReferenceMap.delete(a),this.unMixAudioReference(a));else if(e==="updateVolume"){if(!this.audioProcessor||Je(c))return;this.setAudioReferenceVolume(a,c)}}};function o1(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return jr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;C{let k=setTimeout(()=>{let V=new ai({code:dt.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(a,"() timeout ").concat(A,"s")});(this.log||this._log||QA).warn(V),e===2?S(V):e===1&&y()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(k),o.apply(this,d).then(y,S).finally(()=>{clearTimeout(k),this._checkPendingPromiseSet&&k&&this._checkPendingPromiseSet.delete(k)})})})}var KM=class L3 extends kK{constructor(e,o,a){super({userId:o.userId,sdkAppId:e.sdkAppId,mediaType:a,room:e}),this.room=e,this.user=o,Y(this,"tinyId"),Y(this,"isRemote",!0),Y(this,"jitterBufferDelay",0),Y(this,"availableState"),Y(this,"remotePublishState"),Y(this,"_triggerCheckDecodeSubject",EQ(ca(this,L3.STATE_SUBSCRIBE))),Y(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new Zs("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new Zs("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),ma(UK(ca(this,Zs.STATECHANGED),ca(this.remotePublishState,Zs.STATECHANGED)),VK(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Bl(y=>{this.availableState.state!==(y?Zs.ON:Zs.OFF)&&(this.availableState.state=y?Zs.ON:Zs.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(y)}));let c=ma(ca(this.player,fo.ERROR),JM(y=>y.code===MediaError.MEDIA_ERR_DECODE)),d=ma(PK(5e3),JM(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===YA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),C=ma(d5(c,d),EE(ca(this,Zs.INIT)));ma(this._triggerCheckDecodeSubject,JM(()=>!this.ignoreDecodeError),e1(C),Bl(y=>{this.reportDecodeResult(!1,y)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var e,o,a,c;return(c=(a=(o=(e=this.room)==null?void 0:e.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:a.call(o,2))!=null&&c||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===L3.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Zs.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,o){var a,c;let d=this.kind===YA.AUDIO;if(ii[e?"addSuccessEvent":"addFailedEvent"]({key:d?504700:514702}),!d){let C=((a=this.room)==null?void 0:a.downlinkVideoCodec.toUpperCase())||"H264";ii[e?"addSuccessEvent":"addFailedEvent"]({key:Ey["DECODE_".concat(C,"_RESULT")]}),e||this.log.warn("".concat((c=this.room)==null?void 0:c.downlinkVideoCodec," decode failed"))}e||(ii.addEnum({key:d?504701:514703,value:xp()}),sn.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(rQ()||Yp()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===YA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Zs.ON:Zs.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Y(KM,"STATE_SUBSCRIBE","subscribe"),Ci([o1(5,1)],KM.prototype,"waitHasMediaTrack"),Ci([lc(Zs.INIT,KM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),F.emit(nA.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),fy(521716,!1)],KM.prototype,"subscribe"),Ci([lc(KM.STATE_SUBSCRIBE,Zs.INIT,{sync:!0,success(){this.log.info("unsubscribed"),F.emit(nA.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],KM.prototype,"unsubscribe");var O5=KM,s1=class extends O5{constructor(A,e){super(A,e,1),Y(this,"volume",0),Y(this,"mediaType",1),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return H2.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(A){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var A,e;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((e=(A=this.player.element)==null?void 0:A.error)==null?void 0:e.code)===MediaError.MEDIA_ERR_DECODE&&t_().AudioDecoder&&Kp)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let e=A;for(let[o,a]of this.manager.decodePipeline.entries()){if(!a)continue;let c={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(c.onAudioFrameNTPTime=d=>{let{ntp:C,frame:y,hasLeavingTag:S}=d;this.emit("audio-frame-with-ntp",{ntp:C,frame:y,hasLeavingTag:S})}),e=a(c),!e)return}return e}getAudioLevel(){if(!this.isAvailable)return 0;let A=this.volume||super.getAudioLevel();return A>1?1:A}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},siA=class extends AC{constructor(A,e,o,a,c){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:e}),this.setContainer=a,Y(this,"initStat",{alphaStitchingType:1}),Y(this,"end",EQ()),Y(this,"minSize",320),Y(this,"maxSize",1280),Y(this,"draggable",!1),Y(this,"startDragX",0),Y(this,"startDragY",0),Y(this,"left",0),Y(this,"top",0),Y(this,"baseWidth",320),Y(this,"baseRatio"),Y(this,"container"),this.initStat=c,this.draggable=o,this.bindDragEvents(),ii.addEnum({key:515700,value:1}),this.draggable&&ii.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let e=EE(this.end);ma(ca(A,"mousedown"),JK(this.startDrag.bind(this)),$2(()=>ma(ca(window,"mousemove"),EE(ca(window,"mouseup")))),e,Bl(this.doDrag.bind(this))),ma(ca(A,"dblclick"),e,Bl(this.resetPosition.bind(this))),ma(ca(A,"wheel"),e,Bl(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(A){A.preventDefault(),A.button===0&&(this.startDragX=A.clientX-this.left,this.startDragY=A.clientY-this.top)}renderCanvas(){let{container:A}=this;A||this.setContainer(),A&&this.baseRatio&&this.draggable&&(A.style.setProperty("width","".concat(this.baseWidth,"px")),A.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),A.style.setProperty("position","fixed"),A.style.setProperty("left","".concat(this.left,"px")),A.style.setProperty("top","".concat(this.top,"px")))}doDrag(A){A.preventDefault(),this.left=A.clientX-this.startDragX,this.top=A.clientY-this.startDragY,this.renderCanvas()}handleZoom(A){A.preventDefault();let e=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=e<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(A,e,o,a,c){var d;let{ctx2d:C}=this,y=this.context._canvas;if(!C||!y)return!1;let S=super.draw2d(A,e,o,a,c),k=C.getImageData(0,0,a,c),{data:V}=k,J=!1;if(this.initStat.alphaStitchingType===1){let gA=Math.floor(a/2);for(let CA=0;CA=100;V[$A+3]=ve?255:0}J=super.draw2d(k,0,0,0,0,gA,c),y.width=gA}else if(this.initStat.alphaStitchingType===2){let gA=Math.floor(c/2);for(let CA=0;CA=100;V[$A+3]=ve?255:0}J=super.draw2d(k,0,0,0,0,a,gA),y.height=gA}return(d=this.context.ctx)==null||d.clearRect(0,0,a,c),S&&J}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},cL=class extends O5{constructor(A,e){super(A,e,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),Y(this,"mediaType",4),Y(this,"source"),Y(this,"shouldRenderAlpha",!1),Y(this,"alphaNode"),Y(this,"shouldBeDraggable",!0),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),Y(this,"_keyFrameCountLogged",!1),Y(this,"_keyFrameStartTimestamp",0),Y(this,"_keyFrameStartCount",0),Y(this,"_keyFrameIntervals",[]),Y(this,"_prevKeyFrameTimestamp",0),this.manager=A.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)}),this.on("first-frame-render",o=>{this.room.emit("first-frame-render",o)})}isAlphaSei(A){if(this.userId!==A.userId||A.seiPayloadType!==50)return!1;let e=new Uint8Array(A.data);return e.length%3==0&&e[0]===0&&e[1]===1&&e}play(A,e){return e!=null&&e.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,e).then(()=>{this.player.calculateStat(),F.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let e=this.isAlphaSei(A);if(e)if(this.alphaNode){let o=e[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let a=this.player.getElement();if(a){let c=a.videoWidth/a.videoHeight;c&&(this.alphaNode.baseRatio=c*(o===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(o))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(e[2])}generateAlphaCanvasName(A){let e=Iy[A];return"".concat("alpha","_").concat(e,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new CQ({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});e.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new qK(e,{name:"remotePlayer",logger:this.log});if(this.source=e.createVideoPlayerSource(this.player),this.player.setCanvas(e._canvas),this.shouldRenderAlpha&&A){let a=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},c=new siA(e,this.log,this.shouldBeDraggable,a,{alphaStitchingType:A});this.source.connect(c),c.connect(o),this.alphaNode=c}else this.source.connect(o);jp()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let e=this.decodeFPS,o=(a=e,[15,30,45,60].reduce((c,d)=>Math.abs(d-a)c.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let a=e.find(c=>c.uint32_video_stream_type===o);return a?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),F.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let e of this.manager.decodePipeline)if(e&&!(A=e({frame:A,track:this})))return;return A}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(A){this.room.changeType(A,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(A){A==="publish"||A==="both"||super.setMirror(A)}setDraggable(A){this.shouldBeDraggable=A,this.alphaNode&&(this.alphaNode.draggable=A,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(A){this.emit("decode-downgrade-state-changed",A)}updateKeyFramesDecoded(A){let e=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=A,this._keyFrameCountLogged)return;let o=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=o,this._keyFrameStartCount=A,void(this._prevKeyFrameTimestamp=o);if(this._prevKeyFrameTimestamp&&A>e){let c=A-e,d=(o-this._prevKeyFrameTimestamp)/1e3/c;this._keyFrameIntervals.push(d)}this._prevKeyFrameTimestamp=o;let a=o-this._keyFrameStartTimestamp;if(a>=16e3){let c=A-this._keyFrameStartCount,d=c>0?a/1e3/c:0,C="".concat(c," keyframes in 16s ").concat(d," [").concat(this._keyFrameIntervals.map(S=>S.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),y=d<=2.5?"debug":"info";this.log[y](C),this._keyFrameCountLogged=!0}}},P5=class extends cL{constructor(A,e){super(A,e,2),Y(this,"mediaType",2),Y(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},u_=new Map;function Jg(A,e){let o=Qo(mi({},e),{timestamp:Lf()});u_.has(A)?u_.get(A).push(o):u_.set(A,[o])}function x5(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,C=new Array(d),y=0;yWf(k)?iM(k):Yn(k)?k:Cg(k))},fnName:c,value:o},link:{className:d,fnName:c}})})}else if(!Je(e.type)&&Cg(o)!==e.type)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_TYPE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});if(e.allowEmpty===!1){let S=bn(o)&&(o===0||Number.isNaN(o)),k=Yn(o)&&o.trim()==="";if(S||k)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_EMPTY,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})})}if(e.notLessThanZero&&bn(o)&&o<0)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.CANNOT_LESS_THAN_ZERO,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});if(!Je(e.min)&&bn(o)&&oe.max)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_MAX,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});if(Yn(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})})}else if(Ra(e.instanceOf)&&!(o instanceof e.instanceOf))throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});if(e.values&&!e.values.includes(o))throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PARAMETER_RANGE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});let{properties:C}=e;lE(C)&&$E(o)&&Object.keys(C).forEach(S=>{n1.call(this,{rule:C[S],value:o&&o[S],key:"".concat(a,".").concat(S),fnName:c,className:d})});let{arrayItem:y}=e;lE(y)&&wa(o)&&o.forEach((S,k)=>{n1.call(this,{rule:y,value:S,key:"".concat(a,"[").concat(k,"]"),fnName:c,className:d})}),Ra(e.validate)&&e.validate.call(this,o,a,c,d,this)}F.on(nA.JOIN_SUCCESS,A=>{let{room:e}=A;Jg(e.userId,{eventId:32788})}),F.on(nA.LEAVE_START,A=>{let{room:e}=A;Jg(e.userId,{eventId:32789})}),F.on(nA.LOCAL_TRACK_PUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32769;e.mediaType===4?o=32768:e.mediaType===2&&(o=32805),Jg(e.room.userId,{eventId:o})}}),F.on(nA.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32771;e.mediaType===4?o=32770:e.mediaType===2&&(o=32806),Jg(e.room.userId,{eventId:o})}}),F.on(nA.TRACK_MUTED,A=>{let{track:e}=A;e.room&&(e.kind===YA.AUDIO?Jg(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):Jg(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),F.on(nA.TRACK_UNMUTED,A=>{let{track:e}=A;e.room&&(e.kind===YA.AUDIO?Jg(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):Jg(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),F.on(nA.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Jg(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&Jg(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&Jg(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),F.on(nA.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Jg(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&Jg(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&Jg(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),F.on(nA.SWITCH_DEVICE_SUCCESS,A=>{let{track:e}=A;e.room&&Jg(e.room.userId,{eventId:e.kind===YA.VIDEO?32780:32781})}),F.on(nA.LOCAL_TRACK_REPLACED,A=>{let{track:e}=A;e.room&&Jg(e.room.userId,{eventId:e.kind===YA.VIDEO?32782:32783})}),F.on(nA.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:a,state:c}=A;switch(c){case"CONNECTED":e=a==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":e=a==="RECONNECTING"?32796:32790;break;case"RECONNECTING":e=32794}e&&Jg(o.userId,{eventId:e})}),F.on(nA.PEER_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:a,state:c,remoteUserId:d}=A,C=!!d;switch(c){case"CONNECTED":e=a==="RECONNECTING"?C?32801:32798:C?32793:32792;break;case"DISCONNECTED":a==="RECONNECTING"&&(e=C?32802:32799);break;case"RECONNECTING":e=C?32800:32797}e&&Jg(o.userId,{eventId:e,remoteUserId:d})}),F.on(nA.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:e,userId:o,remoteUserId:a,codec:c,isHWCodec:d,prevImplementation:C,streamType:y}=A,S=d?1:0;C||(S=d?3:2);let k={H264:0,H265:1,VP8:2}[c.toUpperCase()],V={eventId:4004,param1:S,param2:k,streamType:y||2};a&&(V.remoteUserId=a,V.eventId=4005),Jg(o,V),ii.addEnum({key:a?514701:513701,value:S}),ii.addEnum({key:a?514700:513700,value:k})}),F.on(nA.LOCAL_TRACK_RECAPTURE,A=>{let{track:e,error:o}=A;if(e.userId){let a={eventId:2003,param1:0};e.kind===YA.AUDIO?(a.streamType=1,o&&(a.param1=2)):(a.streamType=e.streamType==="auxiliary"?7:2,o&&(a.param1=8)),Jg(e.userId,a)}});var riA=gc(Kl(),1),aiA=class extends riA.EventEmitter{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=e,this.key=o,Y(this,"userMap",new Map),Y(this,"remotePublishedUserMap",new Map),Y(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let e=A[this.key],{userId:o,tinyId:a,role:c,fromType:d}=A;if(d===d0)return void this.addAsrRobotUser(A);if(this.userMap.has(e))return;let C={userId:o,tinyId:a,role:c===20?"anchor":"audience"};this.userMap.set(e,C),this.emit("1",C)}addAsrRobotUser(A){let e=A[this.key],{userId:o,tinyId:a,role:c}=A;if(this.asrRobotUserMap.has(e))return;let d={userId:o,tinyId:a,role:c===20?"anchor":"audience"};this.asrRobotUserMap.set(e,d),this.emit("8",d)}deleteUser(A,e){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let a="peer leave [".concat(A,"]");Je(e)||(a+=":".concat(Kx[e])),this._log.info(a);let c=this.remotePublishedUserMap.get(A);if(c){let d=c.muteState;c.flag=0,this.emit("5",c.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:d,muteState:c.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:e})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let e=this.asrRobotUserMap.get(A);e&&(this.asrRobotUserMap.delete(A),this.emit("9",e))}setUserList(A){this.userMap.forEach(e=>{A.findIndex(o=>o[this.key]===e[this.key])<0&&this.deleteUser(e[this.key],0)}),A.forEach(e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)})}addRemotePublishedUser(A){this.remotePublishedUserMap.has(A[this.key])||this.remotePublishedUserMap.set(A[this.key],A)}deleteRemotePublishedUser(A){this.remotePublishedUserMap.has(A)&&this.remotePublishedUserMap.delete(A)}setRemotePublishedUserList(A){this.remotePublishedUserMap.forEach(e=>{let o=e[this.key];if(A.findIndex(a=>a[this.key]===e[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let a=e.muteState;e.flag=0,this.emit("5",e.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:a,muteState:e.muteState,flag:0})}}),A.forEach(e=>{var o;let a=e[this.key];if(a===this.mySelfId)return void this.emit("7",e);let{flag:c,userId:d,tinyId:C,fromType:y}=e,S=wp(c,d),k=(o=this.remotePublishedUserMap.get(a))==null?void 0:o.muteState;if(k){let V=this.remotePublishedUserMap.get(a);V&&V.flag!==c&&(V.flag=c,this._log.info("remote publish updated: ".concat(JSON.stringify(V.muteState))),this.emit("6",{prevMuteState:k,muteState:S,flag:c}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(S))),this.addUser({userId:d,tinyId:C,role:20,fromType:y}),this.emit("3",e),this.emit("6",{prevMuteState:wp(0,d),muteState:S,flag:c})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},giA=gc(Kl(),1),ciA=class extends giA.default{constructor(){super(...arguments),Y(this,"_connectionTimeoutCount",0),Y(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function Y5(A){let{timesInSecond:e,maxSizeInSecond:o,getSize:a}=A;return jr((c,d)=>{let C=new WeakMap;return F.on(nA.ROOM_DESTROY,y=>{let{room:S}=y;return C.delete(S)}),function(){let y=C.get(this);for(var S=arguments.length,k=new Array(S),V=0;V1e3&&(y.timestamp=Date.now(),y.callCountInSecond=0,y.totalSizeInSecond=0),a&&(y.totalSizeInSecond+=a(...k)),y.timestamp!==0&&Date.now()-y.timestamp<1e3&&(y.callCountInSecond>=e||y.totalSizeInSecond>o))throw new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.CALL_FREQUENCY_LIMIT,data:{isTimes:y.callCountInSecond>=e,isSize:y.totalSizeInSecond>o,name:d,timesInSecond:e,maxSizeInSecond:o}})});y.callCountInSecond++,c.call(this,...k)}})}var St,V5=!0,lL={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},Ro={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},r1=((St=r1||{})[St.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",St[St.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",St[St.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",St[St.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",St[St.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",St[St.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",St[St.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",St[St.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",St[St.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",St[St.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",St[St.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",St[St.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",St[St.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",St[St.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",St[St.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",St[St.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",St[St.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",St[St.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",St[St.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",St[St.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",St[St.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",St[St.INVALID_OPERATION=5100]="INVALID_OPERATION",St[St.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",St[St.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",St[St.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",St[St.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",St[St.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",St[St.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",St[St.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",St[St.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",St[St.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",St[St.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",St[St.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",St[St.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",St[St.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",St[St.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",St[St.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",St[St.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",St[St.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",St[St.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",St[St.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",St[St.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",St[St.DEVICE_ERROR=5300]="DEVICE_ERROR",St[St.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",St[St.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",St[St.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",St[St.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",St[St.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",St[St.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",St[St.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",St[St.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",St[St.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",St[St.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",St[St.SERVER_ERROR=5400]="SERVER_ERROR",St[St.NEED_TO_BUY=5401]="NEED_TO_BUY",St[St.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",St[St.OPERATION_FAILED=5500]="OPERATION_FAILED",St[St.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",St[St.REJOIN_FAILED=5502]="REJOIN_FAILED",St[St.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",St[St.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",St[St.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",St[St.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",St[St.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",St[St.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",St[St.OPERATION_ABORT=5998]="OPERATION_ABORT",St[St.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",St),J5=Qo(mi({},cc),{INVALID_PARAMETER(A){let{fnName:e}=A;return"the parameters of the '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(c,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:a,value:c}=A,d="".concat(e||o.name),C="";return C=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(C," when calling ").concat(a,"(), received type: ").concat(Cg(c),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' cannot be '").concat(c,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:a,value:c}=A,d="".concat(e||o.name),C="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(C," when calling ").concat(a,"(), received type: ").concat(Cg(c),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:a,value:c}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(c,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:a}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,value:a}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,value:a}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(a,".")},INVALID_ELEMENT_ID(A){let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:e,fnName:o,type:a}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},INVALID_STREAM_ID(A){let{key:e}=A;return"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(A){let{key:e}=A;return"'".concat(e,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:e}=A;return"'".concat(e,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:e}=A;return"'".concat(e,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(A){let{key:e}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(e,"', but received '").concat(e==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:e}=A;return"the target '".concat(e,"' must not be the same as the current '").concat(e,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:e}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:e}=A;return"the API '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:e}=A;return"cannot ".concat(e," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:e}=A;return"you are already ".concat(e,"(), cannot repeated call '").concat(e,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:e}=A;return"the buffer size of paramerter '".concat(e,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:A=>{let{fnName:e}=A;return"you need to call ".concat(e,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:e}=A;return"the current browser does not support the capability of the function '".concat(e,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(A){let{fnName:e}=A;return"cannot call ".concat(e," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(e,"'").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"NotReadableError, the ".concat(o," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"SecurityError, check whether the system security policy restricts the use of the ".concat(o,", and it is recommended to turn on the ").concat(o," after the user interacts with the page").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:e,deviceType:o=jM(e),error:a}=A;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(a?" error: ".concat(a.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:e}=A;return"camera recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:e}=A;return"microphone recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},OPERATION_FAILED(A){let{fnName:e,error:o}=A;return"'".concat(e,"' failed, reason: ").concat(o?.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(A){let{eventName:e}=A;return"an error was caught on trtc.on('".concat(e,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:e,error:o}=A;return"video context error ".concat(e," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:e,url:o}=A;return"You need to buy packages for ".concat(e,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:e}=A;return"your TRTC account run out of credit, please recharge.".concat(e.sdkAppId?" SDKAppId: ".concat(e.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:e}=A;return"'".concat(e,"' abort")},UNKNOWN_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function jM(A){if(!A)return"camera";let e=A.toLowerCase();return e.includes("screen")?"screen share":e.includes("audio")?"microphone":"camera"}var liA=class oY extends Error{constructor(e){let{code:o,extraCode:a,message:c="",messageParams:d,fnName:C="",originError:y,data:S}=e;var k;let V;V=c||function(J){let gA,{code:CA,params:MA,enableDocLink:$A=!1}=J,Be="",Ye=r1[CA];try{gA=J5[Ye]}catch{gA=J5.UNKNOWN_ERROR}return Ra(gA)?Be=gA(MA):Yn(gA)&&(Be=gA),MA.fnName&&!Be.includes(MA.fnName)&&(Be[Be.length-1]!=="."&&(Be+="."),Be+=" thrown from ".concat(MA.fnName,"()")),$A&&(Be+=" doc:"),Be}({code:o===Ro.SERVER_ERROR?o:a||o,params:mi({fnName:C,error:y},d)}),super(V),Y(this,"name","RtcError"),Y(this,"code"),Y(this,"extraCode"),Y(this,"functionName"),Y(this,"message"),Y(this,"data"),Y(this,"handler"),Y(this,"originError"),this.name=r1[o],this.code=o,this.extraCode=a,this.functionName=C,this.originError=y,this.message=V,this.data=S,this.extraCode===5302&&(k=this.originError)!=null&&k.message.includes("system")&&(this.handler=()=>{let J=document.createElement("a");ty?J.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):iQ&&(J.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),J.href.length>0&&J.click()})}static convertFrom(e,o,a){let c=e;if(e instanceof ai){let{stack:d}=e,C={code:Ro.UNKNOWN_ERROR,fnName:o,originError:e};switch(e.getCode()){case dt.INVALID_PARAMETER:C.code=Ro.INVALID_PARAMETER,C.message=e.message;break;case dt.INVALID_OPERATION:C.code=Ro.INVALID_OPERATION,C.message=e.message;break;case dt.NOT_SUPPORTED:case dt.NOT_SUPPORTED_H264:C.code=Ro.ENV_NOT_SUPPORTED,e.getCode()===dt.NOT_SUPPORTED_H264&&(C.extraCode=e.message.includes(cc.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case dt.JOIN_ROOM_FAILED:C.messageParams={fnParams:a};case dt.SERVER_TIMEOUT:case dt.SWITCH_ROLE_FAILED:case dt.SWITCH_ROOM_FAILED:C.code=Ro.SERVER_ERROR,C.extraCode=e.getExtraCode();break;case dt.API_CALL_ABORTED:C.code=Ro.OPERATION_ABORT;break;case dt.DEVICE_NOT_FOUND:case dt.DEVICE_AUTO_RECOVER_FAILED:case dt.INITIALIZE_FAILED:C.code=5300,e.name&&(C.extraCode=function(y){let S;switch(y){case"NotFoundError":S=5301;break;case"NotAllowedError":S=5302;break;case"NotReadableError":S=5303;break;case"OverconstrainedError":S=5304;break;case"InvalidStateError":S=5305;break;case"SecurityError":S=5306;break;case"AbortError":S=5307;break;default:S=5300}return S}(e.name));break;case dt.VIDEO_ENCODE_FAILED:C.extraCode=5505;case dt.AUDIO_ENCODE_FAILED:C.extraCode=5506,C.code=Ro.OPERATION_FAILED;break;case dt.UNKNOWN:break;default:C.code=Ro.OPERATION_FAILED}c=new oY(C),d&&(c.stack+=d.substr(d.indexOf(` -`)))}else{if(e instanceof oY)return e;c=new oY({code:Ro.UNKNOWN_ERROR,fnName:o,originError:e})}return c}},wo=liA;function eC(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function a1(A){return A===lL.QOS_PREFERENCE_CLEAR?"detail":A===lL.QOS_PREFERENCE_SMOOTH?"motion":""}function g1(A,e){let o=e?Lx:HS;return u2(A)?mi(mi({},o),A):kC[A]?kC[A]:o}var H5={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},q5={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},E_={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,e,o){if(Yn(A)&&!document.getElementById(A))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:e}})}},K5={name:"userId",required:!0,type:"string"},j5={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function d_(A,e){if(!A)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5101,fnName:e})}function W5(A,e,o){if(!A)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5102,fnName:e,messageParams:{value:o}})}function z5(A,e,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:o}})}function Z5(A,e,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:o}})}function X5(A){var e;if((e=A?.option)==null||!e.small)return;if(!NM())return QA.warn("small stream is not supported"),void delete A.option.small;let o=g1(A.option.profile),a=g1(A.option.small,!0);return((c,d)=>c.width*c.height>=d.width*d.height&&c.frameRate>=d.frameRate&&c.bitrate>=d.bitrate)(o,a)?void 0:(QA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(a))),void delete A.option.small)}var IiA={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(A,e,o){if(this._room.isJoined)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Yn(A.roomId))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:e}});z5(A.roomId,o,e)}else{if(!A.strRoomId)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5015,fnName:o});Z5(A.strRoomId,o,e)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:E_,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:H5},validate(A){var e,o;if(((e=A?.option)==null||!e.videoTrack)&&du())throw new wo({code:Ro.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&X5(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Qo(mi({},E_),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:H5},validate(A){var e;(e=A?.option)!=null&&e.small&&X5(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:j5},validate(A){var e;if(((e=A?.option)==null||!e.audioTrack)&&du())throw new wo({code:Ro.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:j5}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:E_,publish:{type:"boolean"},option:q5},validate(A,e,o,a,c){var d;if((d=A?.option)==null||!d.videoTrack){if(du())throw new wo({code:Ro.ENV_NOT_SUPPORTED,extraCode:5201});if(!qp())throw new wo({code:Ro.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:E_,publish:{type:"boolean"},option:q5}},muteRemoteAudio:[K5,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[K5,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:E_,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,e,o){d_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(W5(!!a,o,A),a&&(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary))throw new wo({code:Ro.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Qo(mi({},E_),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,e,o){d_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(W5(!!a,o,A),a){if(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let c=A.streamType==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!c.isSubscribed||!c.player.isPlaying))throw new wo({code:Ro.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(A,e,o){if(A.userId!=="*"&&Je(A.streamType))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,e,o){d_(this._room.isJoining||this._room.isJoined,o)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(A,e,o,a){if(!xk)throw new wo({code:Ro.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new wo({code:Ro.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5017,messageParams:{key:e},fnName:o});d_(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,e,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5109,messageParams:{key:e},fnName:o})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(A,e,o,a){if(A.byteLength>1e3)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:e}})}}},validate(A,e,o){if(d_(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new wo({code:Ro.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:e}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,e,o){if(d_(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5020,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId&&this._room.useStringRoomId||!A.roomId&&A.strRoomId&&!this._room.useStringRoomId)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)z5(A.roomId,o,e);else{if(!A.strRoomId)throw new wo({code:Ro.INVALID_PARAMETER,extraCode:5015,fnName:o});Z5(A.strRoomId,o,e)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},zl={TRTC:IiA},tC=class extends Error{};function uiA(A,e){let o=zf(A);for(let a=0;a!0),Y(this,"mergeUpdate",uiA);let a=__.instances.get(e);a?a.set(o,this):__.instances.set(e,new Map([[o,this]]))}static get(e,o){if(!o)return;let a=__.instances.get(e);return a&&a.get(o)||new __(e,o)}static gets(e,o){let a=__.instances.get(e),c=[];return a&&a.forEach((d,C)=>{o.test(C)&&c.push(d)}),c}action(e,o,a){let c=y=>{var S;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(S=this.currentOp)==null||S.action(),y},d=y=>{var S,k;throw this.ops.shift(),e===0&&((S=this.currentOp)==null?void 0:S.type)===2&&this.ops.shift().reject(new tC("start failed")),(k=this.currentOp)==null||k.action(),y},C={type:e,action:()=>o(...C.args).then(c,d),args:a,resolve:EiA,reject:diA};try{switch(this.state){case 1:if(e===0)throw new tC("already started");break;case 4:if(e===2)throw new tC("not started");break;default:return this.cacheOp(C)}}catch(y){return Promise.reject(y)}return this.ops.push(C),C.promise=o(...C.args).then(c,d)}cacheOp(e){if(this.ops.length===1)switch(this.state){case 0:case 2:if(e.type===0)throw new tC("already start");break;case 3:switch(e.type){case 2:throw new tC("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new tC("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let a=new tC("keep stop");if(this.ops.slice(1).forEach(c=>c.reject(a)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new tC("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new tC("start not allowed after update");case 0:throw new tC("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new tC("keep start")),new tC("already start")}}e.promise=new Promise((a,c)=>{e._resolve?e._resolve.then(a):e.resolve=a,e._reject?e._reject.catch(c):e.reject=c});let{action:o}=e;return e.action=()=>o().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};Y($5,"instances",new WeakMap);var IL=$5,c1=new WeakMap,l1=(A,e)=>{if(e instanceof tC){let{stack:o}=e;e=new wo({code:Ro.OPERATION_ABORT,message:"".concat(A," abort: ").concat(e.message),fnName:A}),o&&(e.stack+=o.substr(o.indexOf(` -`)))}throw e};function WM(A,e){return jr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;Cfunction(){for(var C=arguments.length,y=new Array(C),S=0;S{var MA,$A;let Be=(MA=c1.get(this))==null?void 0:MA.get(J(...y));if(Be){let{timeoutId:ve,resolve:yi}=Be;clearTimeout(ve),yi()}let Ye=setTimeout(()=>{if(k.state===3||k.state===4)return gA();k.action(2,c.bind(this),y).catch(l1.bind(null,d)).then(gA,CA)},V);c1.has(this)?($A=c1.get(this))==null||$A.set(J(...y),{timeoutId:Ye,resolve:gA}):c1.set(this,new Map([[J(...y),{timeoutId:Ye,resolve:gA}]]))})}return k.action(2,c.bind(this),y).catch(l1.bind(null,d))})}function zM(A){return jr((e,o)=>function(){for(var a=arguments.length,c=new Array(a),d=0;dS.action(3,()=>Promise.resolve(),c))).then(()=>e.call(this,...c));let y=IL.get(this,C);return y?y.action(3,e.bind(this),c).catch(l1.bind(null,o)):e.apply(this,c)})}function ZM(){return function(A,e,o){return A.prototype[e]=function(){let a=this._log||console,c='"'.concat(e,'" is a static method. Use TRTC.').concat(e,"() instead. See: ").concat(qh,"/en/TRTC.html#.").concat(e);a.warn(c)},o}}var Hi={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},CiA=new Set([Hi.AUDIO_VOLUME,Hi.AUDIO_FRAME,Hi.NETWORK_QUALITY,Hi.STATISTICS,Hi.SEI_MESSAGE,Hi.CUSTOM_MESSAGE,Hi.LAYER_DATA]),Az={};Hh(Az,{ScheduleRequestType:()=>iz,getAbilityConfig:()=>hiA,getScheduleDomain:()=>Aj,isNeedToSchedule:()=>uL,scheduleProxy:()=>em,sendScheduleRequest:()=>tz,setIsNeedToSchedule:()=>hQ,setScheduleProxy:()=>$K});var I1=null,u1=0,ez=72e5,E1="trtc_schedule_cache",uL=!0;function hQ(A){Nr(A)&&A!==uL&&(uL=A,QA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(E1)}catch(e){QA.error("clearScheduleCache error",e)}}():u1=Date.now()+ez)}function tz(A){return KA(this,arguments,function(e){let{userId:o,sdkAppId:a,useStringRoomId:c,roomId:d,userSig:C,version:y,frameWorkType:S,role:k,latencyLevel:V}=e;return function*(){var J;if(!uL&&I1&&u1>Date.now())return{isCached:!0,result:I1};let gA={delta:0,count:[1,1],msg:[],detail:[]};try{let CA=new FormData;CA.append("userId",String(o)),CA.append("sdkAppId",String(a)),CA.append("isStrGroupId",String(c)),CA.append("groupId",String(d)),CA.append("sdkVersion",y),CA.append("userSig",String(C));let MA=((J=yield fM())==null?void 0:J.model)||Qk();MA&&CA.append("model",MA);let $A=Yp();$A&&CA.append("osString",$A);let Be=Pp();Be&&CA.append("gpu",Be),k&&CA.append("role",String(k)),V&&CA.append("latencyLevel",String(V)),S&&CA.append("frameWorkType",String(S));let Ye=ko(),ve=yield function(Ge,Bt,hi){return new Promise((Di,Vo)=>{let Jo=null;oM([oz(Qn=>Bt.count[0]=Qn+1,Qn=>{let{error:Ho,retry:Ns,retriedCount:pg,retryFuncArgs:ya}=Qn;Bt.msg[0]=Ho.message,Jo||(pg>=1&&(ya[0]=My(hi,"config",YA.MAIN,!0)),Ns())})(My(hi,"config",YA.MAIN),Ge,{get timeout(){return 1e3*Kf(2+Bt.count[0])}}),oz(Qn=>Bt.count[1]=Qn+1,Qn=>{let{error:Ho,retry:Ns,retriedCount:pg,retryFuncArgs:ya}=Qn;Bt.msg[1]=Ho.message,Jo||(pg>=2&&(ya[0]=My(hi,"config",YA.BACKUP,!0)),Ns())})(My(hi,"config",YA.BACKUP),Ge,{get timeout(){return 1e3*Kf(2+Bt.count[1])}})]).then(Qn=>{Jo=Qn,Di(Jo)}).catch(Vo)})}(CA,gA,a);ve.config&&(ve.config.loggerDomain&&VS(ve.config.loggerDomain),Nr(ve.config.scheduleCache)&&hQ(!ve.config.scheduleCache)),gA.delta=ko()-Ye;let yi=function(Ge,Bt,hi){let Di={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Vo=performance.getEntriesByType("resource"),Jo=My(Ge,"config",YA.MAIN),Qn=My(Ge,"config",YA.BACKUP);for(let Ho of Vo)if(Ho.startTime>=hi&&(Ho.name===Jo||Ho.name===Qn)&&Ho.transferSize>0){let Ns=Ho.name===Jo?YA.MAIN:YA.BACKUP,pg=Math.round(Ho.duration),ya=Math.round(Ho.domainLookupStart-Ho.startTime),Bu=Ho.redirectStart>0?Math.round(Ho.redirectEnd-Ho.redirectStart):0,BL=Ho.fetchStart>0?Math.round(Ho.domainLookupStart-Ho.fetchStart):0,m_=Math.round(Ho.domainLookupEnd-Ho.domainLookupStart),i8=Math.round(Ho.requestStart-Ho.secureConnectionStart),o8=Math.round(Ho.secureConnectionStart-Ho.connectStart),s8=Math.round(Ho.responseStart-Ho.requestStart),n8=Math.round(Ho.responseEnd-Ho.responseStart),JoA=[m_,i8,o8,s8,n8];sn.uploadEvent({log:"stat-schedule-net:".concat(pg,"(").concat(ya,"(").concat(Bu,"->").concat(BL,")->").concat(JoA.join("->"),") ").concat(Ns),userId:Bt}),Di=Qo(mi({},Di),{totalCost:pg,local:ya,dns:m_,tcp:o8,tls:i8,request:s8,response:n8});break}}catch(Vo){QA.error("getScheduleDetailCost error",Vo)}return Di}(Number(a),o,Ye);return I1=ve,function(Ge){if(typeof window<"u"&&typeof localStorage<"u")try{let Bt=Date.now()+ez;localStorage.setItem(E1,JSON.stringify({result:Ge,expireIn:Bt})),u1=Bt}catch(Bt){QA.error("saveScheduleToLocalStorage error",Bt)}}(ve),{isCached:!1,result:ve,detailCost:yi}}catch(CA){let MA=wa(CA)?CA[0]:CA,$A=bn(MA.code)?MA.code:0,Be="schedule failed".concat(MA.message?": ".concat(MA.message):""),Ye=new ai({code:dt.SCHEDULE_FAILED,extraCode:$A,message:Xo({key:Mo.JOIN_ROOM_FAILED,data:{error:Be,code:$A}})});throw QA.error(Be,$A),Ye}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(XB).map(A=>'')).join(`\r -`)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(E1);if(A){let{result:e,expireIn:o}=JSON.parse(A);o>Date.now()?(I1=e,u1=o,uL=!1):localStorage.removeItem(E1)}}catch(A){QA.error("loadScheduleFromLocalStorage error",A)}}(),F.on("28",()=>hQ(!0)),F.on("63",()=>hQ(!0)),F.on("84",()=>hQ(!0)),F.on("201",A=>{A.state==="RECONNECTING"&&hQ(!0)}),F.on("202",A=>{A.state==="RECONNECTING"&&hQ(!0)});var em={main:"",backup:""};function $K(A){wa(A)?(em.main=A[0],em.backup=A[1]):(em.main=A,em.backup=A)}var iz=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(iz||{});function My(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:YA.MAIN,a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(em[o]||Aj(A,o,a),"/api/v1/").concat(e)}function hiA(A,e,o){let a=My(A,e),c=My(A,e,YA.BACKUP),d=new URLSearchParams(o).toString(),C=fetch("".concat(a,"?").concat(d)).then(S=>S.json()),y=fetch("".concat(c,"?").concat(d)).then(S=>S.json());return oM([C,y])}function Aj(A){let e,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:YA.MAIN,a=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return e=Kd(A)?a?o===YA.MAIN?XB.MAIN_OVERSEA_BACKUP:XB.BACKUP_OVERSEA:o===YA.MAIN?XB.MAIN_OVERSEA:XB.BACKUP_OVERSEA:o===YA.MAIN?XB.MAIN:XB.BACKUP,e}function BiA(A,e,o){return new Promise((a,c)=>{eQ({url:A,body:e,timeout:o.timeout,priority:"high"}).then(d=>{d.data.code===0?a(d.data.data):c({code:d.data.code,message:d.data.msg})}).catch(c)})}var oz=(A,e)=>gM({retryFunction:BiA,settings:{retries:3,timeout:0},onError:e,onRetrying:A}),ej=class{constructor(){Y(this,"_log"),this._log=QA.createLogger({id:"fd"})}download(A,e){return KA(this,null,function*(){let{type:o="blob"}=e||{};A=jb(A);try{let a,c=ko();if(a=Ra(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!a||!a.data)throw new Error("data is empty");let d=ko()-c;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(d,"ms")),ii.addSuccessEvent({key:522700,cost:ko()-c}),a.data}catch(a){throw this._log.error("failed to download: ".concat(A,", error: ").concat(a)),ii.addFailedEvent({key:522700,error:a}),a}})}downloadWithFetch(A,e){return KA(this,null,function*(){this._log.info("download with fetch: ".concat(A,", return type: ").concat(e));try{let o,a=yield fetch(A);if(!a.ok){let c=new Error("network response was not ok: ".concat(a.status));throw c.status=a.status,c}return o=e==="arraybuffer"?yield a.arrayBuffer():yield a.blob(),{data:o}}catch(o){throw o}})}downloadWithXHR(A,e){return this._log.info("download with xhr: ".concat(A,", return type: ").concat(e)),new Promise((o,a)=>{let c=new XMLHttpRequest;c.open("GET",A,!0),c.responseType=e,c.onload=()=>{if(c.status===200||c.status===0&&c.response)o({data:c.response});else{let d=new Error("XHR failed, status: ".concat(c.status));d.status=c.status,a(d)}},c.onerror=a,c.send(null)})}loadWasm(A,e){return KA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(e)));let o=ko(),a=null,c=null;if(Ra(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(d=>d.startsWith("file://"))(A)&&Ra(fetch))try{let d=fetch(A);a=(yield WebAssembly.instantiateStreaming(d,e)).instance}catch(d){c=d}if(!a)try{let d=yield this.download(A,{type:"arraybuffer"});a=(yield WebAssembly.instantiate(d,e)).instance}catch(d){c=d}if(a){let d=ko()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(d,"ms")),ii.addSuccessEvent({key:522701,cost:d}),a}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(c)),ii.addFailedEvent({key:522701,error:c}),c})}loadScript(A){this._log.info("loadScript ".concat(A));let e=ko();return new Promise((o,a)=>{let c=document.createElement("script");c.type="text/javascript",c.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(ko()-e,"ms")),ii.addSuccessEvent({key:522702,cost:ko()-e,split:1e3}),o(c)},c.onerror=d=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(d?.message||JSON.stringify(d))),ii.addFailedEvent({key:522702}),a(d)},c.crossOrigin="anonymous",c.src=A,document.head.append?document.head.append(c):document.getElementsByTagName("head")[0].appendChild(c)})}};Ci([$h({settings:{timeout:0,retries:3},onError(A,e,o){var a;A?.status===404||(a=A?.message)!=null&&a.includes("404")?(this._log.warn("download 404, stop retry"),o(A)):e()},onRetrying(A){this._log.warn("download retrying: ".concat(A))}})],ej.prototype,"download"),Ci([$h({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],ej.prototype,"loadScript");var tj=new ej;function sz(A){let[e,o]=A,a=o.byteLength,c=parseInt(String(a/255),10),d=a%255,C=[];C.push(0,0,0,1,6,e);for(let S=0;SV+J.dataView.byteLength,0),C=new ArrayBuffer(d+e.data.byteLength),y=new DataView(C),S=new DataView(e.data),k=0;for(let V=0;Vc.isSEI);o?.(a.reverse())}catch{}return e}function lz(A){let{seiMessageList:e,isAudio:o,getNtpTime:a,isMain:c}=A;return new TransformStream({transform(d,C){let y=d;o?audioEncodePipeline.forEach(S=>{y=S({frame:y,ntp:a(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:""})}})}):videoEncodePipeline.forEach(S=>{y=S({frame:y,seiMessageList:e,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:"",streamType:c?"main":"auxiliary"})}})}),C.enqueue(y)}})}function Iz(A){let{userId:e,streamType:o,isAudio:a}=A;return new TransformStream({transform(c,d){let C=c;a?(audioDecodePipeline.forEach(y=>{C=y({frame:C,onAudioFrameNTPTime:S=>{self.postMessage({type:"audio-ntp",data:S,userId:e,streamType:o})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:C.data,userId:e})}})}),d.enqueue(C)):videoDecodePipeline.forEach(y=>{C=y({frame:C,onSEI:S=>{S.forEach(k=>{self.postMessage({type:"sei",seiPayloadType:k.seiPayloadType,data:k.seiPayload.buffer,userId:e,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:C.data,userId:e,streamType:o})}})}),d.enqueue(C)}})}function uz(A){let e=[i1],o=[az,nz,G5,rz,sz,lz,Iz,T0,aM,t1],a="const videoEncodePipeline=[".concat(A.videoEncodePipeline.toString(),`]; +} `),this.defaultProgam=this.createProgram(this.defaultVShader,this.defaultFShader),this._canvas.addEventListener("webglcontextlost",()=>{this.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let e="";return A&&(e=A.message,this.error=A,si.addFailedEvent({key:512702,error:A})),this.disconnect(),this.log.info("video context destroy".concat(e)?": ".concat(e):""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),A}set width(A){var e;(e=this.ctx)==null||e.viewport(0,0,A,this.height),super.width=A,this._canvas2d&&(this._canvas2d.width=A)}set height(A){var e;(e=this.ctx)==null||e.viewport(0,0,this.width,A),super.height=A,this._canvas2d&&(this._canvas2d.height=A)}setSize(A,e){var o;(o=this.ctx)==null||o.viewport(0,0,A,e),super.setSize(A,e),this._canvas2d&&(this._canvas2d.width=A,this._canvas2d.height=e)}createShader(A,e){let o=this.ctx,a=o.createShader(A);return o.shaderSource(a,e),o.compileShader(a),a}createProgram(A,e){let o=this.ctx,a=o.createProgram();return o.attachShader(a,A),o.attachShader(a,e),o.linkProgram(a),o.getProgramParameter(a,o.LINK_STATUS)||this.log.error(o.getProgramInfoLog(a)),a}};Y(dL,"UNAVAILABLE","unavailable"),hi([lc(Zs.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),si.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),si.addSuccessEvent({key:512700})}})],dL.prototype,"create"),hi([lc("created",Zs.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(dL.UNAVAILABLE,A),this.removeAllListeners()}})],dL.prototype,"destroy");var qC=dL,QQ=class extends EL{constructor(){super(...arguments),Y(this,"ctx")}create(A){if(this.hasAlpha=A.alpha,this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(EL._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(A){let e="";A&&(e=A.message,this.error=A,si.addFailedEvent({key:512703,error:A})),this.disconnect(),this.log.info("video context destroy ".concat(e?": ".concat(e):"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),si.addSuccessEvent({key:512703})}};function wiA(A,e,o,a,l){arguments.length>5&&arguments[5]!==void 0&&arguments[5]&&([o,a]=[a,o]);let d={sWidth:A,sHeight:e,dWidth:o,dHeight:a,sx:0,sy:0,dx:0,dy:0};if(A===0||e===0)return d;switch(l){case void 0:case"fill":break;case"contain":{let h=Math.min(o/A,a/e);d.dWidth=A*h,d.dHeight=e*h,d.dx=(o-d.dWidth)/2,d.dy=(a-d.dHeight)/2;break}case"cover":{let h=Math.max(o/A,a/e),y=o/h,S=a/h;d.sx=(A-y)/2,d.sy=(e-S)/2,d.sWidth=y,d.sHeight=S;break}}return d}hi([lc(Zs.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),si.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),si.addSuccessEvent({key:512701})}})],QQ.prototype,"create"),hi([lc("created",Zs.INIT,{ignoreError:!0,sync:!0})],QQ.prototype,"destroy");var _iA=class{constructor(A,e){this.node=A,this.layout=e,Y(this,"positionBuffer")}get x(){return this.layout.x||this.node.x}get y(){return this.layout.y||this.node.y}get width(){return this.layout.width||this.node.width}get height(){return this.layout.height||this.node.height}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get fillMode(){return this.layout.fillMode}get rotation(){return this.layout.rotation}get hidden(){return!!this.layout.hidden}},rz=class extends AC{constructor(A,e){super(A,{useDefaultProgram:!0,useFbo:!0,name:"mix",create2d:!0,logger:e}),Y(this,"inputs",[]),Y(this,"backgroundColor","black")}addInput(A,e){let o=0,a=this.inputs.length;for(;oe.zIndex))throw new Error("input already exists at zIndex ".concat(e.zIndex));a=d}}let l=new _iA(A,e);this.inputs.splice(o,0,l)}changeInputLayout(A,e){let o=this.inputs.findIndex(cA=>cA.node===A);if(o<0)return;let{x:a,y:l,width:d,height:h,zIndex:y,fillMode:S,rotation:k,hidden:V}=e;if(!Ke(y)&&this.inputs.some(cA=>cA.layout.zIndex===y&&cA.node!==A))throw new Error("input already exists at zIndex ".concat(e.zIndex));let J=this.inputs[o];Ke(a)||(J.layout.x=a),Ke(l)||(J.layout.y=l),Ke(d)||(J.layout.width=d),Ke(h)||(J.layout.height=h),Ke(k)||(J.layout.rotation=k),Ke(V)||(J.layout.hidden=V),S&&(J.layout.fillMode=S),!Ke(y)&&y!==J.layout.zIndex&&(J.layout.zIndex=y,this.inputs.sort((cA,CA)=>cA.layout.zIndex-CA.layout.zIndex))}hasInput(A){return this.inputs.some(e=>e.node===A)}hasNoInput(){return this.inputs.length===0}resize(A,e){if(!this.matchInputSize)return void super.resize(A,e);let o=this.inputs.reduce((a,l)=>l?Object.assign(a,{width:Math.max(a.width,l.right),height:Math.max(a.height,l.bottom)}):a,{width:0,height:0});super.resize(o.width,o.height),this.context instanceof qC&&this.inputs.forEach(a=>{if(a){let l=this.layout2texCoords(a);a.positionBuffer?this.changeBufferData(a.positionBuffer,l):a.positionBuffer=this.createBuffer(l)}})}connect(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;ae.node!==A),this.inputs.length===0&&this.drawBackGround2d(this.backgroundColor)}render(A){let e=this.context.ctx;if(e.clearColor(0,0,0,0),this.inputs.reduce((o,a)=>a.node.requestFrame(A)||o,!1)&&e){this.useProgram(),e.enable(e.BLEND),e.blendFunc(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA),this.useBufferFrame();for(let o=0;oe.node.requestFrame(A)),this.ctx2d){this.drawBackGround2d(this.backgroundColor);for(let e=0;e4&&arguments[4]!==void 0&&arguments[4];this.ctx2d&&(l&&([o,a]=[a,o]),this.ctx2d.save(),this.ctx2d.strokeStyle="red",this.ctx2d.lineWidth=2,this.ctx2d.strokeRect(A,e,o,a),this.ctx2d.restore())}getInfo(){let{totalFrames:A,x:e,y:o,width:a,height:l,name:d}=this,h=Date.now(),y=(A-this.lastInfo.totalFrames)/((h-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:A,x:e,y:o,width:a,height:l,timestamp:h,fps:y,name:d},fi({parent:this.inputs.filter(S=>S).map(S=>S.node.getInfo())},this.lastInfo)}removeAllInputs(){this.inputs.forEach(A=>{var e;if(A.node.disconnect(),A.positionBuffer&&this.context instanceof qC)try{(e=this.context.ctx)==null||e.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},TiA=[1,0,0,0,1,1,0,1],Ry=class extends AC{constructor(A,e,o,a){if(super(A,{useDefaultProgram:!0,useFbo:!0,create2d:!0,name:"transform",logger:e}),Y(this,"mirror",!1),Y(this,"rotation",0),o&&(this.mirror=o),a&&(this.rotation=a),A instanceof qC)try{this.setTexBuffer(TiA)}catch(l){A.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:3,message:"create video node ".concat(this.name," error ").concat(l.message||l)}))}}draw2d(A,e,o,a,l){if(this.ctx2d){this.ctx2d.clearRect(0,0,this.width,this.height),this.ctx2d.save(),this.mirror&&(this.ctx2d.scale(-1,1),this.ctx2d.translate(-this.width,0)),this.rotation===90?(this.ctx2d.translate(a,0),this.ctx2d.rotate(Math.PI/2),this.ctx2d.scale(l/a,a/l)):this.rotation===180?(this.ctx2d.translate(this.width,this.height),this.ctx2d.rotate(Math.PI)):this.rotation===270&&(this.ctx2d.translate(0,l),this.ctx2d.rotate(3*Math.PI/2),this.ctx2d.scale(l/a,a/l));let d=super.draw2d(A,e,o,a,l);return this.ctx2d.restore(),d}return!1}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}resize(A,e){tQ(this.rotation)&&([A,e]=[e,A]),super.resize(A,e)}},gj=class extends lL{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,Ro),Y(this,"inputLocalVideoTracks",new Map),Y(this,"inputLocalScreenTracks",new Map),Y(this,"cameraNodeMap",new Map),Y(this,"screenNodeMap",new Map),Y(this,"textNodeMap",new Map),Y(this,"imageNodeMap",new Map),Y(this,"videoNodeMap",new Map),Y(this,"endedIds",new Set),Y(this,"videoContext"),Y(this,"mixNode"),Y(this,"destination"),Y(this,"manager"),Y(this,"stat"),Y(this,"_checkId",0),Y(this,"autoSetFps",!0),this.manager=A,this.log.id+="mix",this.create2dVideoContext(),this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(AC.RENDER,e=>{this.emit("render",e)}),this.mixNode=new rz(this.videoContext,this.log),this.mixNode.matchInputSize=!1}listenDeviceChange(){throw new Error("Method not implemented.")}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=Gr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new QQ({frameRate:15,logger:this.log,name:"mix-ctx"}),this.videoContext.create({alpha:!1})}setFps(A){this.autoSetFps=!1,this.videoContext.frameRate=A;for(let e of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])e.shouldUpdate=!1;setTimeout(()=>{var e;return(e=this.destination)==null?void 0:e.start(this.videoContext.frameRate)},500)}setFpsAuto(){var A;if(!this.autoSetFps)return;for(let l of[...this.cameraNodeMap.values(),...this.screenNodeMap.values()])l.shouldUpdate=!1;let e=null,o=0,a=!0;for(let[l,d]of this.inputLocalVideoTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.cameraNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,e=l}for(let[l,d]of this.inputLocalScreenTracks)if(d.profile.frameRate>o){if(this.endedIds.has(l)){let h=this.screenNodeMap.get(l);h&&h.image.cancelVideoFrameCallback(h.videoCallbackId);continue}o=d.profile.frameRate,e=l,a=!1}if(e!==null){let l=a?this.cameraNodeMap.get(e):this.screenNodeMap.get(e);l&&(l.shouldUpdate=!0,l.tryVideoFrameCallback()),this.log.info("set mix fps: ",o)}else(A=this.destination)==null||A.start(this.videoContext.frameRate),this.log.info("fallback to timer, fps: ",this.videoContext.frameRate)}setMixBackground(A){this.mixNode&&(this.mixNode.backgroundColor=A)}resizeMixCanvas(A,e){var o;(o=this.mixNode)==null||o.resize(A,e)}startMix(){return WA(this,null,function*(){var A;if(!this.mixNode||!this.destination)throw new Error("can't mix without necessary conditions");this.mixNode.disconnect(),this.mixNode.connect(this.destination),xp&&this.player.setCanvas(this.videoContext._canvas),this.setOutputMediaStreamTrack(this.destination.videoTrack),(A=this.manager)==null||A.changeInput(this)})}addCameraSource(A,e,o){if(this.inputLocalVideoTracks.has(A)||this.cameraNodeMap.has(A))throw new Error("There is already a cameraSource with the same ID: ".concat(A));let a,{mediaTrack:l}=e;if(!l)throw new Error("no mediaTrack, add cameraSource failed");e.recaptureMode=1,nd(this,Pc).add("videoInputRemoved",d=>{d.deviceId===e.deviceId&&(this.endedIds.add(A),this.setFpsAuto())}),e.on("output-media-track-changed",()=>{this.endedIds.delete(A),this.updateCameraSource(A,o,e.mediaTrack)}),a=Zd===16&&l instanceof CanvasCaptureMediaStreamTrack?this.videoContext.createVideoImageSource(l.canvas,{name:"cameraCanvasSource",logger:this.log}):this.videoContext.createVideoTrackSource(l,"cameraNodeSource"),a.resize(e.settings.width,e.settings.height),a.shouldUpdate=!1,this._connectMix(a,o,"cover"),this.inputLocalVideoTracks.set(A,e),this.cameraNodeMap.set(A,a),this.setFpsAuto()}addScreenSource(A,e,o){if(this.inputLocalScreenTracks.has(A)||this.screenNodeMap.has(A))throw new Error("There is already a screenSource with the same ID: ".concat(A));let{mediaTrack:a}=e;if(!a)throw new Error("no mediaTrack, add screenSource failed");e.on("output-media-track-changed",()=>{this.updateScreenSource(A,o,e.mediaTrack)});let l=this.videoContext.createVideoTrackSource(a,"screenNodeSource");l.resize(e.settings.width,e.settings.height),l.shouldUpdate=!1,this._connectMix(l,o),this.inputLocalScreenTracks.set(A,e),this.screenNodeMap.set(A,l),this.setFpsAuto()}addTextSource(A){let{id:e,content:o="",font:a,color:l,layout:d}=A;if(this.textNodeMap.has(e))throw new Error("There is already a textSource with the same ID: ".concat(e));let h=this.videoContext.createTextSource({content:o,font:a,color:l});h.resize(d.width,d.height),this._connectMix(h,d),this.textNodeMap.set(e,h)}addImageSource(A,e,o){if(this.imageNodeMap.has(A))throw new Error("There is already a imageSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});a.resize(e.width,e.height),this._connectMix(a,o),this.imageNodeMap.set(A,a)}addVideoSource(A,e,o){if(this.videoNodeMap.has(A))throw new Error("There is already a videoSource with the same ID: ".concat(A));let a=this.videoContext.createVideoImageSource(e,{autoResize:!1,logger:this.log});a.resize(e.videoWidth,e.videoHeight),a.shouldUpdate=!1,this._connectMix(a,o),this.videoNodeMap.set(A,a)}updateCameraSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=arguments.length>3?arguments[3]:void 0,l=this.inputLocalVideoTracks.get(A);l&&o&&o!==l.mediaTrack&&(this.log.debug("updateCameraSource mixerLocalVideoTrack newTrack:",o,"oldTrack:",l.mediaTrack),l.setInputMediaStreamTrack(o));let d=this.cameraNodeMap.get(A);if(d){if(o){if(Zd===16&&o instanceof CanvasCaptureMediaStreamTrack)if(d instanceof d_){let S=d.output;d.close(),d=this.videoContext.createVideoImageSource(o.canvas,{name:"cameraCanvasSource",logger:this.log}),d.connect(S),this.cameraNodeMap.set(A,d)}else d.image=o.canvas;else if(d instanceof d_)d.replaceTrack(o);else{let S=d.output;d.close(),d=this.videoContext.createVideoTrackSource(o,"cameraNodeSource"),d.connect(S),this.cameraNodeMap.set(A,d)}let{width:h,height:y}=o.getSettings();h&&y&&d.resize(h,y)}a&&d.resize(a.width,a.height),(a||o)&&this.setFpsAuto(),this._changeMixLayout(d,e)}}updateScreenSource(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:null,a=this.inputLocalScreenTracks.get(A);this.log.debug("updateScreenSource mixerLocalScreenTrack",a,o),a&&o&&o!==a.mediaTrack&&a.setInputMediaStreamTrack(o);let l=this.screenNodeMap.get(A);l&&(o&&l.replaceTrack(o),this._changeMixLayout(l,e))}updateTextSource(A){let{id:e,content:o,font:a,color:l,layout:d}=A,h=this.textNodeMap.get(e);h&&(Ke(o)||(h.content=o),Ke(a)||(h.font=a),Ke(l)||(h.color=l),h.resize(d.width,d.height),this._changeMixLayout(h,d))}updateImageSource(A,e,o){let a=this.imageNodeMap.get(A);a&&(o&&(a.image=o,a.resize(o.width,o.height)),this._changeMixLayout(a,e))}updateVideoSource(A,e,o){let a=this.videoNodeMap.get(A);if(a){if(o){let l=a.image;l instanceof HTMLVideoElement&&this.stopVideoElement(l),a.image=o,a.resize(o.videoWidth,o.videoHeight)}this._changeMixLayout(a,e)}}_connectMix(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"contain";if(!this.mixNode)return;let{mirror:a,rotation:l}=e;A.disconnect();let d=new Ry(this.videoContext,this.log,a,l);d=A.connect(d),e.fillMode||(e.fillMode=o),d.connect(this.mixNode,e)}_changeMixLayout(A,e){if(!this.mixNode)return;let{mirror:o,rotation:a}=e,l=A.output||A;l instanceof Ry&&(Ke(o)||(l.mirror=o),Ke(a)||(l.rotation=a),l.resize(A.width,A.height)),this.mixNode.changeInputLayout(l,e)}removeCameraSource(A){let e=this.inputLocalVideoTracks.get(A);if(!e)return;e.close(),this.inputLocalVideoTracks.delete(A);let o=this.cameraNodeMap.get(A);o&&(o.output instanceof Ry&&o.output.close(),o.close(),this.cameraNodeMap.delete(A)),this.checkAfterRemove(!0)}removeScreenSource(A){let e=this.inputLocalScreenTracks.get(A);if(!e)return;e.close(),this.inputLocalScreenTracks.delete(A);let o=this.screenNodeMap.get(A);o&&(o.output instanceof Ry&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let e=this.textNodeMap.get(A);e&&(e.output instanceof Ry&&e.output.close(),e.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let e=this.imageNodeMap.get(A);e&&(e.output instanceof Ry&&e.output.close(),e.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let e=this.videoNodeMap.get(A);e&&(e.output instanceof Ry&&e.output.close(),e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image),e.close(),this.videoNodeMap.delete(A)),this.checkAfterRemove()}checkAfterRemove(){arguments.length>0&&arguments[0]!==void 0&&arguments[0]&&this.setFpsAuto()}stopVideoElement(A){A.pause(),A.src="",A.srcObject=null,A.remove()}close(){var A;super.close(),Gr.clearTask(this._checkId),(A=this.videoContext)==null||A.destroy(),delete this.mixNode,delete this.destination;for(let e of[...this.inputLocalVideoTracks.values(),...this.inputLocalScreenTracks.values()])e.close();this.inputLocalVideoTracks.clear(),this.inputLocalScreenTracks.clear(),this.cameraNodeMap.clear(),this.screenNodeMap.clear(),this.textNodeMap.clear(),this.imageNodeMap.clear(),Ln(this);for(let e of this.videoNodeMap.values())e.image instanceof HTMLVideoElement&&this.stopVideoElement(e.image);this.videoNodeMap.clear(),this.log.info("localMixVideoTrack close, stop mix")}},cj=PA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:cj,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var NiA=function(A){return WA(this,null,function*(){let e=null,o=function(d){let h={preferCurrentTab:d.preferDisplaySurface==="current-tab"||!!d.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},y={width:Bg?{max:d.width}:{ideal:d.width,max:d.width},height:Bg?{max:d.height}:{ideal:d.height,max:d.height},frameRate:d.frameRate,displaySurface:d.preferDisplaySurface||"monitor"};if(h.video=y,d.systemAudio){let{echoCancellation:S=!0,noiseSuppression:k=!1,autoGainControl:V=!1}=d;h.audio={echoCancellation:S,noiseSuppression:k,autoGainControl:V,sampleRate:48e3}}return h}(A);pA.info("getDisplayMedia with constraints: ".concat(JSON.stringify(o)));let a=yield navigator.mediaDevices.getDisplayMedia(o);A.systemAudio&&a.getAudioTracks().length===0&&(K0&&td<74||Bg||or)&&pA.warn("Your browser not support capture system audio");let l=a.getVideoTracks()[0];if(l){if(A.frameRate)try{yield l.applyConstraints({frameRate:{min:A.frameRate,ideal:A.frameRate},width:A.width,height:A.height})}catch(d){pA.warn("screen applyConstraints failed: ".concat(d))}A.captureElement&&(yield function(d,h){return WA(this,null,function*(){var y;if("CropTarget"in window&&"fromElement"in CropTarget&&Ra(d.cropTo))try{if(((y=d.getCaptureHandle())==null?void 0:y.handle)!==cj)return;let S=yield CropTarget.fromElement(h);yield d.cropTo(S)}catch(S){pA.warn("cropTo target failed ".concat(S))}})}(l,A.captureElement))}if(A.audio){let d=function(h){let y={echoCancellation:h.echoCancellation,autoGainControl:h.autoGainControl,noiseSuppression:h.noiseSuppression,sampleRate:h.sampleRate,channelCount:h.channelCount};return Ke(h.microphoneId)||(y.deviceId=h.microphoneId),{audio:y,video:!1}}(A);pA.info("getUserMedia with constraints: ".concat(JSON.stringify(d))),e=yield navigator.mediaDevices.getUserMedia(d),a.addTrack(e.getAudioTracks()[0])}return a})},WM=class extends BQ{constructor(A){super(A,2),Y(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Y(this,"objectFit","contain"),Y(this,"isScreen",!0),this._log.id="s-".concat(this._log.id)}get isShareCurrentTab(){var A,e;try{return cj===((e=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:e.handle)}catch{return}}capture(A){return WA(this,arguments,function(e){var o=this;let{systemAudio:a=!1,autoGainControl:l,echoCancellation:d,noiseSuppression:h,audioTrack:y,videoTrack:S,captureElement:k,preferDisplaySurface:V}=e;return function*(){var J;try{let cA,CA=ko();return S||y?(cA=new MediaStream,S&&cA.addTrack(S),y&&cA.addTrack(y)):(cA=yield NiA({audio:!1,systemAudio:a,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:l,echoCancellation:d,noiseSuppression:h,captureElement:k,preferDisplaySurface:V}),o.sourceTrack=cA.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(cA.getVideoTracks()[0]),F.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:ko()-CA,profile:o.profile,room:(J=o.manager)==null?void 0:J.room}),cA}catch(cA){throw o.log.error("getDisplayMedia error observed ".concat(cA)),cA instanceof gi?cA:new gi({code:Ct.INITIALIZE_FAILED,name:cA.name,message:cA.message})}}()})}switchDevice(A){return WA(this,null,function*(){throw new Error("Method not implemented.")})}};hi([qM(function(A){this.setContentHint(A.contentHint||"detail")})],WM.prototype,"capture");var lj,Ij=class extends jM{constructor(A){super(A),this._log.id="s-".concat(this._log.id),this.isScreen=!0}addAudioProcessor(A,e,o){this.pipeline.silentNode.setNode(o),this.pipeline.mixNode.setNode(e),this.pipeline.aec.setNode(A),this.enableTrackAEC(!1)}removeAudioProcessor(A){this.pipeline.aec.node===A&&(this.pipeline.aec.deleteNode(),this.pipeline.silentNode.deleteNode(),this.pipeline.mixNode.deleteNode(),this.enableTrackAEC(!0))}};function uj(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,a=arguments.length>3?arguments[3]:void 0;return WA(this,null,function*(){let l=OI();lj||(lj=Vg(l,URL.createObjectURL(new Blob(['registerProcessor("dumper",class extends AudioWorkletProcessor{constructor(e){super(),this.sourceSampleRate=e.processorOptions.sourceSampleRate||48e3,this.targetSampleRate=e.processorOptions.targetSampleRate||48e3,this.port.onmessage=e=>{this.port2=e.data.port}}process(e){return(this.port2||this.port).postMessage(this.resampleAll(e,this.sourceSampleRate,this.targetSampleRate)),!0}resampleAll(r,s,a){if(s===a)return r;var o=[];for(let t=0;ty.connect(h,0,S)),new ReadableStream({start(y){h.port.onmessage=S=>{y.enqueue(S.data)}},cancel(){A.forEach(y=>y.disconnect(h)),h.port.close()}})})}var GiA=class extends jeA{constructor(A){super(),this.room=A,Y(this,"_localAudioTrack"),Y(this,"_localScreenAudioTrack"),Y(this,"log"),Y(this,"denoiser"),Y(this,"voiceChanger"),Y(this,"mixChangedDebounce"),Y(this,"audioProcessor"),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"getPCMAbortCtrlMap",new Map),Y(this,"audioFrameEventConfigMap",new Map),Y(this,"audioReferenceMap",new Map),Y(this,"isLocalAudioNeedAudioProcess",!1),Y(this,"isScreenAudioNeedAudioProcess",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"am",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.installEvent()}get localAudioTrack(){return this._localAudioTrack}get _localAudioPipline(){var A;return(A=this._localAudioTrack)==null?void 0:A.pipeline}get _localScreenAudioPipeline(){var A;return(A=this._localScreenAudioTrack)==null?void 0:A.pipeline}dump(A){var e,o;if(!this._localAudioTrack)return;let a=[],l=[];(e=this._localAudioPipline)!=null&&e.source.node&&(a.push(this._localAudioPipline.source.node),l.push("mic")),(o=this._localAudioPipline)!=null&&o.denoiser.node&&(a.push(this._localAudioPipline.denoiser.node),l.push("mic-processed")),this.mixWeight>1&&(a.push(this.audioContext.createMediaStreamSource(this._localAudioPipline.stream)),l.push("mix")),this.log.info("dump audio track ".concat(l,", duration: ").concat(A));let d=new AbortController,h=[],y=setTimeout(()=>{this.log.info('dump audio track complete please input "download()" to download.'),d.abort("timeout")},1e3*A),S=()=>{for(let V=0;VV.pipeTo(new WritableStream({write(J){J.forEach((cA,CA)=>h[CA]=h[CA]?h[CA].concat(cA[0]):[cA[0]])}}),d).catch(J=>S));return{then:k.then.bind(k),download:S}}getPCM(A,e){var o,a,l;if(typeof WritableStream>"u")return void this.log.warn("getPCM failed: browser not support WritableStream");let{enable:d,sampleRate:h=48e3,channelCount:y=1,port:S}=(e===""?this.audioFrameEventConfigMap.get(""):this.audioFrameEventConfigMap.get(e)||this.audioFrameEventConfigMap.get("*"))||{};if(!d)return;this.log.info("getPCM ".concat(e||"local"));let k,V,J=Math.floor(.04*h),cA=new Float32Array(J),CA=new Float32Array(J),MA=0,ie=new AbortController,pe=e===""?(o=this._localAudioTrack)==null?void 0:o.mediaTrack:(l=(a=this.room)==null?void 0:a.remotePublishedUserMap.get(e))==null?void 0:l.remoteAudioTrack.mediaTrack;if(pe)return uj([OI().createMediaStreamSource(new MediaStream([pe]))],h,y,S).then(qe=>qe.pipeTo(new WritableStream({write(we){we[0][0]&&(MA+we[0][0].length>J?(cA.set(we[0][0].subarray(0,J-MA),MA),k=we[0][0].subarray(J-MA),we[0][1]&&(CA.set(we[0][1].subarray(0,J-MA),MA),V=we[0][1].subarray(J-MA)),MA+=J-MA):(k&&(cA.set(k,MA),MA+=k.length,k=void 0),V&&(CA.set(V,MA),V=void 0),cA.set(we[0][0],MA),we[0][1]&&CA.set(we[0][1],MA),MA+=we[0][0].length),MA>=J&&(MA=0,A({userId:e,sampleRate:h,channelCount:y,data:y===1?cA:[cA,CA]}),cA=new Float32Array(J),CA=new Float32Array(J)))}}),ie).catch(we=>this.log.warn("stop getPCM reason:".concat(we)))),ie;this.log.info("getPCM failed: ".concat(e||"local"," has no audio track"))}get hasScreenAudioTrack(){return!Ke(this._localScreenAudioTrack)}get hasAudioTrack(){return!Ke(this._localAudioTrack)}changeInput(A){var e,o;return A instanceof Ij?(this._localScreenAudioTrack=A,this.isScreenAudioNeedAudioProcess&&(e=this.audioProcessor)!=null&&e.screenAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.screenAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof jM?(this._localAudioTrack=A,this.denoiser&&A.addDenoiser(this.denoiser),this.isLocalAudioNeedAudioProcess&&(o=this.audioProcessor)!=null&&o.localAudioWorkletNode&&(A.addAudioProcessor(this.audioProcessor.localAudioWorkletNode,this.audioProcessor.mixNode,this.audioProcessor.silentNode),this.audioReferenceMap.forEach((a,l)=>{A.mixAudioReference(a,l)})),A.pipeline.connect(),this.mixOnChange()):A instanceof d1?A.setOutputMediaStreamTrack(A.mediaTrack):void 0}mixAudioReference(A,e){var o;(o=this._localAudioTrack)==null||o.mixAudioReference(A,e)}unMixAudioReference(A){var e;(e=this._localAudioTrack)==null||e.unMixAudioReference(A)}setAudioReferenceVolume(A,e){var o;(o=this._localAudioTrack)==null||o.setAudioReferenceVolume(A,e)}mixOnChange(){return this.mixChangedDebounce||(this.mixChangedDebounce=Promise.resolve().then(()=>{var A,e;return delete this.mixChangedDebounce,Promise.all([(A=this._localAudioTrack)==null?void 0:A.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localAudioTrack.mediaTrack),(e=this._localScreenAudioTrack)==null?void 0:e.setOutputMediaStreamTrack(this.mixWeight>1?this.mixTrack:this._localScreenAudioTrack.mediaTrack)])})),this.mixChangedDebounce}removeInput(A){A instanceof Ij?delete this._localScreenAudioTrack:A instanceof jM&&delete this._localAudioTrack}addDenoiser(A){var e;this.denoiser=A,(e=this._localAudioTrack)==null||e.addDenoiser(A)}addAudioProcessor(A,e,o,a){var l;this.audioProcessor={localAudioWorkletNode:o,mixNode:A,silentNode:e,screenAudioWorkletNode:a},this.isLocalAudioNeedAudioProcess&&this._localAudioTrack&&o&&(this._localAudioTrack.addAudioProcessor(o,A,e),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localAudioTrack)==null||y.mixAudioReference(d,h)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&a&&((l=this._localScreenAudioTrack)==null||l.addAudioProcessor(a,A,e),this.audioReferenceMap.forEach((d,h)=>{var y;(y=this._localScreenAudioTrack)==null||y.mixAudioReference(d,h)}))}removeDenoiser(A){var e;return delete this.denoiser,(e=this._localAudioTrack)==null?void 0:e.removeDenoiser(A)}addVoiceChanger(A,e){var o;this.voiceChanger=[A,e],(o=this._localAudioTrack)==null||o.pipeline.voiceChanger.setNode(A,e)}removeVoiceChanger(){var A;delete this.voiceChanger,(A=this._localAudioTrack)==null||A.pipeline.voiceChanger.deleteNode()}removeAudioProcessor(A,e){var o,a;delete this.audioProcessor,(o=this._localAudioTrack)==null||o.removeAudioProcessor(A),(a=this._localScreenAudioTrack)==null||a.removeAudioProcessor(e)}destroy(){this.close(),this.audioReferenceMap.clear(),this.getPCMAbortCtrlMap.forEach(A=>A?.abort("destroy")),this.getPCMAbortCtrlMap.clear(),this.audioFrameEventConfigMap.clear(),this.uninstallEvent()}addEncodeProcessor(A){let{processor:e,type:o}=A;var a;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var a;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}handleLocalTrackStarted(A){let{room:e,userId:o}=A;var a;if(e!==this.room||this.getPCMAbortCtrlMap.get(o))return;let l=this.getPCM(d=>{var h;(h=this.room)==null||h.emit("audio-frame",d)},"");this.getPCMAbortCtrlMap.set(o,l),this.getPCMAbortCtrlMap.get(o)&&((a=this._localAudioTrack)==null||a.on("input-media-track-changed",()=>{let d=this.getPCMAbortCtrlMap.get(o);d&&(d.abort("inputMediaTrackChanged"),d=this.getPCM(h=>{var y;(y=this.room)==null||y.emit("audio-frame",h)},""),this.getPCMAbortCtrlMap.set(o,d))}))}handleLocalTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopLocalAudio"),this.getPCMAbortCtrlMap.delete(o))}handleRemoteTrackStarted(A){let{room:e,userId:o}=A;if(e===this.room&&!this.getPCMAbortCtrlMap.get(o)){let a=this.room.audioManager.getPCM(l=>{var d;(d=this.room)==null||d.emit("audio-frame",l)},o);this.getPCMAbortCtrlMap.set(o,a)}}handleRemoteTrackStopped(A){let{room:e,userId:o}=A;if(e!==this.room)return;let a=this.getPCMAbortCtrlMap.get(o);a&&(a.abort("stopRemoteAudio"),this.getPCMAbortCtrlMap.delete(o))}installEvent(){F.on("113",this.handleLocalTrackStarted,this),F.on("114",this.handleLocalTrackStopped,this),F.on("115",this.handleRemoteTrackStarted,this),F.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){F.off("113",this.handleLocalTrackStarted),F.off("114",this.handleLocalTrackStopped),F.off("115",this.handleRemoteTrackStarted),F.off("116",this.handleRemoteTrackStopped)}updateAudioReference(A){let{type:e,audioReference:o,refId:a,volume:l}=A;if(e==="add"){if(this.audioReferenceMap.get(a)||!o||(this.audioReferenceMap.set(a,o),!this.audioProcessor))return;this.mixAudioReference(o,a)}else if(e==="remove")this.audioReferenceMap.get(a)&&(this.audioReferenceMap.delete(a),this.unMixAudioReference(a));else if(e==="updateVolume"){if(!this.audioProcessor||Ke(l))return;this.setAudioReferenceVolume(a,l)}}};function E1(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return jr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{let k=setTimeout(()=>{let V=new gi({code:Ct.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(a,"() timeout ").concat(A,"s")});(this.log||this._log||pA).warn(V),e===2?S(V):e===1&&y()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(k),o.apply(this,d).then(y,S).finally(()=>{clearTimeout(k),this._checkPendingPromiseSet&&k&&this._checkPendingPromiseSet.delete(k)})})})}var zM=class X3 extends zK{constructor(e,o,a){super({userId:o.userId,sdkAppId:e.sdkAppId,mediaType:a,room:e}),this.room=e,this.user=o,Y(this,"tinyId"),Y(this,"isRemote",!0),Y(this,"jitterBufferDelay",0),Y(this,"availableState"),Y(this,"remotePublishState"),Y(this,"_triggerCheckDecodeSubject",hQ(la(this,X3.STATE_SUBSCRIBE))),Y(this,"ignoreUpdatePlayingState"),this.tinyId=o.tinyId,this.availableState=new Zs("".concat(o.userId,"-").concat(this.mediaType,"-available"),"remote-track-available"),this.remotePublishState=new Zs("".concat(o.userId,"-").concat(this.mediaType,"-remote-publish"),"remote-track-publish"),ma(XK(la(this,Zs.STATECHANGED),la(this.remotePublishState,Zs.STATECHANGED)),oj(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Bl(y=>{this.availableState.state!==(y?Zs.ON:Zs.OFF)&&(this.availableState.state=y?Zs.ON:Zs.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(y)}));let l=ma(la(this.player,yo.ERROR),KM(y=>y.code===MediaError.MEDIA_ERR_DECODE)),d=ma(ej(5e3),KM(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===YA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),h=ma(F5(l,d),dE(la(this,Zs.INIT)));ma(this._triggerCheckDecodeSubject,KM(()=>!this.ignoreDecodeError),l1(h),Bl(y=>{this.reportDecodeResult(!1,y)}))}setMute(e){this.isRemotePublished&&super.setMute(e)}setInputMediaStreamTrack(e){super.setInputMediaStreamTrack(e),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(e=>{this.mediaTrack?e():this.once("input-media-track-changed",e)})}get ignoreDecodeError(){var e,o,a,l;return(l=(a=(o=(e=this.room)==null?void 0:e.networkQuality)==null?void 0:o.hadRecentBadDownlink)==null?void 0:a.call(o,2))!=null&&l||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===X3.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Zs.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(e){return e}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(e,o){var a,l;let d=this.kind===YA.AUDIO;if(si[e?"addSuccessEvent":"addFailedEvent"]({key:d?504700:514702}),!d){let h=((a=this.room)==null?void 0:a.downlinkVideoCodec.toUpperCase())||"H264";si[e?"addSuccessEvent":"addFailedEvent"]({key:hy["DECODE_".concat(h,"_RESULT")]}),e||this.log.warn("".concat((l=this.room)==null?void 0:l.downlinkVideoCodec," decode failed"))}e||(si.addEnum({key:d?504701:514703,value:Jp()}),sn.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(cQ()||Hp()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===YA.AUDIO?"audioLevel: ".concat(this.getAudioLevel()):"framesDecoded: ".concat(this.stat.framesDecoded>0))),this.emit("decode-failed",{error:o}))}updatePlayingState(e){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===e){if(e&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info("abort play, isSubscribed: ".concat(this.isSubscribed," isAvailable: ").concat(this.isRemotePublished," hasTrack: ").concat(!!this.outMediaTrack," "));super.updatePlayingState(e)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Zs.ON:Zs.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};Y(zM,"STATE_SUBSCRIBE","subscribe"),hi([E1(5,1)],zM.prototype,"waitHasMediaTrack"),hi([lc(Zs.INIT,zM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),F.emit(nA.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),Sy(521716,!1)],zM.prototype,"subscribe"),hi([lc(zM.STATE_SUBSCRIBE,Zs.INIT,{sync:!0,success(){this.log.info("unsubscribed"),F.emit(nA.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],zM.prototype,"unsubscribe");var az=zM,d1=class extends az{constructor(A,e){super(A,e,1),Y(this,"volume",0),Y(this,"mediaType",1),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,end2EndDelay:0,jitterBufferDelay:0}),this.manager=A.audioManager}get dbVolume(){return e1.isRunning?this.player.pipeline.volumeMeter.getVolumeDb():Math.floor(Math.max(10*Math.log10(this.volume)+100,0))}onPlayerError(A){this.enableDecodeFrame&&(this._log.warn("use audio decoder"),this.room.enableInsertableStreams())}get enableDecodeFrame(){var A,e;return!!this.manager&&(this.manager.decodePipeline.some(o=>o)||((e=(A=this.player.element)==null?void 0:A.error)==null?void 0:e.code)===MediaError.MEDIA_ERR_DECODE&&s_().AudioDecoder&&zp)}get enableDecryptFrame(){return this.manager&&!!this.manager.decodePipeline[0]}decodeFrame(A){if(!this.manager)return A;let e=A;for(let[o,a]of this.manager.decodePipeline.entries()){if(!a)continue;let l={frame:A,track:this};if(o===1&&this.isAvailable&&this.room.role==="audience"&&(l.onAudioFrameNTPTime=d=>{let{ntp:h,frame:y,hasLeavingTag:S}=d;this.emit("audio-frame-with-ntp",{ntp:h,frame:y,hasLeavingTag:S})}),e=a(l),!e)return}return e}getAudioLevel(){if(!this.isAvailable)return 0;let A=this.volume||super.getAudioLevel();return A>1?1:A}getInternalAudioLevel(){return this.isAvailable?super.getInternalAudioLevel():0}get isRemotePublished(){return this.user.muteState.audioAvailable}},biA=class extends AC{constructor(A,e,o,a,l){super(A,{useDefaultProgram:!0,useFbo:!0,name:"alpha",create2d:!0,logger:e}),this.setContainer=a,Y(this,"initStat",{alphaStitchingType:1}),Y(this,"end",hQ()),Y(this,"minSize",320),Y(this,"maxSize",1280),Y(this,"draggable",!1),Y(this,"startDragX",0),Y(this,"startDragY",0),Y(this,"left",0),Y(this,"top",0),Y(this,"baseWidth",320),Y(this,"baseRatio"),Y(this,"container"),this.initStat=l,this.draggable=o,this.bindDragEvents(),si.addEnum({key:515700,value:1}),this.draggable&&si.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let e=dE(this.end);ma(la(A,"mousedown"),sj(this.startDrag.bind(this)),g1(()=>ma(la(window,"mousemove"),dE(la(window,"mouseup")))),e,Bl(this.doDrag.bind(this))),ma(la(A,"dblclick"),e,Bl(this.resetPosition.bind(this))),ma(la(A,"wheel"),e,Bl(this.handleZoom.bind(this))),this.renderCanvas()}else{if(!this.container)return;this.container.style.removeProperty("left"),this.container.style.removeProperty("top"),this.end.next()}}render(A){var e;return!((e=this.input)==null||!e.requestFrame(A))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),!0)}startDrag(A){A.preventDefault(),A.button===0&&(this.startDragX=A.clientX-this.left,this.startDragY=A.clientY-this.top)}renderCanvas(){let{container:A}=this;A||this.setContainer(),A&&this.baseRatio&&this.draggable&&(A.style.setProperty("width","".concat(this.baseWidth,"px")),A.style.setProperty("height","".concat(this.baseWidth/this.baseRatio,"px")),A.style.setProperty("position","fixed"),A.style.setProperty("left","".concat(this.left,"px")),A.style.setProperty("top","".concat(this.top,"px")))}doDrag(A){A.preventDefault(),this.left=A.clientX-this.startDragX,this.top=A.clientY-this.startDragY,this.renderCanvas()}handleZoom(A){A.preventDefault();let e=A.deltaY,o=this.context._canvas;o&&(this.baseWidth||(this.baseWidth=o.offsetWidth),this.baseWidth=e<0?Math.min(1.1*this.baseWidth,this.maxSize):Math.max(.9*this.baseWidth,this.minSize),this.renderCanvas())}resetPosition(){this.left=0,this.top=0,this.renderCanvas()}onRatioReset(){this.renderCanvas()}draw2d(A,e,o,a,l){var d;let{ctx2d:h}=this,y=this.context._canvas;if(!h||!y)return!1;let S=super.draw2d(A,e,o,a,l),k=h.getImageData(0,0,a,l),{data:V}=k,J=!1;if(this.initStat.alphaStitchingType===1){let cA=Math.floor(a/2);for(let CA=0;CA=100;V[ie+3]=we?255:0}J=super.draw2d(k,0,0,0,0,cA,l),y.width=cA}else if(this.initStat.alphaStitchingType===2){let cA=Math.floor(l/2);for(let CA=0;CA=100;V[ie+3]=we?255:0}J=super.draw2d(k,0,0,0,0,a,cA),y.height=cA}return(d=this.context.ctx)==null||d.clearRect(0,0,a,l),S&&J}close(){this.baseRatio=void 0,this.end.next(),this.end.complete()}},CL=class extends az{constructor(A,e){super(A,e,arguments.length>2&&arguments[2]!==void 0?arguments[2]:4),Y(this,"mediaType",4),Y(this,"source"),Y(this,"shouldRenderAlpha",!1),Y(this,"alphaNode"),Y(this,"shouldBeDraggable",!0),Y(this,"stat",{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,end2EndDelay:0,jitterBufferDelay:0,keyFramesDecoded:0}),Y(this,"_keyFrameCountLogged",!1),Y(this,"_keyFrameStartTimestamp",0),Y(this,"_keyFrameStartCount",0),Y(this,"_keyFrameIntervals",[]),Y(this,"_prevKeyFrameTimestamp",0),this.manager=A.videoManager,this.on("first-video-frame",o=>{this.room.emit("first-video-frame",o)}),this.on("first-frame-render",o=>{this.room.emit("first-frame-render",o)})}isAlphaSei(A){if(this.userId!==A.userId||A.seiPayloadType!==50)return!1;let e=new Uint8Array(A.data);return e.length%3==0&&e[0]===0&&e[1]===1&&e}play(A,e){return e!=null&&e.canvasRender&&!this.source&&this.useCanvasPlayer(),super.play(A,e).then(()=>{this.player.calculateStat(),F.emit("156",{track:this,player:this.player})})}updateAlphaRenderInfo(A){let e=this.isAlphaSei(A);if(e)if(this.alphaNode){let o=e[2];if(this.alphaNode.baseRatio&&this.alphaNode.initStat.alphaStitchingType===o)return;this.alphaNode.initStat={alphaStitchingType:o};let a=this.player.getElement();if(a){let l=a.videoWidth/a.videoHeight;l&&(this.alphaNode.baseRatio=l*(o===1?.5:2),this.alphaNode.onRatioReset())}this.player.canvas&&(this.player.canvas.id=this.generateAlphaCanvasName(o))}else this.shouldRenderAlpha=!0,this.player.shouldRenderAlpha=!0,this.useCanvasPlayer(e[2])}generateAlphaCanvasName(A){let e=dy[A];return"".concat("alpha","_").concat(e,"_").concat(this.userId)}useCanvasPlayer(A){if(this.log.info("useCanvasPlayer(), has element:".concat(!!this.player.element)),!this.player.element)return;let e=new QQ({frameRate:15,logger:this.log,name:this.shouldRenderAlpha&&A?this.generateAlphaCanvasName(A):this.userId});e.create({alpha:this.shouldRenderAlpha,willReadFrequently:this.shouldRenderAlpha});let o=new rj(e,{name:"remotePlayer",logger:this.log});if(this.source=e.createVideoPlayerSource(this.player),this.player.setCanvas(e._canvas),this.shouldRenderAlpha&&A){let a=()=>{!this.player.container||!this.alphaNode||(this.alphaNode.container=this.player.container,this.alphaNode.renderCanvas())},l=new biA(e,this.log,this.shouldBeDraggable,a,{alphaStitchingType:A});this.source.connect(l),l.connect(o),this.alphaNode=l}else this.source.connect(o);Zp()||(this.updateCanvasPlayerFPS=this.updateCanvasPlayerFPS.bind(this,e),this.room.on("heartbeat-report",this.updateCanvasPlayerFPS,this))}updateCanvasPlayerFPS(A){let e=this.decodeFPS,o=(a=e,[15,30,45,60].reduce((l,d)=>Math.abs(d-a)l.msg_user_info.str_identifier===this.userId))||{},o=this.mediaType===2?7:this.isSmall?3:2;if(!e||e.length===0)return 0;let a=e.find(l=>l.uint32_video_stream_type===o);return a?.uint32_video_dec_fps||0}stop(){return this.room.off("heartbeat-report",this.updateCanvasPlayerFPS,this),F.emit("157",{track:this,player:this.player}),this.alphaNode&&this.alphaNode.close(),super.stop()}decodeFrame(A){if(!this.manager)return A;for(let e of this.manager.decodePipeline)if(e&&!(A=e({frame:A,track:this})))return;return A}get isBig(){return this.mediaType===4}get isSmall(){return this.mediaType===8}changeType(A){this.room.changeType(A,this.user)}get isRemotePublished(){return this.user.muteState.videoAvailable}setMirror(A){A==="publish"||A==="both"||super.setMirror(A)}setDraggable(A){this.shouldBeDraggable=A,this.alphaNode&&(this.alphaNode.draggable=A,this.alphaNode.bindDragEvents())}onDecodeDowngradeStateChanged(A){this.emit("decode-downgrade-state-changed",A)}updateKeyFramesDecoded(A){let e=this.stat.keyFramesDecoded||0;if(this.stat.keyFramesDecoded=A,this._keyFrameCountLogged)return;let o=Date.now();if(!this._keyFrameStartTimestamp)return this._keyFrameStartTimestamp=o,this._keyFrameStartCount=A,void(this._prevKeyFrameTimestamp=o);if(this._prevKeyFrameTimestamp&&A>e){let l=A-e,d=(o-this._prevKeyFrameTimestamp)/1e3/l;this._keyFrameIntervals.push(d)}this._prevKeyFrameTimestamp=o;let a=o-this._keyFrameStartTimestamp;if(a>=16e3){let l=A-this._keyFrameStartCount,d=l>0?a/1e3/l:0,h="".concat(l," keyframes in 16s ").concat(d," [").concat(this._keyFrameIntervals.map(S=>S.toFixed(1)).join(","),"] keyFramesDecoded ").concat(A),y=d<=2.5?"debug":"info";this.log[y](h),this._keyFrameCountLogged=!0}}},gz=class extends CL{constructor(A,e){super(A,e,2),Y(this,"mediaType",2),Y(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},C_=new Map;function Jg(A,e){let o=po(fi({},e),{timestamp:Of()});C_.has(A)?C_.get(A).push(o):C_.set(A,[o])}function cz(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yXf(k)?nM(k):Vn(k)?k:Cg(k))},fnName:l,value:o},link:{className:d,fnName:l}})})}else if(!Ke(e.type)&&Cg(o)!==e.type)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_TYPE,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})});if(e.allowEmpty===!1){let S=kn(o)&&(o===0||Number.isNaN(o)),k=Vn(o)&&o.trim()==="";if(S||k)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_EMPTY,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})})}if(e.notLessThanZero&&kn(o)&&o<0)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.CANNOT_LESS_THAN_ZERO,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})});if(!Ke(e.min)&&kn(o)&&oe.max)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_MAX,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})});if(Vn(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})})}else if(Ra(e.instanceOf)&&!(o instanceof e.instanceOf))throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})});if(e.values&&!e.values.includes(o))throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PARAMETER_RANGE,data:{key:a,rule:e,fnName:l,value:o},link:{className:d,fnName:l}})});let{properties:h}=e;IE(h)&&XE(o)&&Object.keys(h).forEach(S=>{C1.call(this,{rule:h[S],value:o&&o[S],key:"".concat(a,".").concat(S),fnName:l,className:d})});let{arrayItem:y}=e;IE(y)&&wa(o)&&o.forEach((S,k)=>{C1.call(this,{rule:y,value:S,key:"".concat(a,"[").concat(k,"]"),fnName:l,className:d})}),Ra(e.validate)&&e.validate.call(this,o,a,l,d,this)}F.on(nA.JOIN_SUCCESS,A=>{let{room:e}=A;Jg(e.userId,{eventId:32788})}),F.on(nA.LEAVE_START,A=>{let{room:e}=A;Jg(e.userId,{eventId:32789})}),F.on(nA.LOCAL_TRACK_PUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32769;e.mediaType===4?o=32768:e.mediaType===2&&(o=32805),Jg(e.room.userId,{eventId:o})}}),F.on(nA.LOCAL_TRACK_UNPUBLISHED,A=>{let{track:e}=A;if(e.room){let o=32771;e.mediaType===4?o=32770:e.mediaType===2&&(o=32806),Jg(e.room.userId,{eventId:o})}}),F.on(nA.TRACK_MUTED,A=>{let{track:e}=A;e.room&&(e.kind===YA.AUDIO?Jg(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):Jg(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),F.on(nA.TRACK_UNMUTED,A=>{let{track:e}=A;e.room&&(e.kind===YA.AUDIO?Jg(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):Jg(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),F.on(nA.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Jg(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&Jg(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&Jg(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),F.on(nA.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Jg(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&Jg(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&Jg(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),F.on(nA.SWITCH_DEVICE_SUCCESS,A=>{let{track:e}=A;e.room&&Jg(e.room.userId,{eventId:e.kind===YA.VIDEO?32780:32781})}),F.on(nA.LOCAL_TRACK_REPLACED,A=>{let{track:e}=A;e.room&&Jg(e.room.userId,{eventId:e.kind===YA.VIDEO?32782:32783})}),F.on(nA.SIGNAL_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:a,state:l}=A;switch(l){case"CONNECTED":e=a==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":e=a==="RECONNECTING"?32796:32790;break;case"RECONNECTING":e=32794}e&&Jg(o.userId,{eventId:e})}),F.on(nA.PEER_CONNECTION_STATE_CHANGED,A=>{let e,{room:o,prevState:a,state:l,remoteUserId:d}=A,h=!!d;switch(l){case"CONNECTED":e=a==="RECONNECTING"?h?32801:32798:h?32793:32792;break;case"DISCONNECTED":a==="RECONNECTING"&&(e=h?32802:32799);break;case"RECONNECTING":e=h?32800:32797}e&&Jg(o.userId,{eventId:e,remoteUserId:d})}),F.on(nA.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:e,userId:o,remoteUserId:a,codec:l,isHWCodec:d,prevImplementation:h,streamType:y}=A,S=d?1:0;h||(S=d?3:2);let k={H264:0,H265:1,VP8:2}[l.toUpperCase()],V={eventId:4004,param1:S,param2:k,streamType:y||2};a&&(V.remoteUserId=a,V.eventId=4005),Jg(o,V),si.addEnum({key:a?514701:513701,value:S}),si.addEnum({key:a?514700:513700,value:k})}),F.on(nA.LOCAL_TRACK_RECAPTURE,A=>{let{track:e,error:o}=A;if(e.userId){let a={eventId:2003,param1:0};e.kind===YA.AUDIO?(a.streamType=1,o&&(a.param1=2)):(a.streamType=e.streamType==="auxiliary"?7:2,o&&(a.param1=8)),Jg(e.userId,a)}});var LiA=gc(jl(),1),UiA=class extends LiA.EventEmitter{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"userId";super(),this.mySelfId=A,this._log=e,this.key=o,Y(this,"userMap",new Map),Y(this,"remotePublishedUserMap",new Map),Y(this,"asrRobotUserMap",new Map)}get hasRobotUser(){return!![...this.remotePublishedUserMap.values()].find(A=>A.isRobot)}getPublishedUser(A){return this.remotePublishedUserMap.get(A)}addUser(A){let e=A[this.key],{userId:o,tinyId:a,role:l,fromType:d}=A;if(d===B0)return void this.addAsrRobotUser(A);if(this.userMap.has(e))return;let h={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.userMap.set(e,h),this.emit("1",h)}addAsrRobotUser(A){let e=A[this.key],{userId:o,tinyId:a,role:l}=A;if(this.asrRobotUserMap.has(e))return;let d={userId:o,tinyId:a,role:l===20?"anchor":"audience"};this.asrRobotUserMap.set(e,d),this.emit("8",d)}deleteUser(A,e){let o=this.userMap.get(A);if(!o)return;if(this.asrRobotUserMap.has(A))return void this.deleteAsrRobotUser(A);let a="peer leave [".concat(A,"]");Ke(e)||(a+=":".concat(i2[e])),this._log.info(a);let l=this.remotePublishedUserMap.get(A);if(l){let d=l.muteState;l.flag=0,this.emit("5",l.userId),this.deleteRemotePublishedUser(A),this.emit("6",{prevMuteState:d,muteState:l.muteState,flag:0})}this.userMap.delete(A),this.emit("2",{userId:o.userId,reason:e})}deleteAsrRobotUser(A){if(!this.asrRobotUserMap.has(A))return;let e=this.asrRobotUserMap.get(A);e&&(this.asrRobotUserMap.delete(A),this.emit("9",e))}setUserList(A){this.userMap.forEach(e=>{A.findIndex(o=>o[this.key]===e[this.key])<0&&this.deleteUser(e[this.key],0)}),A.forEach(e=>{!this.userMap.has(e[this.key])&&e[this.key]!==this.mySelfId&&this.addUser(e)})}addRemotePublishedUser(A){this.remotePublishedUserMap.has(A[this.key])||this.remotePublishedUserMap.set(A[this.key],A)}deleteRemotePublishedUser(A){this.remotePublishedUserMap.has(A)&&this.remotePublishedUserMap.delete(A)}setRemotePublishedUserList(A){this.remotePublishedUserMap.forEach(e=>{let o=e[this.key];if(A.findIndex(a=>a[this.key]===e[this.key])<0){this._log.info("remote [".concat(o,"] unpublish"));let a=e.muteState;e.flag=0,this.emit("5",e.userId),this.deleteRemotePublishedUser(o),this.emit("6",{prevMuteState:a,muteState:e.muteState,flag:0})}}),A.forEach(e=>{var o;let a=e[this.key];if(a===this.mySelfId)return void this.emit("7",e);let{flag:l,userId:d,tinyId:h,fromType:y}=e,S=Np(l,d),k=(o=this.remotePublishedUserMap.get(a))==null?void 0:o.muteState;if(k){let V=this.remotePublishedUserMap.get(a);V&&V.flag!==l&&(V.flag=l,this._log.info("remote publish updated: ".concat(JSON.stringify(V.muteState))),this.emit("6",{prevMuteState:k,muteState:S,flag:l}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(S))),this.addUser({userId:d,tinyId:h,role:20,fromType:y}),this.emit("3",e),this.emit("6",{prevMuteState:Np(0,d),muteState:S,flag:l})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},FiA=gc(jl(),1),OiA=class extends FiA.default{constructor(){super(...arguments),Y(this,"_connectionTimeoutCount",0),Y(this,"_isFirewallRestrictionEventEmitted",!1)}increaseTimeoutCount(){this._connectionTimeoutCount+=1,this.checkAndEmitFirewallRestriction()}resetTimeoutCount(){this._connectionTimeoutCount=0}checkAndEmitFirewallRestriction(){this._connectionTimeoutCount>=3&&!this._isFirewallRestrictionEventEmitted&&(this._isFirewallRestrictionEventEmitted=!0,this.emit("firewall-restriction"))}destroy(){this._connectionTimeoutCount=0,this._isFirewallRestrictionEventEmitted=!1,this.removeAllListeners()}};function lz(A){let{timesInSecond:e,maxSizeInSecond:o,getSize:a}=A;return jr((l,d)=>{let h=new WeakMap;return F.on(nA.ROOM_DESTROY,y=>{let{room:S}=y;return h.delete(S)}),function(){let y=h.get(this);for(var S=arguments.length,k=new Array(S),V=0;V1e3&&(y.timestamp=Date.now(),y.callCountInSecond=0,y.totalSizeInSecond=0),a&&(y.totalSizeInSecond+=a(...k)),y.timestamp!==0&&Date.now()-y.timestamp<1e3&&(y.callCountInSecond>=e||y.totalSizeInSecond>o))throw new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.CALL_FREQUENCY_LIMIT,data:{isTimes:y.callCountInSecond>=e,isSize:y.totalSizeInSecond>o,name:d,timesInSecond:e,maxSizeInSecond:o}})});y.callCountInSecond++,l.call(this,...k)}})}var vt,Iz=!0,hL={SCENE_LIVE:"live",SCENE_RTC:"rtc",ROLE_ANCHOR:"anchor",ROLE_AUDIENCE:"audience",STREAM_TYPE_MAIN:"main",STREAM_TYPE_SUB:"sub",AUDIO_PROFILE_STANDARD:"standard",AUDIO_PROFILE_STANDARD_STEREO:"standard-stereo",AUDIO_PROFILE_HIGH:"high",AUDIO_PROFILE_HIGH_STEREO:"high-stereo",QOS_PREFERENCE_SMOOTH:"smooth",QOS_PREFERENCE_CLEAR:"clear",SPEAKER:"Speakerphone",HEADSET:"Headset earpiece"},wo={INVALID_PARAMETER:5e3,INVALID_OPERATION:5100,ENV_NOT_SUPPORTED:5200,DEVICE_ERROR:5300,SERVER_ERROR:5400,OPERATION_FAILED:5500,OPERATION_ABORT:5998,UNKNOWN_ERROR:5999},h1=((vt=h1||{})[vt.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",vt[vt.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",vt[vt.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",vt[vt.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",vt[vt.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",vt[vt.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",vt[vt.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",vt[vt.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",vt[vt.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",vt[vt.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",vt[vt.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",vt[vt.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",vt[vt.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",vt[vt.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",vt[vt.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",vt[vt.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",vt[vt.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",vt[vt.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",vt[vt.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",vt[vt.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",vt[vt.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",vt[vt.INVALID_OPERATION=5100]="INVALID_OPERATION",vt[vt.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",vt[vt.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",vt[vt.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",vt[vt.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",vt[vt.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",vt[vt.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",vt[vt.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",vt[vt.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",vt[vt.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",vt[vt.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",vt[vt.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",vt[vt.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",vt[vt.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",vt[vt.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",vt[vt.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",vt[vt.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",vt[vt.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",vt[vt.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",vt[vt.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",vt[vt.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",vt[vt.DEVICE_ERROR=5300]="DEVICE_ERROR",vt[vt.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",vt[vt.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",vt[vt.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",vt[vt.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",vt[vt.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",vt[vt.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",vt[vt.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",vt[vt.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",vt[vt.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",vt[vt.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",vt[vt.SERVER_ERROR=5400]="SERVER_ERROR",vt[vt.NEED_TO_BUY=5401]="NEED_TO_BUY",vt[vt.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",vt[vt.OPERATION_FAILED=5500]="OPERATION_FAILED",vt[vt.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",vt[vt.REJOIN_FAILED=5502]="REJOIN_FAILED",vt[vt.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",vt[vt.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",vt[vt.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",vt[vt.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",vt[vt.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",vt[vt.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",vt[vt.OPERATION_ABORT=5998]="OPERATION_ABORT",vt[vt.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",vt),uz=po(fi({},cc),{INVALID_PARAMETER(A){let{fnName:e}=A;return"the parameters of the '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_PARAMETER_REQUIRED(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' is a required param when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_TYPE(A){let{key:e,rule:o,fnName:a,value:l}=A,d="".concat(e||o.name),h="";return h=Array.isArray(o.type)?o.type.join("|"):o.type,"'".concat(d,"' must be type of ").concat(h," when calling ").concat(a,"(), received type: ").concat(Cg(l),".")},INVALID_PARAMETER_EMPTY(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' cannot be '").concat(l,"' when calling ").concat(a,"().")},INVALID_PARAMETER_INSTANCE(A){let{key:e,rule:o,fnName:a,value:l}=A,d="".concat(e||o.name),h="".concat(o.instanceOf.name||o.instanceOf);return"'".concat(d,"' must be instanceof ").concat(h," when calling ").concat(a,"(), received type: ").concat(Cg(l),".")},INVALID_PARAMETER_RANGE(A){let{key:e,rule:o,fnName:a,value:l}=A;return"'".concat(e||o.name,"' must be one of ").concat(o.values.join("|")," when calling ").concat(a,"(), received: ").concat(l,".")},INVALID_PARAMETER_LESS_THAN_ZERO(A){let{key:e,rule:o,fnName:a}=A;return"'".concat(e||o.name,"' cannot be less than 0 when calling ").concat(a,"().")},INVALID_PARAMETER_MIN(A){let{key:e,rule:o,value:a}=A;return"the min value of ".concat(e||o.name," is ").concat(o.min,", received: ").concat(a,".")},INVALID_PARAMETER_MAX(A){let{key:e,rule:o,value:a}=A;return"the max value of ".concat(e||o.name," is ").concat(o.max,", received: ").concat(a,".")},INVALID_ELEMENT_ID(A){let{key:e,fnName:o}=A;return"'".concat(e,"' is not found in the document object when calling ").concat(o,"().")},INVALID_ELEMENT_ID_TYPE(A){let{key:e,fnName:o,type:a}=A;return"the element corresponding to '".concat(e,"' must be instanceof HTMLElement when calling ").concat(o,"(), received: ").concat(a,".")},INVALID_STREAM_ID(A){let{key:e}=A;return"'".concat(e,"' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.")},INVALID_ROOM_ID_STRING(A){let{key:e}=A;return"'".concat(e,"' must be a valid string.")},INVALID_ROOM_ID_INTEGER(A){let{key:e}=A;return"'".concat(e,"' must be an integer between [1, 4294967294].")},INVALID_ROOM_ID_INTEGER_STRING(A){let{key:e}=A;return"'".concat(e,"' must be an integer but go a string, use 'parseInt' to convert it or use 'strRoomId' instead.")},INVALID_ROOM_ID_REQUIRED:()=>"at least one of 'roomId'(between [1, 4294967294]) and 'strRoomId'(not empty) is required.",INVALID_ROOM_ID_TYPE_MISMATCH(A){let{key:e}=A;return"The type of target roomId must match the current roomId. Current room is using '".concat(e,"', but received '").concat(e==="strRoomId"?"roomId":"strRoomId","'.")},INVALID_ROOM_ID_DUPLICATE(A){let{key:e}=A;return"the target '".concat(e,"' must not be the same as the current '").concat(e,"'.")},INVALID_STREAM_TYPE:A=>{let{fnName:e}=A;return"'streamType' is required when 'userId' is not '*', calling ".concat(e,"()")},INVALID_IMAGE_URL:"The 'src' param must be filled in when the background type is image.",INVALID_OPERATION(A){let{fnName:e}=A;return"the API '".concat(e,"' you called does not meet the requirements, please check the API documentation.")},INVALID_OPERATION_NOT_JOINED(A){let{fnName:e}=A;return"cannot ".concat(e," because you are not enter room yet.")},INVALID_OPERATION_REMOTE_USER_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing stream.")},INVALID_OPERATION_STREAM_TYPE_NOT_EXIST(A){let{fnName:e,value:o}=A;return"cannot ".concat(e," because remote user(userId: ").concat(o.userId,") does not publishing ").concat(o.streamType," video.")},INVALID_OPERATION_REPEAT_CALL(A){let{fnName:e}=A;return"you are already ".concat(e,"(), cannot repeated call '").concat(e,"'.")},INVALID_OPERATION_NEED_VIDEO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the camera is not turned on.")},INVALID_OPERATION_NEED_AUDIO(A){let{fnName:e}=A;return"cannot call '".concat(e,"' because the microphone or screen share is not turned on.")},INVALID_BUFFER_EMPTY:A=>{let{key:e}=A;return"the buffer size of paramerter '".concat(e,"' cannot be empty")},INVALID_BUFFER_OVERSIZE:()=>"buffer size is over 1000 Bytes",INVALID_ROLE_AUDIENCE:()=>"role: 'audience' cannot call this api.",INVALID_NOT_ENABLE_SEI:()=>"you need to enable SEI in TRTC.create({ enableSEI: true })",INVALID_NEED_CALL_PUBLISHED:A=>{let{fnName:e}=A;return"you need to call ".concat(e,"() after publish stream.")},ENV_NOT_SUPPORTED(A){let{fnName:e}=A;return"the current browser does not support the capability of the function '".concat(e,"' you are calling, please check the API documentation.")},NOT_SUPPORTED_WEBRTC:"the current browser does not support WebRTC capability, please check the SDK documentation.",NOT_SUPPORTED_H264_ENCODE:"this browser does not support H264 encode.",NOT_SUPPORTED_H264_DECODE:"this browser does not support H264 decode.",NOT_SUPPORTED_SCREEN_SHARE:"this browser does not support screen share, please check the browser version.",NOT_SUPPORTED_SMALL_VIDEO:"this browser does not support small video, please check the browser version.",NOT_SUPPORTED_SEI:"this browser does not support SEI, please check the browser version.",NOT_SUPPORTED_WEBGL:"this browser does not support WebGL, please check the browser version.",NOT_SUPPORTED_CHROME_VERSION(A){let{fnName:e}=A;return"cannot call ".concat(e," because the browser version is too low, please upgrade to the latest version")},DEVICE_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got device exception").concat(o?", error: ".concat(o.toString(),"."):".")},DEVICE_NOT_FOUND_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"NotFoundError, no ".concat(o," detected, please check your device and the configuration on '").concat(e,"'").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_ALLOWED_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"NotAllowedError, you have disabled ".concat(o," access, please allow the current application to use the ").concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_NOT_READABLE_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"NotReadableError, the ".concat(o," maybe in use by another APP, please check if the device is pre-occupied by another APP.")},DEVICE_OVERCONSTRAINED_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"OverconstrainedError, the device ID is incorrect, please check whether the device ID passed in is correct".concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_INVALID_STATE_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"InvalidStateError, after the user clicks and interacts with the page, turn on the ".concat(o).concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_SECURITY_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"SecurityError, check whether the system security policy restricts the use of the ".concat(o,", and it is recommended to turn on the ").concat(o," after the user interacts with the page").concat(a?", error: ".concat(a.toString(),"."):".")},DEVICE_ABORT_ERROR(A){let{fnName:e,deviceType:o=ZM(e),error:a}=A;return"AbortError, an unknown exception in the system makes the device unusable, recommended to change the device or browser and re-check whether the device is normal".concat(a?" error: ".concat(a.toString(),"."):".")},CAMERA_RECOVER_FAILED(A){let{error:e}=A;return"camera recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},MICROPHONE_RECOVER_FAILED(A){let{error:e}=A;return"microphone recover capture failed ".concat(e?.name||"",": ").concat(e?.originMessage||e?.message)},OPERATION_FAILED(A){let{fnName:e,error:o}=A;return"'".concat(e,"' failed, reason: ").concat(o?.toString())},FIREWALL_RESTRICTION:()=>"media connection failure due to firewall restrictions, please try to change your network.",EVENT_HANDLER_ERROR(A){let{eventName:e}=A;return"an error was caught on trtc.on('".concat(e,"', handler), please check your code on 'handler'.")},VIDEO_CONTEXT_ERROR(A){let{reason:e,error:o}=A;return"video context error ".concat(e," ").concat(o?.name||""," ").concat(o?.message||"")},SERVER_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' got server error: ").concat(o?.toString(),", please check the SDK documentation.")},NEED_TO_BUY(A){let{value:e,url:o}=A;return"You need to buy packages for ".concat(e,". Refer to: ").concat(o)},ACCOUNT_NO_MONEY:A=>{let{fnParams:e}=A;return"your TRTC account run out of credit, please recharge.".concat(e.sdkAppId?" SDKAppId: ".concat(e.sdkAppId):"")},OPERATION_ABORT(A){let{fnName:e}=A;return"'".concat(e,"' abort")},UNKNOWN_ERROR(A){let{fnName:e,error:o}=A;return"'".concat(e,"' throw unknown exception").concat(o?", error: ".concat(o.toString(),"."):".")}});function ZM(A){if(!A)return"camera";let e=A.toLowerCase();return e.includes("screen")?"screen share":e.includes("audio")?"microphone":"camera"}var PiA=class CY extends Error{constructor(e){let{code:o,extraCode:a,message:l="",messageParams:d,fnName:h="",originError:y,data:S}=e;var k;let V;V=l||function(J){let cA,{code:CA,params:MA,enableDocLink:ie=!1}=J,pe="",qe=h1[CA];try{cA=uz[qe]}catch{cA=uz.UNKNOWN_ERROR}return Ra(cA)?pe=cA(MA):Vn(cA)&&(pe=cA),MA.fnName&&!pe.includes(MA.fnName)&&(pe[pe.length-1]!=="."&&(pe+="."),pe+=" thrown from ".concat(MA.fnName,"()")),ie&&(pe+=" doc:"),pe}({code:o===wo.SERVER_ERROR?o:a||o,params:fi({fnName:h,error:y},d)}),super(V),Y(this,"name","RtcError"),Y(this,"code"),Y(this,"extraCode"),Y(this,"functionName"),Y(this,"message"),Y(this,"data"),Y(this,"handler"),Y(this,"originError"),this.name=h1[o],this.code=o,this.extraCode=a,this.functionName=h,this.originError=y,this.message=V,this.data=S,this.extraCode===5302&&(k=this.originError)!=null&&k.message.includes("system")&&(this.handler=()=>{let J=document.createElement("a");sy?J.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):nQ&&(J.href="x-apple.systempreferences:com.apple.preference.security?Privacy_".concat({startLocalVideo:"Camera",startLocalAudio:"Microphone",startScreenShare:"ScreenCapture"}[this.functionName])),J.href.length>0&&J.click()})}static convertFrom(e,o,a){let l=e;if(e instanceof gi){let{stack:d}=e,h={code:wo.UNKNOWN_ERROR,fnName:o,originError:e};switch(e.getCode()){case Ct.INVALID_PARAMETER:h.code=wo.INVALID_PARAMETER,h.message=e.message;break;case Ct.INVALID_OPERATION:h.code=wo.INVALID_OPERATION,h.message=e.message;break;case Ct.NOT_SUPPORTED:case Ct.NOT_SUPPORTED_H264:h.code=wo.ENV_NOT_SUPPORTED,e.getCode()===Ct.NOT_SUPPORTED_H264&&(h.extraCode=e.message.includes(cc.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case Ct.JOIN_ROOM_FAILED:h.messageParams={fnParams:a};case Ct.SERVER_TIMEOUT:case Ct.SWITCH_ROLE_FAILED:case Ct.SWITCH_ROOM_FAILED:h.code=wo.SERVER_ERROR,h.extraCode=e.getExtraCode();break;case Ct.API_CALL_ABORTED:h.code=wo.OPERATION_ABORT;break;case Ct.DEVICE_NOT_FOUND:case Ct.DEVICE_AUTO_RECOVER_FAILED:case Ct.INITIALIZE_FAILED:h.code=5300,e.name&&(h.extraCode=function(y){let S;switch(y){case"NotFoundError":S=5301;break;case"NotAllowedError":S=5302;break;case"NotReadableError":S=5303;break;case"OverconstrainedError":S=5304;break;case"InvalidStateError":S=5305;break;case"SecurityError":S=5306;break;case"AbortError":S=5307;break;default:S=5300}return S}(e.name));break;case Ct.VIDEO_ENCODE_FAILED:h.extraCode=5505;case Ct.AUDIO_ENCODE_FAILED:h.extraCode=5506,h.code=wo.OPERATION_FAILED;break;case Ct.UNKNOWN:break;default:h.code=wo.OPERATION_FAILED}l=new CY(h),d&&(l.stack+=d.substr(d.indexOf(` +`)))}else{if(e instanceof CY)return e;l=new CY({code:wo.UNKNOWN_ERROR,fnName:o,originError:e})}return l}},_o=PiA;function eC(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function B1(A){return A===hL.QOS_PREFERENCE_CLEAR?"detail":A===hL.QOS_PREFERENCE_SMOOTH?"motion":""}function Q1(A,e){let o=e?qx:jS;return y2(A)?fi(fi({},o),A):FC[A]?FC[A]:o}var Ez={type:"object",properties:{cameraId:{type:"string"},useFrontCamera:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:["string","boolean"],values:[!0,!1,"view","publish","both"]},small:{type:["string","object","boolean"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack}}},dz={type:"object",properties:{systemAudio:{type:"boolean"},fillMode:{type:"string",values:["contain","cover","fill"]},profile:{type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},videoTrack:{instanceOf:MediaStreamTrack},audioTrack:{instanceOf:MediaStreamTrack}}},h_={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,e,o){if(Vn(A)&&!document.getElementById(A))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:e}})}},Cz={name:"userId",required:!0,type:"string"},hz={type:"object",properties:{microphoneId:{type:"string"},audioTrack:{instanceOf:MediaStreamTrack},captureVolume:{type:"number",min:0},earMonitorVolume:{type:"number",min:0,max:100},profile:{type:["string","object"],properties:{bitrate:{type:"number"},channelCount:{type:"number"}}},echoCancellation:{values:[!0,!1,"remote-only","all"]},autoGainControl:{type:"boolean"},noiseSuppression:{type:"boolean"}}};function B_(A,e){if(!A)throw new _o({code:wo.INVALID_OPERATION,extraCode:5101,fnName:e})}function Bz(A,e,o){if(!A)throw new _o({code:wo.INVALID_OPERATION,extraCode:5102,fnName:e,messageParams:{value:o}})}function Qz(A,e,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:o}})}function pz(A,e,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:o}})}function mz(A){var e;if((e=A?.option)==null||!e.small)return;if(!kM())return pA.warn("small stream is not supported"),void delete A.option.small;let o=Q1(A.option.profile),a=Q1(A.option.small,!0);return((l,d)=>l.width*l.height>=d.width*d.height&&l.frameRate>=d.frameRate&&l.bitrate>=d.bitrate)(o,a)?void 0:(pA.warn("small stream profile must be less than big stream profile. Big: ".concat(JSON.stringify(o),", Small: ").concat(JSON.stringify(a))),void delete A.option.small)}var xiA={create:[{name:"RoomConfig",instanceOf:Function},{name:"CreateConfig",type:"object",properties:{plugins:{type:"array",arrayItem:{instanceOf:Function}}}}],enterRoom:{name:"EnterRoomConfig",type:"object",required:!0,validate(A,e,o){if(this._room.isJoined)throw new _o({code:wo.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Vn(A.roomId))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:e}});Qz(A.roomId,o,e)}else{if(!A.strRoomId)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5015,fnName:o});pz(A.strRoomId,o,e)}},properties:{sdkAppId:{required:!0,type:"number",allowEmpty:!1},userId:{required:!0,type:"string",allowEmpty:!1},userSig:{required:!0,type:"string",allowEmpty:!1},scene:{type:"string",values:["live","rtc"]},role:{type:"string",values:["audience","anchor"]},roomId:{type:["string","number"]},strRoomId:{type:"string"},proxy:{type:["object","string"],properties:{websocketProxy:{type:"string"},turnServer:{type:["object","array"],properties:{url:{required:!0,type:"string"},username:{type:"string"},credential:{type:"string"},credentialType:{type:"string",values:["password"]}}},loggerProxy:{type:"string"},webtransportProxy:{type:"string"}}},enableAutoPlayDialog:{type:"boolean"},userDefineRecordId:{type:"string"},latencyLevel:{type:"number"},playoutDelay:{type:"object",properties:{min:{type:"number",min:0,max:1e3},max:{type:"number",min:0,max:1e4}}}}},startLocalVideo:{name:"LocalVideoConfig",type:"object",properties:{view:h_,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:Ez},validate(A){var e,o;if(((e=A?.option)==null||!e.videoTrack)&&Cu())throw new _o({code:wo.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&mz(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:po(fi({},h_),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:Ez},validate(A){var e;(e=A?.option)!=null&&e.small&&mz(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:hz},validate(A){var e;if(((e=A?.option)==null||!e.audioTrack)&&Cu())throw new _o({code:wo.ENV_NOT_SUPPORTED,extraCode:5201})}},updateLocalAudio:{name:"updateLocalAudioConfig",type:"object",required:!0,properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:hz}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:h_,publish:{type:"boolean"},option:dz},validate(A,e,o,a,l){var d;if((d=A?.option)==null||!d.videoTrack){if(Cu())throw new _o({code:wo.ENV_NOT_SUPPORTED,extraCode:5201});if(!Wp())throw new _o({code:wo.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:h_,publish:{type:"boolean"},option:dz}},muteRemoteAudio:[Cz,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[Cz,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:h_,userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,e,o){B_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Bz(!!a,o,A),a&&(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary))throw new _o({code:wo.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:po(fi({},h_),{required:!1}),userId:{type:"string",required:!0},streamType:{values:["main","sub"],required:!0},option:{type:"object",properties:{fillMode:{type:"string",values:["contain","cover","fill"]},mirror:{type:"boolean"}}}},validate(A,e,o){B_(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(Bz(!!a,o,A),a){if(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary)throw new _o({code:wo.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}});if(A.option){let l=A.streamType==="main"?a.remoteVideoTrack:a.remoteAuxiliaryTrack;if((A.option.pictureInPicture||A.option.fullScreen||A.option.fullScreen)&&(!l.isSubscribed||!l.player.isPlaying))throw new _o({code:wo.INVALID_OPERATION,message:"cannot set pictureInPicture or fullScreen when remote video is not playing"})}}}},stopRemoteVideo:{name:"stopRemoteVideoConfig",type:"object",required:!0,properties:{userId:{type:"string",required:!0},streamType:{values:["main","sub"]}},validate(A,e,o){if(A.userId!=="*"&&Ke(A.streamType))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,e,o){B_(this._room.isJoining||this._room.isJoined,o)}},enableAudioVolumeEvaluation:[{name:"interval",type:"number"},{name:"enableInBackground",type:"boolean"}],sendSEIMessage:[{name:"buffer",required:!0,instanceOf:ArrayBuffer,validate(A,e,o,a){if(!Kk)throw new _o({code:wo.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new _o({code:wo.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5017,messageParams:{key:e},fnName:o});B_(this._room.isJoined,o)}},{name:"options",type:"object",properties:{seiPayloadType:{type:"number",values:[5,243]},toSubStream:{type:"boolean",validate(A,e,o){if(!A&&!this._room.isMainStreamPublished||A&&!this._room.isAuxStreamPublished)throw new _o({code:wo.INVALID_OPERATION,extraCode:5109,messageParams:{key:e},fnName:o})}}}}],sendCustomMessage:{name:"message",required:!0,type:"object",properties:{cmdId:{type:"number",required:!0,min:1,max:10},data:{instanceOf:ArrayBuffer,required:!0,validate(A,e,o,a){if(A.byteLength>1e3)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:e}})}}},validate(A,e,o){if(B_(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new _o({code:wo.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:e}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,e,o){if(B_(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new _o({code:wo.INVALID_PARAMETER,extraCode:5020,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId&&this._room.useStringRoomId||!A.roomId&&A.strRoomId&&!this._room.useStringRoomId)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)Qz(A.roomId,o,e);else{if(!A.strRoomId)throw new _o({code:wo.INVALID_PARAMETER,extraCode:5015,fnName:o});pz(A.strRoomId,o,e)}},properties:{roomId:{type:"number"},strRoomId:{type:"string"},privateMapKey:{type:"string"},userSig:{type:"string",required:!0},autoSubscribeCount:{type:"number",min:0,max:50}}}},Zl={TRTC:xiA},tC=class extends Error{};function YiA(A,e){let o=$f(A);for(let a=0;a!0),Y(this,"mergeUpdate",YiA);let a=G_.instances.get(e);a?a.set(o,this):G_.instances.set(e,new Map([[o,this]]))}static get(e,o){if(!o)return;let a=G_.instances.get(e);return a&&a.get(o)||new G_(e,o)}static gets(e,o){let a=G_.instances.get(e),l=[];return a&&a.forEach((d,h)=>{o.test(h)&&l.push(d)}),l}action(e,o,a){let l=y=>{var S;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(S=this.currentOp)==null||S.action(),y},d=y=>{var S,k;throw this.ops.shift(),e===0&&((S=this.currentOp)==null?void 0:S.type)===2&&this.ops.shift().reject(new tC("start failed")),(k=this.currentOp)==null||k.action(),y},h={type:e,action:()=>o(...h.args).then(l,d),args:a,resolve:ViA,reject:JiA};try{switch(this.state){case 1:if(e===0)throw new tC("already started");break;case 4:if(e===2)throw new tC("not started");break;default:return this.cacheOp(h)}}catch(y){return Promise.reject(y)}return this.ops.push(h),h.promise=o(...h.args).then(l,d)}cacheOp(e){if(this.ops.length===1)switch(this.state){case 0:case 2:if(e.type===0)throw new tC("already start");break;case 3:switch(e.type){case 2:throw new tC("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new tC("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let a=new tC("keep stop");if(this.ops.slice(1).forEach(l=>l.reject(a)),this.ops=this.ops.slice(0,1),this.state===3)return this.currentOp.promise}break;case 2:switch(this.lastOpType){case 2:return this.lastOp.args=this.mergeUpdate(this.lastOp.args,e.args),this.lastOp.promise;case 3:throw new tC("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new tC("start not allowed after update");case 0:throw new tC("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new tC("keep start")),new tC("already start")}}e.promise=new Promise((a,l)=>{e._resolve?e._resolve.then(a):e.resolve=a,e._reject?e._reject.catch(l):e.reject=l});let{action:o}=e;return e.action=()=>o().then(e.resolve,e.reject),this.ops.push(e),e.promise}get lastOp(){return this.ops[this.ops.length-1]}get lastOpType(){return this.lastOp.type}get currentOp(){return this.ops[0]}get state(){return this.currentOp?this.currentOp.type:this.started?1:4}};Y(fz,"instances",new WeakMap);var BL=fz,p1=new WeakMap,m1=(A,e)=>{if(e instanceof tC){let{stack:o}=e;e=new _o({code:wo.OPERATION_ABORT,message:"".concat(A," abort: ").concat(e.message),fnName:A}),o&&(e.stack+=o.substr(o.indexOf(` +`)))}throw e};function XM(A,e){return jr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;hfunction(){for(var h=arguments.length,y=new Array(h),S=0;S{var MA,ie;let pe=(MA=p1.get(this))==null?void 0:MA.get(J(...y));if(pe){let{timeoutId:we,resolve:Di}=pe;clearTimeout(we),Di()}let qe=setTimeout(()=>{if(k.state===3||k.state===4)return cA();k.action(2,l.bind(this),y).catch(m1.bind(null,d)).then(cA,CA)},V);p1.has(this)?(ie=p1.get(this))==null||ie.set(J(...y),{timeoutId:qe,resolve:cA}):p1.set(this,new Map([[J(...y),{timeoutId:qe,resolve:cA}]]))})}return k.action(2,l.bind(this),y).catch(m1.bind(null,d))})}function $M(A){return jr((e,o)=>function(){for(var a=arguments.length,l=new Array(a),d=0;dS.action(3,()=>Promise.resolve(),l))).then(()=>e.call(this,...l));let y=BL.get(this,h);return y?y.action(3,e.bind(this),l).catch(m1.bind(null,o)):e.apply(this,l)})}function Av(){return function(A,e,o){return A.prototype[e]=function(){let a=this._log||console,l='"'.concat(e,'" is a static method. Use TRTC.').concat(e,"() instead. See: ").concat(Wh,"/en/TRTC.html#.").concat(e);a.warn(l)},o}}var Ki={ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",KICKED_OUT:"kicked-out",REMOTE_USER_ENTER:"remote-user-enter",REMOTE_USER_EXIT:"remote-user-exit",REMOTE_AUDIO_AVAILABLE:"remote-audio-available",REMOTE_AUDIO_UNAVAILABLE:"remote-audio-unavailable",REMOTE_VIDEO_AVAILABLE:"remote-video-available",REMOTE_VIDEO_UNAVAILABLE:"remote-video-unavailable",AUDIO_VOLUME:"audio-volume",AUDIO_FRAME:"audio-frame",NETWORK_QUALITY:"network-quality",CONNECTION_STATE_CHANGED:"connection-state-changed",AUDIO_PLAY_STATE_CHANGED:"audio-play-state-changed",VIDEO_PLAY_STATE_CHANGED:"video-play-state-changed",SCREEN_SHARE_STOPPED:"screen-share-stopped",DEVICE_CHANGED:"device-changed",PUBLISH_STATE_CHANGED:"publish-state-changed",TRACK:"track",STATISTICS:"statistics",SEI_MESSAGE:"sei-message",CUSTOM_MESSAGE:"custom-message",VIDEO_DECODE_DOWNGRADE_STATE_CHANGED:"video-decode-downgrade-state-changed",LAYER_DATA:"layerData",FIRST_VIDEO_FRAME:"first-video-frame",PERMISSION_STATE_CHANGE:"permission-state-change",VIDEO_SIZE_CHANGED:"video-size-changed",REALTIME_TRANSCRIBER_MESSAGE:"realtime-transcriber-message",REALTIME_TRANSCRIBER_STATE_CHANGED:"realtime-transcriber-state-changed",PICTURE_IN_PICTURE_STATE_CHANGED:"picture-in-picture-state-changed",FULL_SCREEN_STATE_CHANGED:"full-screen-state-changed"},HiA=new Set([Ki.AUDIO_VOLUME,Ki.AUDIO_FRAME,Ki.NETWORK_QUALITY,Ki.STATISTICS,Ki.SEI_MESSAGE,Ki.CUSTOM_MESSAGE,Ki.LAYER_DATA]),yz={};jh(yz,{ScheduleRequestType:()=>Mz,getAbilityConfig:()=>qiA,getScheduleDomain:()=>dj,isNeedToSchedule:()=>QL,scheduleProxy:()=>om,sendScheduleRequest:()=>Sz,setIsNeedToSchedule:()=>pQ,setScheduleProxy:()=>Ej});var f1=null,y1=0,Dz=72e5,D1="trtc_schedule_cache",QL=!0;function pQ(A){Nr(A)&&A!==QL&&(QL=A,pA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(D1)}catch(e){pA.error("clearScheduleCache error",e)}}():y1=Date.now()+Dz)}function Sz(A){return WA(this,arguments,function(e){let{userId:o,sdkAppId:a,useStringRoomId:l,roomId:d,userSig:h,version:y,frameWorkType:S,role:k,latencyLevel:V}=e;return function*(){var J;if(!QL&&f1&&y1>Date.now())return{isCached:!0,result:f1};let cA={delta:0,count:[1,1],msg:[],detail:[]};try{let CA=new FormData;CA.append("userId",String(o)),CA.append("sdkAppId",String(a)),CA.append("isStrGroupId",String(l)),CA.append("groupId",String(d)),CA.append("sdkVersion",y),CA.append("userSig",String(h));let MA=((J=yield SM())==null?void 0:J.model)||Sk();MA&&CA.append("model",MA);let ie=Hp();ie&&CA.append("osString",ie);let pe=Vp();pe&&CA.append("gpu",pe),k&&CA.append("role",String(k)),V&&CA.append("latencyLevel",String(V)),S&&CA.append("frameWorkType",String(S));let qe=ko(),we=yield function(Le,Qt,Bi){return new Promise((Si,Jo)=>{let Ho=null;rM([vz(Qn=>Qt.count[0]=Qn+1,Qn=>{let{error:qo,retry:Ns,retriedCount:pg,retryFuncArgs:ya}=Qn;Qt.msg[0]=qo.message,Ho||(pg>=1&&(ya[0]=wy(Bi,"config",YA.MAIN,!0)),Ns())})(wy(Bi,"config",YA.MAIN),Le,{get timeout(){return 1e3*zf(2+Qt.count[0])}}),vz(Qn=>Qt.count[1]=Qn+1,Qn=>{let{error:qo,retry:Ns,retriedCount:pg,retryFuncArgs:ya}=Qn;Qt.msg[1]=qo.message,Ho||(pg>=2&&(ya[0]=wy(Bi,"config",YA.BACKUP,!0)),Ns())})(wy(Bi,"config",YA.BACKUP),Le,{get timeout(){return 1e3*zf(2+Qt.count[1])}})]).then(Qn=>{Ho=Qn,Si(Ho)}).catch(Jo)})}(CA,cA,a);we.config&&(we.config.loggerDomain&&qS(we.config.loggerDomain),Nr(we.config.scheduleCache)&&pQ(!we.config.scheduleCache)),cA.delta=ko()-qe;let Di=function(Le,Qt,Bi){let Si={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Jo=performance.getEntriesByType("resource"),Ho=wy(Le,"config",YA.MAIN),Qn=wy(Le,"config",YA.BACKUP);for(let qo of Jo)if(qo.startTime>=Bi&&(qo.name===Ho||qo.name===Qn)&&qo.transferSize>0){let Ns=qo.name===Ho?YA.MAIN:YA.BACKUP,pg=Math.round(qo.duration),ya=Math.round(qo.domainLookupStart-qo.startTime),Qu=qo.redirectStart>0?Math.round(qo.redirectEnd-qo.redirectStart):0,DL=qo.fetchStart>0?Math.round(qo.domainLookupStart-qo.fetchStart):0,D_=Math.round(qo.domainLookupEnd-qo.domainLookupStart),M8=Math.round(qo.requestStart-qo.secureConnectionStart),v8=Math.round(qo.secureConnectionStart-qo.connectStart),R8=Math.round(qo.responseStart-qo.requestStart),w8=Math.round(qo.responseEnd-qo.responseStart),QsA=[D_,M8,v8,R8,w8];sn.uploadEvent({log:"stat-schedule-net:".concat(pg,"(").concat(ya,"(").concat(Qu,"->").concat(DL,")->").concat(QsA.join("->"),") ").concat(Ns),userId:Qt}),Si=po(fi({},Si),{totalCost:pg,local:ya,dns:D_,tcp:v8,tls:M8,request:R8,response:w8});break}}catch(Jo){pA.error("getScheduleDetailCost error",Jo)}return Si}(Number(a),o,qe);return f1=we,function(Le){if(typeof window<"u"&&typeof localStorage<"u")try{let Qt=Date.now()+Dz;localStorage.setItem(D1,JSON.stringify({result:Le,expireIn:Qt})),y1=Qt}catch(Qt){pA.error("saveScheduleToLocalStorage error",Qt)}}(we),{isCached:!1,result:we,detailCost:Di}}catch(CA){let MA=wa(CA)?CA[0]:CA,ie=kn(MA.code)?MA.code:0,pe="schedule failed".concat(MA.message?": ".concat(MA.message):""),qe=new gi({code:Ct.SCHEDULE_FAILED,extraCode:ie,message:Xo({key:vo.JOIN_ROOM_FAILED,data:{error:pe,code:ie}})});throw pA.error(pe,ie),qe}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(eQ).map(A=>'')).join(`\r +`)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(D1);if(A){let{result:e,expireIn:o}=JSON.parse(A);o>Date.now()?(f1=e,y1=o,QL=!1):localStorage.removeItem(D1)}}catch(A){pA.error("loadScheduleFromLocalStorage error",A)}}(),F.on("28",()=>pQ(!0)),F.on("63",()=>pQ(!0)),F.on("84",()=>pQ(!0)),F.on("201",A=>{A.state==="RECONNECTING"&&pQ(!0)}),F.on("202",A=>{A.state==="RECONNECTING"&&pQ(!0)});var om={main:"",backup:""};function Ej(A){wa(A)?(om.main=A[0],om.backup=A[1]):(om.main=A,om.backup=A)}var Mz=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(Mz||{});function wy(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:YA.MAIN,a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(om[o]||dj(A,o,a),"/api/v1/").concat(e)}function qiA(A,e,o){let a=wy(A,e),l=wy(A,e,YA.BACKUP),d=new URLSearchParams(o).toString(),h=fetch("".concat(a,"?").concat(d)).then(S=>S.json()),y=fetch("".concat(l,"?").concat(d)).then(S=>S.json());return rM([h,y])}function dj(A){let e,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:YA.MAIN,a=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return e=Kd(A)?a?o===YA.MAIN?eQ.MAIN_OVERSEA_BACKUP:eQ.BACKUP_OVERSEA:o===YA.MAIN?eQ.MAIN_OVERSEA:eQ.BACKUP_OVERSEA:o===YA.MAIN?eQ.MAIN:eQ.BACKUP,e}function KiA(A,e,o){return new Promise((a,l)=>{oQ({url:A,body:e,timeout:o.timeout,priority:"high"}).then(d=>{d.data.code===0?a(d.data.data):l({code:d.data.code,message:d.data.msg})}).catch(l)})}var vz=(A,e)=>IM({retryFunction:KiA,settings:{retries:3,timeout:0},onError:e,onRetrying:A}),Cj=class{constructor(){Y(this,"_log"),this._log=pA.createLogger({id:"fd"})}download(A,e){return WA(this,null,function*(){let{type:o="blob"}=e||{};A=Ak(A);try{let a,l=ko();if(a=Ra(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!a||!a.data)throw new Error("data is empty");let d=ko()-l;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(d,"ms")),si.addSuccessEvent({key:522700,cost:ko()-l}),a.data}catch(a){throw this._log.error("failed to download: ".concat(A,", error: ").concat(a)),si.addFailedEvent({key:522700,error:a}),a}})}downloadWithFetch(A,e){return WA(this,null,function*(){this._log.info("download with fetch: ".concat(A,", return type: ").concat(e));try{let o,a=yield fetch(A);if(!a.ok){let l=new Error("network response was not ok: ".concat(a.status));throw l.status=a.status,l}return o=e==="arraybuffer"?yield a.arrayBuffer():yield a.blob(),{data:o}}catch(o){throw o}})}downloadWithXHR(A,e){return this._log.info("download with xhr: ".concat(A,", return type: ").concat(e)),new Promise((o,a)=>{let l=new XMLHttpRequest;l.open("GET",A,!0),l.responseType=e,l.onload=()=>{if(l.status===200||l.status===0&&l.response)o({data:l.response});else{let d=new Error("XHR failed, status: ".concat(l.status));d.status=l.status,a(d)}},l.onerror=a,l.send(null)})}loadWasm(A,e){return WA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(e)));let o=ko(),a=null,l=null;if(Ra(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(d=>d.startsWith("file://"))(A)&&Ra(fetch))try{let d=fetch(A);a=(yield WebAssembly.instantiateStreaming(d,e)).instance}catch(d){l=d}if(!a)try{let d=yield this.download(A,{type:"arraybuffer"});a=(yield WebAssembly.instantiate(d,e)).instance}catch(d){l=d}if(a){let d=ko()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(d,"ms")),si.addSuccessEvent({key:522701,cost:d}),a}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(l)),si.addFailedEvent({key:522701,error:l}),l})}loadScript(A){this._log.info("loadScript ".concat(A));let e=ko();return new Promise((o,a)=>{let l=document.createElement("script");l.type="text/javascript",l.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(ko()-e,"ms")),si.addSuccessEvent({key:522702,cost:ko()-e,split:1e3}),o(l)},l.onerror=d=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(d?.message||JSON.stringify(d))),si.addFailedEvent({key:522702}),a(d)},l.crossOrigin="anonymous",l.src=A,document.head.append?document.head.append(l):document.getElementsByTagName("head")[0].appendChild(l)})}};hi([tB({settings:{timeout:0,retries:3},onError(A,e,o){var a;A?.status===404||(a=A?.message)!=null&&a.includes("404")?(this._log.warn("download 404, stop retry"),o(A)):e()},onRetrying(A){this._log.warn("download retrying: ".concat(A))}})],Cj.prototype,"download"),hi([tB({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],Cj.prototype,"loadScript");var hj=new Cj;function Rz(A){let[e,o]=A,a=o.byteLength,l=parseInt(String(a/255),10),d=a%255,h=[];h.push(0,0,0,1,6,e);for(let S=0;SV+J.dataView.byteLength,0),h=new ArrayBuffer(d+e.data.byteLength),y=new DataView(h),S=new DataView(e.data),k=0;for(let V=0;Vl.isSEI);o?.(a.reverse())}catch{}return e}function bz(A){let{seiMessageList:e,isAudio:o,getNtpTime:a,isMain:l}=A;return new TransformStream({transform(d,h){let y=d;o?audioEncodePipeline.forEach(S=>{y=S({frame:y,ntp:a(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:""})}})}):videoEncodePipeline.forEach(S=>{y=S({frame:y,seiMessageList:e,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:y.data,userId:"",streamType:l?"main":"auxiliary"})}})}),h.enqueue(y)}})}function kz(A){let{userId:e,streamType:o,isAudio:a}=A;return new TransformStream({transform(l,d){let h=l;a?(audioDecodePipeline.forEach(y=>{h=y({frame:h,onAudioFrameNTPTime:S=>{self.postMessage({type:"audio-ntp",data:S,userId:e,streamType:o})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:h.data,userId:e})}})}),d.enqueue(h)):videoDecodePipeline.forEach(y=>{h=y({frame:h,onSEI:S=>{S.forEach(k=>{self.postMessage({type:"sei",seiPayloadType:k.seiPayloadType,data:k.seiPayload.buffer,userId:e,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:h.data,userId:e,streamType:o})}})}),d.enqueue(h)}})}function Lz(A){let e=[u1],o=[Tz,wz,tz,_z,Rz,bz,kz,b0,lM,I1],a="const videoEncodePipeline=[".concat(A.videoEncodePipeline.toString(),`]; const videoDecodePipeline=[`).concat(A.videoDecodePipeline.toString(),`]; const audioEncodePipeline = [`).concat(A.audioEncodePipeline.toString(),`]; - const audioDecodePipeline = [`).concat(A.audioDecodePipeline.toString(),"];"),c="(()=>{".concat(e.map(S=>"const ".concat(S.name,"=(()=>").concat(S.toString(),")()")).join(` + const audioDecodePipeline = [`).concat(A.audioDecodePipeline.toString(),"];"),l="(()=>{".concat(e.map(S=>"const ".concat(S.name,"=(()=>").concat(S.toString(),")()")).join(` `),` `).concat(o.map(S=>S.toString()).join(` -`),";(").concat(()=>{let S=[],k=[],V=[],J=0;self.onmessage=gA=>{switch(gA.data.type){case"sei":gA.data.isMain?(S.push(gA.data.data),gA.data.small&&V.push(gA.data.data)):k.push(gA.data.data);break;case"ntp-offset":J=gA.data.data}},self.onrtctransform=gA=>{let{options:CA}=gA.transformer,MA=CA.isReceiver?Iz({userId:CA.userId,streamType:CA.streamType,isAudio:CA.isAudio}):lz({getNtpTime:()=>Date.now()+J,isAudio:CA.isAudio,isMain:CA.isMain,seiMessageList:CA.isMain?CA.small?V:S:k});gA.transformer.readable.pipeThrough(MA).pipeTo(gA.transformer.writable)}},")();").concat(a,"})()"),d=new Blob([c],{type:"text/javascript"}),C=URL.createObjectURL(d),y=new Worker(C);return URL.revokeObjectURL(C),y}var Ez,ij=class{constructor(A){Y(this,"audioPlayer"),Y(this,"videoPlayer"),Y(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(fo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(fo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(fo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(fo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(fo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(fo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(fo.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),Ha&&sy&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),Ha&&sy?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(A){A.muted!==void 0&&this.audioPlayer.muted!==A.muted&&(this.log.warn("sync audio muted to ".concat(A.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(A.muted))}destroy(){this.videoPlayer.off(fo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(fo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(fo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(fo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(fo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(fo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(fo.VOLUME_CHANGE,this.handleVolumeChange,this)}},dz=!1;function QiA(A){var e=this;let{TRTC:o,room:a,errorModule:c,assetsPath:d}=A;return{TRTC:o,LocalMixVideoTrack:jK,LocalVideoTrack:dQ,LocalScreenTrack:qM,room:a,assetsPath:d,fileDownloader:tj,innerEmitter:F,INNER_EVENT:nA,constants:Tx,environment:E2,utils:k5,eventLogger:sn,log:this.room.getLogger(),loggerManager:QA,errorModule:c,kvStatManager:ii,rtcDectection:te,trtc:this,rx:c5,enums:ke,schedule:Az,getDevices:q2,initVisionTaskRegistry:function(C,y){let S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return KA(e,null,function*(){!window.VisionTaskRegistry&&!dz&&(dz=!0,Ez=tj.loadScript("".concat(C,"/").concat(S).replace(/([^:]\/)\/+/g,"$1"))),yield Ez,yield(yield window.VisionTaskRegistry.getInstance(C)).preloadModels(y)})},audioContext:FI(),deviceDetector:Pc,AudioPlayer:bK,RemoteAudioPlayer:o5,VideoPlayer:vo,showAutoPlayDialog:YC,Timer:Gr,clearStarted:(C,y)=>{let S=C.getAlias(),k=IL.instances.get(this);if(k)if(y){let V=k.get(S+y);if(!V)return;V.started=!1}else k.forEach((V,J)=>{J.startsWith(S)&&(V.started=!1)})},startGetPCM:XK,createAudioNode:V2,getNetworkTimeOffset:Rx,validateSourceNode:()=>{var C;if(er&&((C=this.room.audioManager._localAudioPipline)==null||!C.source.node))throw new wo({code:Ro.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:uz,AVPlayerStateSyncManager:ij,PlayerEvent:fo}}var h_=new WeakMap,Cz="5.15.3-beta.12";function hu(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,C=new Array(d),y=0;yfunction(){for(var d=arguments.length,C=new Array(d),y=0;yWf(V)?iM(V):Yn(V)?V:Cg(V))},value:o}})}else if(!Je(e.type)&&Cg(o)!==e.type)throw new wo(C(5002));if(e.allowEmpty===!1){let k=bn(o)&&(o===0||Number.isNaN(o)),V=Yn(o)&&o.trim()==="";if(k||V)throw new wo(C(5003))}if(e.notLessThanZero&&bn(o)&&o<0)throw new wo(C(5006));if(!Je(e.min)&&bn(o)&&oe.max)throw new wo(C(5008));if(Yn(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new wo(C(5004))}else if(Ra(e.instanceOf)&&!(o instanceof e.instanceOf))throw new wo(C(5004));if(Array.isArray(e.values)&&!e.values.includes(o))throw new wo(C(5005));let{properties:y}=e;lE(y)&&$E(o)&&Object.keys(y).forEach(k=>{d1.call(this,{rule:y[k],value:o&&o[k],key:"".concat(k),fnName:c,className:d})});let{arrayItem:S}=e;lE(S)&&wa(o)&&o.forEach((k,V)=>{d1.call(this,{rule:S,value:k,key:"".concat(a,"[").concat(V,"]"),fnName:c,className:d})}),Ra(e.validate)&&e.validate.call(this,o,a,c,d,this)}var piA=0;function fa(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:e=()=>"",replaceArg:o,getKVReportKey:a,ignoreLog:c,ignoreErrorLog:d}=A;return jr((C,y)=>function(){for(var S=arguments.length,k=new Array(S),V=0;V0?$A.info("".concat(y,"() ").concat(Be," ").concat(JSON.stringify(k,(yi,Ge)=>MA(yi,Ge,["userSig","privateMapKey"])))):$A.info("".concat(y,"() ").concat(Be));let Ye=a?a(...k):w2[y],ve=d?.(...k)||!1;try{let yi=C.apply(this,k),Ge=ko();if(jf(yi)){let Bt="".concat(y.includes("Plugin")?"".concat(((gA=(J=k[0]).getName)==null?void 0:gA.call(J))||""," "):" ");return yi.then(hi=>($A.info("".concat(y,"() success ").concat(Be," ").concat(Bt).concat(e.call(this,...k))),ii.addSuccessEvent({key:Ye,cost:ko()-Ge}),hi)).catch(hi=>{var Di;let Vo=(hi=wo.convertFrom.call(this,hi,y,k.length===1?k[0]:k)).extraCode||hi.code,Jo=(Di=hi.message)!=null&&Di.includes(Vo)?"":" code:".concat(Vo),Qn=hi?.code===Ro.OPERATION_ABORT;throw ve||$A[Qn?"warn":"error"]("".concat(y,"() failed ").concat(Be," ").concat(Bt).concat(e.call(this,...k)," ").concat(hi).concat(Jo," params: ").concat(JSON.stringify(k,MA))),ii.addFailedEvent({key:Ye,error:hi}),hi})}return ii.addSuccessEvent({key:Ye}),yi}catch(yi){let Ge=(yi=wo.convertFrom.call(this,yi,y)).extraCode||yi.code,Bt=(CA=yi.message)!=null&&CA.includes(Ge)?"":" code:".concat(Ge),hi=yi?.code===Ro.OPERATION_ABORT;throw ve||$A[hi?"warn":"error"]("".concat(y,"() failed ").concat(Be," ").concat(yi).concat(Bt," params: ").concat(JSON.stringify(k,MA))),ii.addFailedEvent({key:Ye,error:yi}),yi}})}var sj,nj=A=>jr((e,o)=>function(a,c){return KA(this,null,function*(){let d=this._plugins.get(a);if(!d)throw this._log.error("plugin ".concat(String(a)," is not found")),new wo({code:Ro.OPERATION_ABORT,message:"plugin ".concat(String(a)," is not found"),fnName:o});if(Ra(d.constructor.isSupported)&&!d.constructor.isSupported())throw this._log.error("plugin ".concat(String(a)," is not supported")),new wo({code:Ro.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(a)," is not supported"),extraCode:5210,fnName:o});return oj.call(this,d.getValidateRule(A),[c],o,"TRTC"),e.call(this,d,c)})}),rj=0,C1=class GL{constructor(e){this.core=e,Y(this,"log"),Y(this,"customAudioReferenceMap",new Map),Y(this,"audioRefId",0),Y(this,"audioContext",FI()),Y(this,"localAudioWorkletNode"),Y(this,"screenAudioWorkletNode"),Y(this,"mixNode"),Y(this,"silentNode"),rj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(rj)}),this.log.info("created id=".concat(this.getAlias()).concat(rj)),this.installEvent()}static getStartValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(o,a,c,d){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5106,fnName:c})}}}preload(e){return sj||(sj=this.doPreload(e)),sj}doPreload(e){return KA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Vg(this.audioContext,a)}catch(c){this.log.error("preload audioProcessor failed. ".concat(c))}finally{URL.revokeObjectURL(a)}})}getName(){return GL.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(e){switch(e){case"start":return GL.getStartValidateRule(this.core);case"update":return GL.updateValidateRule;case"stop":return GL.stopValidateRule}}start(e){return KA(this,null,function*(){var o,a,c,d;let{room:C}=this.core,{sdkAppId:y,userId:S,userSig:k,assetsPath:V=this.core.assetsPath,audioReference:J,processLevel:gA,enableDump:CA,isLocalAudioNeedAudioProcess:MA=!0,isScreenAudioNeedAudioProcess:$A=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=MA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=$A,!V)throw new wo({code:Ro.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(V,"/audioProcessor-wasm.js")),MA&&!this.localAudioWorkletNode){let{sign:Be,status:Ye,timestamp:ve}=yield this.getAuthData(y,S,k);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",y,S,ve,Be,Ye,C)}if($A&&!this.screenAudioWorkletNode){let{sign:Be,status:Ye,timestamp:ve}=yield this.getAuthData(y,S,k);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",y,S,ve,Be,Ye,C)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"enable"}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"enable"}),C.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),Je(J)||J.forEach(Be=>{this.customAudioReferenceMap.set(Be,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:Be,refId:"o-".concat(this.audioRefId++)})}),Je(gA)||(c=this.localAudioWorkletNode)==null||c.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:gA}}),Je(CA)||(d=this.localAudioWorkletNode)==null||d.port.postMessage({type:"dump",data:{enable:CA}})})}update(e){return KA(this,null,function*(){var o,a,c;let{audioReference:d,enableDump:C,processLevel:y}=e;Je(d)||(this.customAudioReferenceMap.forEach((S,k)=>{this.customAudioReferenceMap.delete(k),this.core.room.audioManager.updateAudioReference({type:"remove",refId:S})}),d.forEach(S=>{this.customAudioReferenceMap.set(S,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:S,refId:"o-".concat(this.audioRefId++)})})),Je(y)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:y}}),Je(C)||((a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:C}}),(c=this.screenAudioWorkletNode)==null||c.port.postMessage({type:"dump",data:{enable:C}}))})}stop(){return KA(this,null,function*(){var e,o;let{room:a}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield a.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,o,a){return KA(this,null,function*(){let c=String(Date.now()).slice(0,-3),{auth:d,sign:C,status:y,message:S}=yield function(k){return KA(this,arguments,function(V){let{sdkAppId:J,userId:gA,userSig:CA,timestamp:MA}=V;return function*(){let $A="".concat(function(Vo){let Jo=arguments.length>1&&arguments[1]!==void 0?arguments[1]:YA.MAIN;return"https://".concat(em[Jo]||Aj(Vo,Jo),"/api/v1/audioAiAuth")}(J),"?sdkAppId=").concat(J,"&userId=").concat(gA,"&userSig=").concat(CA,"×tamp=").concat(MA),Be=yield fetch($A),{data:{errCode:Ye,errMsg:ve,sign:yi,status:Ge}}=yield Be.json();if(Ge==="1")return{auth:!0,sign:yi,status:Ge,message:ve};let Bt=Kd(J)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",hi="Init RTCAudioProcessor failed.",Di="";switch(Ye){case 1:Di="Please check your params.";break;case 2:Di="You need to buy packages. Refer to: ".concat(Bt);break;case 3:Di="Server is invalid. Please contact our engineer. ";break;case 4:Di="Your packages is not active. Refer to: ".concat(Bt);break;case 5:Di="Your packages is expired. Refer to: ".concat(Bt);break;case 6:Di="Your version is not supported."}return{auth:!1,status:Ge,message:ve?"".concat(hi," Reason: ").concat(ve,". ").concat(Di):"".concat(hi,", ").concat(Di)}}()})}({sdkAppId:e,userSig:a,userId:o,timestamp:c});if(!d)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(d,". Message: ").concat(S)),new wo({code:Ro.INVALID_PARAMETER,message:S});return{sign:C,status:y,timestamp:c}})}initWorkletNode(e,o,a,c,d,C,y,S){e.port.postMessage({type:"init",data:{sdkAppId:String(a),userId:c,timestamp:d,sign:C,status:y}}),e.port.onmessage=k=>{var V;let{data:J}=k;switch(J.type){case"cost":let gA=J?.value>10?"info":"debug";return void this.log[gA]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(J.value," max: ").concat(J?.max,"(").concat(mb(new Date(J?.maxCostTimestamp)),") hist: ").concat((V=J?.hist)==null?void 0:V.join(" ")));case"log":return void this.log[J.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(J.value));case"dump":return void F.emit("265",{room:S,data:J.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(q0()?rQ():Yp()))}}}handleLocalAudioStarted(e){return KA(this,null,function*(){var o;if(this.hitTest(e.room)&&((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)===!0)try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(a){this.log.warn("audio processor auto start failed, error: ".concat(a))}})}handleLocalAudioStopped(e){return KA(this,null,function*(){var o;!this.hitTest(e.room)||((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(e){return e===this.core.room}};Y(C1,"updateValidateRule",{type:"object"}),Y(C1,"stopValidateRule",{type:"object"}),Y(C1,"Name","AudioProcessor");var miA=C1,aj=0,fiA=class{constructor(A,e){Y(this,"audioObjectURL"),Y(this,"player"),Y(this,"publisher"),Y(this,"mixInput"),this.mixInput=new Z4(e),A.url?(this.player=new Audio(A.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(A.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(A.track),this.mixInput.connect()}updateSettings(A){this.player&&(Je(A.volume)||(this.volume=A.volume),Je(A.loop)||(this.loop=A.loop),Je(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:e}=A;this.player.ondurationchange=o=>{e(o.target.duration)}}if(A.onTimeUpdate){let e=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{e(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return KA(this,null,function*(){if(A.url){let e=yield tj.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(A),this.updateSettings(A))}else this.mixInput.replaceSource(A.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(A){this.player&&(A<0&&A>this.player.duration||(this.player.currentTime=A,this.publisher.currentTime=A))}play(){var A,e;return Promise.all([(A=this.player)==null?void 0:A.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var A,e;(A=this.player)==null||A.pause(),(e=this.publisher)==null||e.pause()}stop(){var A;(A=this.player)==null||A.pause(),this.mixInput.disconnect()}setOperation(A){A==="pause"&&this.pause(),A==="resume"&&(this.pause(),this.play()),A==="stop"&&(this.pause(),this.seek(0))}set volume(A){!this.player||!this.publisher||(this.player.volume=A,this.publisher.volume=A)}set loop(A){!this.player||!this.publisher||(this.player.loop=A,this.publisher.loop=A)}set playbackRate(A){!this.player||!this.publisher||(this.player.playbackRate=A,this.publisher.playbackRate=A)}};function B_(A,e){if(e&&typeof e!="function")throw new wo({code:Ro.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var EL=class bL{constructor(e){this.core=e,Y(this,"log"),Y(this,"mixedMusicMap",new Map),Y(this,"cacheMusicMap",new Map),aj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(aj)}),this.log.info("created id=".concat(this.getAlias()).concat(aj))}getName(){return bL.Name}getAlias(){return"ax"}getGroup(e){return e?.id}getValidateRule(e){switch(e){case"start":return bL.startValidateRule;case"update":return bL.updateValidateRule;case"stop":return bL.stopValidateRule}}start(e){return KA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:a,url:c}=e;if(this.mixedMusicMap.has(a))return;let d=this.cacheMusicMap.get(a);d?e.url?d.reset():(d.mixInput.replaceSource(e.track),d.mixInput.connect()):(d=new fiA(e,o.audioManager),this.cacheMusicMap.set(a,d)),d.updateListener(e),d.updateSettings(e);try{yield d.play()}catch(C){yield this.handleAutoPlayFailed(d,e,C)}this.mixedMusicMap.set(a,d),d.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d.mixInput.source.node,refId:"ax-".concat(a)}),this.log.info("start mix audio track ".concat(a," success.")),ii.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,o,a){return KA(this,null,function*(){if(a.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(a)),yield e.reload(o),yield e.play();else{if(a.name!=="NotAllowedError")throw a;if(this.core.room.enableAutoPlayDialog){let c=()=>{var d;(d=e.play())==null||d.finally(()=>{F.off("154",c,this)})};F.on("154",c,this),YC()}else this.core.trtc.emit(Hi.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>KA(this,null,function*(){return e.play()})})}})}update(e){return KA(this,null,function*(){let{id:o,operation:a,seekFrom:c,playbackRate:d}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let C=this.mixedMusicMap.get(o);C?(C.updateSettings(e),C.updateListener(e),Je(a)||C.setOperation(a),Je(c)||C.seek(c),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(e){return KA(this,arguments,function(o){var a=this;let{id:c}=o;return function*(){if(a.mixedMusicMap.has(c)){a.log.info("remove music source, music id: ".concat(c));let d=a.mixedMusicMap.get(c);d!=null&&d.mixInput.source.node&&a.core.room.audioManager.updateAudioReference({type:"remove",audioReference:d.mixInput.source.node,refId:"ax-".concat(c)}),d?.stop(),a.mixedMusicMap.delete(c)}c==="*"&&a.destroyAllMusic()}()})}kvUpload(e){let{track:o,loop:a,volume:c,playbackRate:d,operation:C,seekFrom:y,onTimeUpdate:S,onDurationChange:k,onEnded:V}=e;o&&ii.addCount({key:502009}),a&&ii.addCount({key:502001}),c&&ii.addCount({key:502002}),d&&ii.addCount({key:502003}),C&&ii.addCount({key:502004}),y&&ii.addCount({key:502005}),typeof S!="function"&&ii.addCount({key:502007}),typeof V!="function"&&ii.addCount({key:502008}),typeof k!="function"&&ii.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((e,o)=>{e!=null&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId:o}),this.stop({id:o})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};Y(EL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(A,e,o){if(A.url&&A.url!=="*"){let a=A.url.split("?")[0],c=["mp3","ogg","wav","flac"],d=a.split(".").pop(),C=c.indexOf(d)>=0,y=a.startsWith("blob"),S=a.startsWith("data");if(!(C||y||S))throw new wo({code:Ro.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new wo({code:Ro.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});B_("onTimeUpdate",A.onTimeUpdate),B_("onEnded",A.onEnded),B_("onDurationChange",A.onDurationChange)}}),Y(EL,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(A,e,o){B_("onTimeUpdate",A.onTimeUpdate),B_("onEnded",A.onEnded),B_("onDurationChange",A.onDurationChange)}}),Y(EL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Y(EL,"Name","AudioMixer");var gj,yiA=EL,cj=0,h1=class kL{constructor(e){this.core=e,Y(this,"log"),Y(this,"audioContext",FI()),Y(this,"workletNode"),Y(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),cj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(cj)}),this.log.info("created id=".concat(this.getAlias()).concat(cj))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(o,a,c,d){if(!e.room.audioManager.hasAudioTrack)throw new wo({code:Ro.INVALID_OPERATION,extraCode:5106,fnName:c})}}}preload(e){return gj||(gj=this.doPreload(e)),gj}doPreload(e){return KA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Vg(this.audioContext,a)}catch(c){throw this.log.error("load worklet failed",c),c}finally{URL.revokeObjectURL(a)}})}getName(){return kL.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(e){switch(e){case"start":return kL.startValidateRule(this.core);case"update":return kL.updateValidateRule;case"stop":return kL.stopValidateRule}}start(e){return KA(this,null,function*(){let{room:o,schedule:a}=this.core,{assetsPath:c=this.core.assetsPath}=e;if(!c)throw new wo({code:Ro.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(c,"/denoiser-wasm").concat(bM()?"":"-nosimd",".js")),!this.workletNode){let d=String(Date.now()).slice(0,-3),{auth:C,sign:y,status:S,message:k}=yield function(V,J){return KA(this,arguments,function(gA,CA){let{sdkAppId:MA,userId:$A,userSig:Be,timestamp:Ye}=CA;return function*(){try{let{data:{errCode:ve,errMsg:yi,sign:Ge,status:Bt}}=yield gA.getAbilityConfig(MA,gA.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:MA,userId:$A,userSig:Be,timestamp:Ye});if(Bt==="1")return{auth:!0,sign:Ge,status:Bt,message:yi};let hi=Kd(MA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Di="Init RTCAIDenoiser failed.",Vo="";switch(ve){case 1:Vo="Please check your params.";break;case 2:Vo="You need to buy packages. Refer to: ".concat(hi);break;case 3:Vo="Server is invalid. Please contact our engineer. ";break;case 4:Vo="Your packages is not active. Refer to: ".concat(hi);break;case 5:Vo="Your packages is expired. Refer to: ".concat(hi);break;case 6:Vo="Your version is not supported."}return{auth:!1,status:Bt,message:yi?"".concat(Di," Reason: ").concat(yi,". ").concat(Vo):"".concat(Di,", ").concat(Vo)}}catch(ve){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(ve)}}}()})}(a,Qo(mi({},e),{timestamp:d}));if(!C)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(C,". Message: ").concat(k)),new wo({code:Ro.INVALID_PARAMETER,message:k});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:d,sign:y,status:S}}),this.workletNode.port.onmessage=V=>{var J;let{data:gA}=V;if(gA.type==="cost"){let CA=gA?.max>20?"warn":gA?.max>10?"info":"debug";this.log[CA]("avg cost: ".concat(gA.value," max: ").concat(gA?.max,"(").concat(mb(new Date(gA?.maxCostTimestamp)),") hist: ").concat((J=gA?.hist)==null?void 0:J.join(" ")))}else gA.type==="log"&&this.log[gA.logLevel]("".concat(gA.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(e){return KA(this,null,function*(){this.updateConfig(e)})}stop(){return KA(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let o=!1;Je(e.mode)||(e.mode===0?this.config.enableFarFieldReduce=!1:e.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),Je(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};Y(h1,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Y(h1,"stopValidateRule",{type:"object"}),Y(h1,"Name","AIDenoiser");var DiA=h1,SiA=gc(Kl(),1),MiA=class extends SiA.EventEmitter{constructor(){super(),Y(this,"observer"),Y(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return KA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Ha&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){sn.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let e=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||e>3)&&QA.info("".concat(o.source,": ").concat(o.state)),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var A;try{(A=this.observer)==null||A.disconnect(),this.observer=null}catch(e){sn.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:e})}}},Bz=new MiA,lj=0,Ij=class U9{constructor(e){this.core=e,Y(this,"log"),Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_subStreamSeiMessageList",[]),lj++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(lj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(lj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:o,mediaType:a}=e;try{return gz({frame:o,seiMessageList:a===8?this._smallSeiMessageList:a===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(c){this.log.warn(c)}return o}decode(e){let{frame:o,track:a}=e;return cz({frame:o,onSEI:c=>{c.forEach(d=>{a!=null&&a.userId?this.core.trtc.emit(Hi.SEI_MESSAGE,{seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:a.userId,streamType:a.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:d})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:Kp?this.encode:gz,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Kp?this.decode:cz,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:o,options:a}=e;var c;let d=[a.seiPayloadType,o],C=!!a.small;a.toSubStream?this._subStreamSeiMessageList.push(d):(this._seiMessageList.push(d),C&&this._smallSeiMessageList.push(d)),(c=this.core.room.scriptTransformWorker)==null||c.postMessage({type:"sei",data:d,isMain:!a.toSubStream,small:C})}getName(){return U9.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Y(Ij,"autoStart",!0),Y(Ij,"Name","SEI");var B1,viA=Ij,RiA=0,uj=class F9{constructor(e){this.core=e,Y(this,"_core"),Y(this,"log"),Y(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++RiA)}),this.log.info("created")}getName(){return F9.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return KA(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return KA(this,arguments,function(o){var a=this;let{visible:c}=o;return function*(){c?yield a.openDebugDiaLog():a.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return KA(this,null,function*(){var e;if(!this.dialog)try{if(B1)yield B1;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(qd,"/assets/debug-dialog.js");B1=this._core.fileDownloader.loadScript(o),yield B1}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(o){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(o))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};Y(uj,"Name","Debug"),Y(uj,"autoStart",!0);var wiA=uj,Qz=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},pz=class{constructor(A,e,o){Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"type","auto"),Y(this,"config"),Y(this,"decoder"),Y(this,"_decodeSink");let{kvStatManager:a,trtc:c}=A;this.config=o.config,this.trackDoneOB=ca(e,Zs.INIT),this.stopOB=EQ(),this.startOB=EQ(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let d=EQ();ma(this.startOB,FK(0),$2(C=>{let y=this.pipe(e);return d.next("STARTING"),e.log.info("decoder type: ".concat(this.type)),ma(y,EE(this.stopOB),Bl(()=>{},S=>{e.log.error(S),a.addFailedEvent({key:Qz(this.type),error:S}),C>4?this.startOB.error(S):this.startOB.next(C+1)})),ma(y,l_(1),N5(xK))}),EE(this.stopOB),Bl(()=>{e.player.setOutput(),d.next("STARTED")},C=>{d.next("FAILED")},()=>{a.addSuccessEvent({key:Qz(this.type)}),a.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return AL()(e=>KA(this,null,function*(){this._decodeSink=e,e.defer(()=>{var a;(a=this.decoder)==null||a.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:a=>{A.log.error(a),e.error(4)},output:a=>{this.decodedFrameCount++,e.next(a),A.player.write(a)}})),this.decoder.configure(this.config)}catch(a){A.log.error(a),e.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},_iA={type:"object"},mz=class U3{constructor(e){this.core=e,Y(this,"log"),Y(this,"contextMap",new Map),Y(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return U3.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return U3.Name}getValidateRule(e){return _iA}start(e){let{track:o}=e;this.decodeProcessorMap.set(o,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:a=>{let{frame:c,track:d}=a;return this.decodeProcessorMap.has(d)?this.decodeProcessorMap.get(d)({frame:c,track:d}):c},type:3})}decode(e){return o=>{let{frame:a,track:c}=o;if(c!==e.track)return a;if(this.contextMap.has(c))return this.contextMap.get(c).decodeFrame(a);let d=new pz(this.core,c,e);return ma(d.trackDoneOB,l_(1),Bl(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:c})})),this.contextMap.set(c,d),d.decodeFrame(a)}}stop(e){let{track:o}=e,a=this.contextMap.get(o);a&&(a.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let o=this.contextMap.get(e.track);if(o){if(e.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(e.track,new pz(this.core,e.track,e))}}};Y(mz,"Name","TRTCAudioDecoder");var fz=mz,TiA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},NiA=class{constructor(){Y(this,"log"),Y(this,"autoMode",{enabled:!1,instance:null,config:TiA,sortedStreamList:[],currentQualityIndex:0}),Y(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),Y(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),Y(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),Y(this,"onStatistics",A=>{var e,o;if(!this.autoMode.instance)return;let{config:a}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttV.userId===d);if((o=y?.video)==null||!o.length)return;let S=C==="sub"?"sub":"big",k=y.video.find(V=>V.videoType===S);k?(this.networkMetrics.frameRate=k.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(d,", streamType=").concat(C))}),this.log=QA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var e,o;let a=A,c=a._playbackQualityList;if(!c||c.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let d of c){let C=A.room.remotePublishedUserMap.get(d.userId);if(!C)continue;let y=(e=d.streamType)!=null?e:"main";if((y==="sub"?C.remoteAuxiliaryTrack:C.remoteVideoTrack).isPlayCalled){let S=(o=a._remoteVideoConfigMap.get("".concat(d.userId,"_").concat(y)))==null?void 0:o.config;if(S)return{userId:d.userId,streamType:y,config:S}}}return null}switchPlaybackQuality(A){return KA(this,null,function*(){var e;let{trtcInstance:o,streamList:a,quality:c}=A;this.log.info("switchPlaybackQuality quality: ".concat(c,", streamList: ").concat(JSON.stringify(a)));let d=o;if(a&&a.length>0&&(d._playbackQualityList=a.map(MA=>{var $A;return Qo(mi({},MA),{streamType:($A=MA.streamType)!=null?$A:"main"})})),c==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&c&&!this.switchControl.isInternal&&this.stopAutoMode(),!c)return;if(!d._playbackQualityList||d._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let C=d._playbackQualityList.find(MA=>MA.name===c);if(!C)return void this.log.warn('switchPlaybackQuality: quality "'.concat(c,'" not found in streamList'));let y=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(y?.userId,", streamType: ").concat(y?.streamType)),!y)return;let S=(e=C.streamType)!=null?e:"main";if(y.userId===C.userId&&y.streamType===S)return void this.log.info("switchPlaybackQuality: already playing target stream");let k=mi({},y.config);k.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(k.userId,!0));let V,J=new Promise(MA=>{V=MA}),gA=MA=>{MA.userId===C.userId&&MA.streamType===S&&MA.state==="PLAYING"&&MA.reason==="playing"&&V("success")};o.on(Hi.VIDEO_PLAY_STATE_CHANGED,gA);let CA=new Promise(MA=>setTimeout(()=>MA("timeout"),1e4));try{if(yield o.startRemoteVideo(Qo(mi({},y.config),{userId:C.userId,streamType:S,option:Qo(mi({},y.config.option),{isLiveStream:!0})})),(yield Promise.race([J,CA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:C.userId,streamType:S})}catch($A){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",$A)}throw k.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(k.userId,!1).catch($A=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",$A)})),new ai({code:dt.SUBSCRIPTION_TIMEOUT,message:Xo({key:Mo.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:C.userId}})})}let MA=o.stopRemoteVideo(k);k.streamType==="main"&&S==="main"?yield Promise.all([o.muteRemoteAudio(C.userId,!1).catch($A=>{this.log.warn("muteRemoteAudio(new, false) failed",$A)}),MA]):yield MA,d._currentLiveUserId=C.userId,d._currentLiveStreamType=S}finally{o.off(Hi.VIDEO_PLAY_STATE_CHANGED,gA)}})}startAutoMode(A){return KA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let e=A;if(!e._playbackQualityList||e._playbackQualityList.length<=1)return void this.log.warn("startAutoMode: need at least 2 streams in streamList for auto mode");this.autoMode.enabled=!0,this.autoMode.instance=A,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.switchControl.lastSwitchTime=0;let o=e._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((c,d)=>d.bitrate-c.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(c=>"".concat(c.name,"(").concat(c.bitrate,"kbps)")).join(" > ")));let a=this.getCurrentPlayingStream(A);if(a){let{userId:c,streamType:d}=a,C=this.autoMode.sortedStreamList.findIndex(y=>{var S;return y.userId===c&&((S=y.streamType)!=null?S:"main")===d});this.autoMode.currentQualityIndex=C>=0?C:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Hi.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Hi.STATISTICS,this.switchControl.boundOnStatistics),this.switchControl.boundOnStatistics=null,this.autoMode.enabled=!1,this.autoMode.instance=null,this.autoMode.sortedStreamList=[],this.autoMode.currentQualityIndex=0,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.networkMetrics.frameRate=0,this.networkMetrics.rtt=0,this.networkMetrics.loss=0,this.switchControl.isSwitching=!1,this.log.info("auto mode stopped"))}checkAndSwitchQuality(){var A;if(!this.autoMode.enabled||!this.autoMode.instance||this.switchControl.isSwitching)return;let{config:e}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,C=this.networkMetrics.frameRate<=e.fpsPoorLimit,y=this.networkMetrics.loss>=e.lossPoorLimit||this.networkMetrics.rtt>=e.rttPoorLimit,S=C&&y;this.counters.downgradeCondition=S?this.counters.downgradeCondition+1:0;let k=this.counters.rttUnder>=e.goodCount&&this.counters.lossUnder>=e.goodCount,V=this.counters.upgradeFail{if(V.remoteAudioTrack.isAvailable){if(S.get(V.userId))return;let J=y.getPCM(gA=>{e.emit(Hi.AUDIO_FRAME,gA)},V.userId);S.set(V.userId,J)}});else{if(S.get(a))return;let V=y.getPCM(J=>{e.emit(Hi.AUDIO_FRAME,J)},a);S.set(a,V)}else if(a==="*")e.room.remotePublishedUserMap.forEach(V=>{if(V.remoteAudioTrack.isSubscribed){let{userId:J}=V,gA=S.get(J);gA?.abort("disable"),S.delete(J)}});else{let V=S.get(a);V?.abort("disable"),S.delete(a)}})}resumeRemotePlayer(A){return KA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(a=>{let{remoteAudioTrack:c,remoteVideoTrack:d,remoteAuxiliaryTrack:C}=a;A.streamType?A.streamType==="main"?(c.isAvailable&&o.push(c.player.resume()),d.isAvailable&&o.push(d.player.resume())):C.isAvailable&&o.push(C.player.resume()):(c.isAvailable&&o.push(c.player.resume()),d.isAvailable&&o.push(d.player.resume()),C.isAvailable&&o.push(C.player.resume()))}),Promise.all(o)}let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(e)return A.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:o,remoteVideoTrack:a,remoteAuxiliaryTrack:c}=e;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1)):c.isAvailable&&c.player.pause(!1):(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1),c.isAvailable&&c.player.pause(!1))});else{let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);e&&(A.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new ai({code:dt.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new ai({code:dt.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return KA(this,null,function*(){let e=A.trtcInstance;return e._playbackQualitySwitcher||(e._playbackQualitySwitcher=new NiA),e._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return KA(this,null,function*(){let{trtcInstance:e}=A;return A.enable?e.room.prelink(A.sdkAppId,A.userId,A.userSig,CL.frameWorkType,A.roomId,A.strRoomId):e.room.closePrelink()})}};Ci([x5({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],Ej.prototype,"enableAudioFrameEvent"),Ci([x5({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!1,type:"string"},sdkAppId:{required:!1,type:"number"},userSig:{required:!1,type:"string"},roomId:{required:!1,type:"number"},strRoomId:{required:!1,type:"string"}}})],Ej.prototype,"prelink");var GiA=new Ej,biA=gc(Kl(),1),kiA=class extends biA.EventEmitter{constructor(){super(),Y(this,"states",{}),Y(this,"permissionChangeHandler"),Y(this,"log"),this.log=QA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,e;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(e=this.states.microphone)==null?void 0:e.state})}}request(A){return KA(this,null,function*(){if(this.log.info("request ".concat(A.join(", "))),A.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:A.includes("camera"),audio:A.includes("microphone")})).getTracks().forEach(e=>e.stop())})}get(A){return KA(this,null,function*(){try{return this.states[A]||(this.states[A]=yield navigator.permissions.query({name:A}),this.states[A].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(A," permission state: ").concat(this.states[A].state)),this.states[A].state}catch(e){return this.log.error("get ".concat(A," permission failed, error: ").concat(e instanceof Error?e.message:e)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},Q1=new kiA,yz=0,dL=new Set,Zl=null;Nx(Cz),jA.checkStorage();var Ss=class nm extends iK.EventEmitter{constructor(e,o){super(),Y(this,"_room"),Y(this,"_eventListened",new Set),Y(this,"_localVideoTrack",null),Y(this,"_localAudioTrack",null),Y(this,"_localScreenTrack",null),Y(this,"_localScreenAudioTrack",null),Y(this,"_localVideoConfig",null),Y(this,"_localScreenConfig",null),Y(this,"_localAudioConfig",null),Y(this,"_remoteVideoConfigMap",new Map),Y(this,"_remoteAudioConfigMap",new Map),Y(this,"_remoteAudioVolumeMap",new Map),Y(this,"_remoteAudioMuteMap",new Map),Y(this,"_mediaTrackMap",new WeakMap),Y(this,"_log",QA.createLogger({id:"t".concat(++yz)})),Y(this,"_plugins",new Map),Y(this,"_networkQuality",null),Y(this,"_speakerId"),Y(this,"enterRoomParams"),Y(this,"_enableAutoSwitchWhenRecapturing",!0),Y(this,"_autoSubscribeDataChannel",!1),Y(this,"_playbackQualityList",[]),this._room=new e(mi({logger:this._log,frameWorkType:nm.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,Nr(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(a,c)=>a==="plugins"?c.map(d=>d.Name):c))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(a){return this._room.audioManager.dump(a)}}}),o.plugins&&o.plugins.forEach(a=>{this._use(a,o.assetsPath)}),this._use(yiA,o.assetsPath),this._use(miA,o.assetsPath),this._use(DiA,o.assetsPath),this._use(fz,o.assetsPath),this._use(wiA),o.enableSEI&&xk&&this._use(viA),this._room.on("audio-volume",a=>{var c,d;!a.find(C=>C.userId==="")&&this._localAudioTrack&&a.push({userId:"",volume:Math.floor(100*((c=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?c:this._localAudioTrack.getAudioLevel())),floatVolume:(d=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?d:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&a.forEach(C=>{var y;let S=C.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(C.userId))==null?void 0:y.remoteAudioTrack;S&&(C.volume=S.dbVolume)}),o.enableDbVolume&&a.forEach(C=>{var y;let S=C.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(C.userId))==null?void 0:y.remoteAudioTrack;S&&(C.volume=S.dbVolume)}),this.emit(Hi.AUDIO_VOLUME,{result:a.sort((C,y)=>y.volume-C.volume)})}),this._room.videoManager.on("error",a=>{this._log.error(new wo({code:Ro.OPERATION_FAILED,extraCode:5504,message:a.message,originError:a}))}),this._listenEvents(),this._initActiveSpeaker(),((a,c)=>{let{emit:d}=a;a.emit=function(){for(var C=arguments.length,y=new Array(C),S=0;S{let S=[],k=[],V=[],J=0;self.onmessage=cA=>{switch(cA.data.type){case"sei":cA.data.isMain?(S.push(cA.data.data),cA.data.small&&V.push(cA.data.data)):k.push(cA.data.data);break;case"ntp-offset":J=cA.data.data}},self.onrtctransform=cA=>{let{options:CA}=cA.transformer,MA=CA.isReceiver?kz({userId:CA.userId,streamType:CA.streamType,isAudio:CA.isAudio}):bz({getNtpTime:()=>Date.now()+J,isAudio:CA.isAudio,isMain:CA.isMain,seiMessageList:CA.isMain?CA.small?V:S:k});cA.transformer.readable.pipeThrough(MA).pipeTo(cA.transformer.writable)}},")();").concat(a,"})()"),d=new Blob([l],{type:"text/javascript"}),h=URL.createObjectURL(d),y=new Worker(h);return URL.revokeObjectURL(h),y}var Uz,Bj=class{constructor(A){Y(this,"audioPlayer"),Y(this,"videoPlayer"),Y(this,"log"),this.audioPlayer=A.audioPlayer,this.videoPlayer=A.videoPlayer,this.log=A.log.createChild({id:"pip"}),this.videoPlayer.on(yo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(yo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(yo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(yo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(yo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(yo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(yo.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),Ha&&ay&&this.videoPlayer.resetSrcObjectToReplay()}handleUserPauseInPIPOrFullScreen(){this.audioPlayer.isPaused||(this.log.warn("pause audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doPause())}handleEnterPIPOrFullScreen(){this.videoPlayer.element&&this.audioPlayer.muted!==this.videoPlayer.element.muted&&(this.log.warn("sync video muted to ".concat(this.audioPlayer.muted," when enter ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.videoPlayer.element.muted=this.audioPlayer.muted)}handleLeavePIP(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume after leave pip"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave pip"),this.videoPlayer.doResume())}handleLeaveFullScreen(){this.audioPlayer.isPaused&&!this.audioPlayer.isPausedByUserCall&&(this.log.warn("resume audio after leave fullscreen"),this.audioPlayer.doResume()),this.videoPlayer.isPaused&&!this.videoPlayer.isPausedByUserCall&&(this.log.warn("resume video after leave fullscreen"),Ha&&ay?this.videoPlayer.resetSrcObjectToReplay():this.videoPlayer.doResume())}handleVolumeChange(A){A.muted!==void 0&&this.audioPlayer.muted!==A.muted&&(this.log.warn("sync audio muted to ".concat(A.muted," in ").concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.setMuted(A.muted))}destroy(){this.videoPlayer.off(yo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(yo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(yo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(yo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(yo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(yo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(yo.VOLUME_CHANGE,this.handleVolumeChange,this)}},Fz=!1;function jiA(A){var e=this;let{TRTC:o,room:a,errorModule:l,assetsPath:d}=A;return{TRTC:o,LocalMixVideoTrack:gj,LocalVideoTrack:BQ,LocalScreenTrack:WM,room:a,assetsPath:d,fileDownloader:hj,innerEmitter:F,INNER_EVENT:nA,constants:xx,environment:D2,utils:oz,eventLogger:sn,log:this.room.getLogger(),loggerManager:pA,errorModule:l,kvStatManager:si,rtcDectection:re,trtc:this,rx:G5,enums:Ue,schedule:yz,getDevices:t1,initVisionTaskRegistry:function(h,y){let S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return WA(e,null,function*(){!window.VisionTaskRegistry&&!Fz&&(Fz=!0,Uz=hj.loadScript("".concat(h,"/").concat(S).replace(/([^:]\/)\/+/g,"$1"))),yield Uz,yield(yield window.VisionTaskRegistry.getInstance(h)).preloadModels(y)})},audioContext:OI(),deviceDetector:Pc,AudioPlayer:WK,RemoteAudioPlayer:v5,VideoPlayer:Ro,showAutoPlayDialog:HC,Timer:Gr,clearStarted:(h,y)=>{let S=h.getAlias(),k=BL.instances.get(this);if(k)if(y){let V=k.get(S+y);if(!V)return;V.started=!1}else k.forEach((V,J)=>{J.startsWith(S)&&(V.started=!1)})},startGetPCM:uj,createAudioNode:$2,getNetworkTimeOffset:Ox,validateSourceNode:()=>{var h;if(or&&((h=this.room.audioManager._localAudioPipline)==null||!h.source.node))throw new _o({code:wo.DEVICE_ERROR,extraCode:5310,message:"The audio processing plugin cannot be used due to the microphone's sampling rate is not 48KHz in Firefox. Please switch to another browser such as Chrome."})},createScriptTransformWorker:Lz,AVPlayerStateSyncManager:Bj,PlayerEvent:yo}}var p_=new WeakMap,Oz="5.15.3-beta.12";function Bu(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,h=new Array(d),y=0;yfunction(){for(var d=arguments.length,h=new Array(d),y=0;yXf(V)?nM(V):Vn(V)?V:Cg(V))},value:o}})}else if(!Ke(e.type)&&Cg(o)!==e.type)throw new _o(h(5002));if(e.allowEmpty===!1){let k=kn(o)&&(o===0||Number.isNaN(o)),V=Vn(o)&&o.trim()==="";if(k||V)throw new _o(h(5003))}if(e.notLessThanZero&&kn(o)&&o<0)throw new _o(h(5006));if(!Ke(e.min)&&kn(o)&&oe.max)throw new _o(h(5008));if(Vn(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new _o(h(5004))}else if(Ra(e.instanceOf)&&!(o instanceof e.instanceOf))throw new _o(h(5004));if(Array.isArray(e.values)&&!e.values.includes(o))throw new _o(h(5005));let{properties:y}=e;IE(y)&&XE(o)&&Object.keys(y).forEach(k=>{S1.call(this,{rule:y[k],value:o&&o[k],key:"".concat(k),fnName:l,className:d})});let{arrayItem:S}=e;IE(S)&&wa(o)&&o.forEach((k,V)=>{S1.call(this,{rule:S,value:k,key:"".concat(a,"[").concat(V,"]"),fnName:l,className:d})}),Ra(e.validate)&&e.validate.call(this,o,a,l,d,this)}var WiA=0;function fa(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:e=()=>"",replaceArg:o,getKVReportKey:a,ignoreLog:l,ignoreErrorLog:d}=A;return jr((h,y)=>function(){for(var S=arguments.length,k=new Array(S),V=0;V0?ie.info("".concat(y,"() ").concat(pe," ").concat(JSON.stringify(k,(Di,Le)=>MA(Di,Le,["userSig","privateMapKey"])))):ie.info("".concat(y,"() ").concat(pe));let qe=a?a(...k):O2[y],we=d?.(...k)||!1;try{let Di=h.apply(this,k),Le=ko();if(Zf(Di)){let Qt="".concat(y.includes("Plugin")?"".concat(((cA=(J=k[0]).getName)==null?void 0:cA.call(J))||""," "):" ");return Di.then(Bi=>(ie.info("".concat(y,"() success ").concat(pe," ").concat(Qt).concat(e.call(this,...k))),si.addSuccessEvent({key:qe,cost:ko()-Le}),Bi)).catch(Bi=>{var Si;let Jo=(Bi=_o.convertFrom.call(this,Bi,y,k.length===1?k[0]:k)).extraCode||Bi.code,Ho=(Si=Bi.message)!=null&&Si.includes(Jo)?"":" code:".concat(Jo),Qn=Bi?.code===wo.OPERATION_ABORT;throw we||ie[Qn?"warn":"error"]("".concat(y,"() failed ").concat(pe," ").concat(Qt).concat(e.call(this,...k)," ").concat(Bi).concat(Ho," params: ").concat(JSON.stringify(k,MA))),si.addFailedEvent({key:qe,error:Bi}),Bi})}return si.addSuccessEvent({key:qe}),Di}catch(Di){let Le=(Di=_o.convertFrom.call(this,Di,y)).extraCode||Di.code,Qt=(CA=Di.message)!=null&&CA.includes(Le)?"":" code:".concat(Le),Bi=Di?.code===wo.OPERATION_ABORT;throw we||ie[Bi?"warn":"error"]("".concat(y,"() failed ").concat(pe," ").concat(Di).concat(Qt," params: ").concat(JSON.stringify(k,MA))),si.addFailedEvent({key:qe,error:Di}),Di}})}var pj,mj=A=>jr((e,o)=>function(a,l){return WA(this,null,function*(){let d=this._plugins.get(a);if(!d)throw this._log.error("plugin ".concat(String(a)," is not found")),new _o({code:wo.OPERATION_ABORT,message:"plugin ".concat(String(a)," is not found"),fnName:o});if(Ra(d.constructor.isSupported)&&!d.constructor.isSupported())throw this._log.error("plugin ".concat(String(a)," is not supported")),new _o({code:wo.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(a)," is not supported"),extraCode:5210,fnName:o});return Qj.call(this,d.getValidateRule(A),[l],o,"TRTC"),e.call(this,d,l)})}),fj=0,M1=class OL{constructor(e){this.core=e,Y(this,"log"),Y(this,"customAudioReferenceMap",new Map),Y(this,"audioRefId",0),Y(this,"audioContext",OI()),Y(this,"localAudioWorkletNode"),Y(this,"screenAudioWorkletNode"),Y(this,"mixNode"),Y(this,"silentNode"),fj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(fj)}),this.log.info("created id=".concat(this.getAlias()).concat(fj)),this.installEvent()}static getStartValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0}},validate(o,a,l,d){if(!e.room.audioManager.hasAudioTrack&&!e.room.audioManager.hasScreenAudioTrack)throw new _o({code:wo.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(e){return pj||(pj=this.doPreload(e)),pj}doPreload(e){return WA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Vg(this.audioContext,a)}catch(l){this.log.error("preload audioProcessor failed. ".concat(l))}finally{URL.revokeObjectURL(a)}})}getName(){return OL.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(e){switch(e){case"start":return OL.getStartValidateRule(this.core);case"update":return OL.updateValidateRule;case"stop":return OL.stopValidateRule}}start(e){return WA(this,null,function*(){var o,a,l,d;let{room:h}=this.core,{sdkAppId:y,userId:S,userSig:k,assetsPath:V=this.core.assetsPath,audioReference:J,processLevel:cA,enableDump:CA,isLocalAudioNeedAudioProcess:MA=!0,isScreenAudioNeedAudioProcess:ie=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=MA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=ie,!V)throw new _o({code:wo.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(V,"/audioProcessor-wasm.js")),MA&&!this.localAudioWorkletNode){let{sign:pe,status:qe,timestamp:we}=yield this.getAuthData(y,S,k);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",y,S,we,pe,qe,h)}if(ie&&!this.screenAudioWorkletNode){let{sign:pe,status:qe,timestamp:we}=yield this.getAuthData(y,S,k);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",y,S,we,pe,qe,h)}this.mixNode||(this.mixNode=this.audioContext.createGain(),this.mixNode.gain.value=1),this.silentNode||(this.silentNode=this.audioContext.createConstantSource(),this.silentNode.offset.setValueAtTime(0,this.audioContext.currentTime),this.silentNode.start()),(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"enable"}),(a=this.screenAudioWorkletNode)==null||a.port.postMessage({type:"enable"}),h.audioManager.addAudioProcessor(this.mixNode,this.silentNode,this.localAudioWorkletNode,this.screenAudioWorkletNode),Ke(J)||J.forEach(pe=>{this.customAudioReferenceMap.set(pe,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:pe,refId:"o-".concat(this.audioRefId++)})}),Ke(cA)||(l=this.localAudioWorkletNode)==null||l.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:cA}}),Ke(CA)||(d=this.localAudioWorkletNode)==null||d.port.postMessage({type:"dump",data:{enable:CA}})})}update(e){return WA(this,null,function*(){var o,a,l;let{audioReference:d,enableDump:h,processLevel:y}=e;Ke(d)||(this.customAudioReferenceMap.forEach((S,k)=>{this.customAudioReferenceMap.delete(k),this.core.room.audioManager.updateAudioReference({type:"remove",refId:S})}),d.forEach(S=>{this.customAudioReferenceMap.set(S,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:S,refId:"o-".concat(this.audioRefId++)})})),Ke(y)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:y}}),Ke(h)||((a=this.localAudioWorkletNode)==null||a.port.postMessage({type:"dump",data:{enable:h}}),(l=this.screenAudioWorkletNode)==null||l.port.postMessage({type:"dump",data:{enable:h}}))})}stop(){return WA(this,null,function*(){var e,o;let{room:a}=this.core;(e=this.localAudioWorkletNode)==null||e.port.postMessage({type:"disable"}),(o=this.screenAudioWorkletNode)==null||o.port.postMessage({type:"disable"}),yield a.audioManager.removeAudioProcessor(this.localAudioWorkletNode,this.screenAudioWorkletNode)})}destroy(){this.localAudioWorkletNode&&(this.localAudioWorkletNode.port.onmessage=null),this.screenAudioWorkletNode&&(this.screenAudioWorkletNode.port.onmessage=null),this.uninstallEvent()}getAuthData(e,o,a){return WA(this,null,function*(){let l=String(Date.now()).slice(0,-3),{auth:d,sign:h,status:y,message:S}=yield function(k){return WA(this,arguments,function(V){let{sdkAppId:J,userId:cA,userSig:CA,timestamp:MA}=V;return function*(){let ie="".concat(function(Jo){let Ho=arguments.length>1&&arguments[1]!==void 0?arguments[1]:YA.MAIN;return"https://".concat(om[Ho]||dj(Jo,Ho),"/api/v1/audioAiAuth")}(J),"?sdkAppId=").concat(J,"&userId=").concat(cA,"&userSig=").concat(CA,"×tamp=").concat(MA),pe=yield fetch(ie),{data:{errCode:qe,errMsg:we,sign:Di,status:Le}}=yield pe.json();if(Le==="1")return{auth:!0,sign:Di,status:Le,message:we};let Qt=Kd(J)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Bi="Init RTCAudioProcessor failed.",Si="";switch(qe){case 1:Si="Please check your params.";break;case 2:Si="You need to buy packages. Refer to: ".concat(Qt);break;case 3:Si="Server is invalid. Please contact our engineer. ";break;case 4:Si="Your packages is not active. Refer to: ".concat(Qt);break;case 5:Si="Your packages is expired. Refer to: ".concat(Qt);break;case 6:Si="Your version is not supported."}return{auth:!1,status:Le,message:we?"".concat(Bi," Reason: ").concat(we,". ").concat(Si):"".concat(Bi,", ").concat(Si)}}()})}({sdkAppId:e,userSig:a,userId:o,timestamp:l});if(!d)throw this.log.info("audioProcessor: ".concat(o," auth result: ").concat(d,". Message: ").concat(S)),new _o({code:wo.INVALID_PARAMETER,message:S});return{sign:h,status:y,timestamp:l}})}initWorkletNode(e,o,a,l,d,h,y,S){e.port.postMessage({type:"init",data:{sdkAppId:String(a),userId:l,timestamp:d,sign:h,status:y}}),e.port.onmessage=k=>{var V;let{data:J}=k;switch(J.type){case"cost":let cA=J?.value>10?"info":"debug";return void this.log[cA]("".concat(o==="localAudio"?"":"[".concat(o,"] "),"avg cost: ").concat(J.value," max: ").concat(J?.max,"(").concat(vb(new Date(J?.maxCostTimestamp)),") hist: ").concat((V=J?.hist)==null?void 0:V.join(" ")));case"log":return void this.log[J.logLevel]("".concat(o==="localAudio"?"":"[".concat(o,"] ")).concat(J.value));case"dump":return void F.emit("265",{room:S,data:J.value,type:o==="localAudio"?"dump":"dump-screen-audio"});case"detectEcho":return void this.log.warn("".concat(o==="localAudio"?"":"[".concat(o,"] "),"detect echo: ").concat(W0()?cQ():Hp()))}}}handleLocalAudioStarted(e){return WA(this,null,function*(){var o;if(this.hitTest(e.room)&&((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)===!0)try{yield this.core.trtc.startPlugin("AudioProcessor",{sdkAppId:this.core.room.sdkAppId,userId:this.core.room.userId,userSig:this.core.room.userSig}),this.log.warn("audio processor auto start success")}catch(a){this.log.warn("audio processor auto start failed, error: ".concat(a))}})}handleLocalAudioStopped(e){return WA(this,null,function*(){var o;!this.hitTest(e.room)||((o=this.core.room.scheduleResult.config)==null?void 0:o.audioProcessor)!==!0||(yield this.core.trtc.stopPlugin("AudioProcessor"))})}installEvent(){this.core.innerEmitter.on("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.on("114",this.handleLocalAudioStopped,this)}uninstallEvent(){this.core.innerEmitter.off("104",this.handleLocalAudioStarted,this),this.core.innerEmitter.off("114",this.handleLocalAudioStopped,this)}hitTest(e){return e===this.core.room}};Y(M1,"updateValidateRule",{type:"object"}),Y(M1,"stopValidateRule",{type:"object"}),Y(M1,"Name","AudioProcessor");var ziA=M1,yj=0,ZiA=class{constructor(A,e){Y(this,"audioObjectURL"),Y(this,"player"),Y(this,"publisher"),Y(this,"mixInput"),this.mixInput=new p5(e),A.url?(this.player=new Audio(A.url),this.player.crossOrigin="anonymous",this.publisher=new Audio(A.url),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher)):this.mixInput.replaceSource(A.track),this.mixInput.connect()}updateSettings(A){this.player&&(Ke(A.volume)||(this.volume=A.volume),Ke(A.loop)||(this.loop=A.loop),Ke(A.playbackRate)||(this.playbackRate=A.playbackRate))}updateListener(A){if(this.player){if(A.onDurationChange){let{onDurationChange:e}=A;this.player.ondurationchange=o=>{e(o.target.duration)}}if(A.onTimeUpdate){let e=A.onTimeUpdate,{player:o}=this;o.ontimeupdate=()=>{e(o.currentTime,o.duration)}}A.onEnded&&(this.player.onended=A.onEnded)}}reload(A){return WA(this,null,function*(){if(A.url){let e=yield hj.download(A.url,{retries:3,type:"blob"});this.audioObjectURL&&URL.revokeObjectURL(this.audioObjectURL),this.audioObjectURL=URL.createObjectURL(e),this.player&&this.publisher?(this.player.src=this.audioObjectURL,this.publisher.src=this.audioObjectURL):(this.player=new Audio(this.audioObjectURL),this.player.crossOrigin="anonymous",this.publisher=new Audio(this.audioObjectURL),this.publisher.crossOrigin="anonymous",this.mixInput.replaceSource(this.publisher),this.updateListener(A),this.updateSettings(A))}else this.mixInput.replaceSource(A.track)})}reset(){this.seek(0),this.mixInput.connect()}seek(A){this.player&&(A<0&&A>this.player.duration||(this.player.currentTime=A,this.publisher.currentTime=A))}play(){var A,e;return Promise.all([(A=this.player)==null?void 0:A.play(),(e=this.publisher)==null?void 0:e.play()])}pause(){var A,e;(A=this.player)==null||A.pause(),(e=this.publisher)==null||e.pause()}stop(){var A;(A=this.player)==null||A.pause(),this.mixInput.disconnect()}setOperation(A){A==="pause"&&this.pause(),A==="resume"&&(this.pause(),this.play()),A==="stop"&&(this.pause(),this.seek(0))}set volume(A){!this.player||!this.publisher||(this.player.volume=A,this.publisher.volume=A)}set loop(A){!this.player||!this.publisher||(this.player.loop=A,this.publisher.loop=A)}set playbackRate(A){!this.player||!this.publisher||(this.player.playbackRate=A,this.publisher.playbackRate=A)}};function m_(A,e){if(e&&typeof e!="function")throw new _o({code:wo.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var pL=class PL{constructor(e){this.core=e,Y(this,"log"),Y(this,"mixedMusicMap",new Map),Y(this,"cacheMusicMap",new Map),yj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(yj)}),this.log.info("created id=".concat(this.getAlias()).concat(yj))}getName(){return PL.Name}getAlias(){return"ax"}getGroup(e){return e?.id}getValidateRule(e){switch(e){case"start":return PL.startValidateRule;case"update":return PL.updateValidateRule;case"stop":return PL.stopValidateRule}}start(e){return WA(this,null,function*(){let{room:o}=this.core;this.core.validateSourceNode(),this.log.info("add music source, id: ".concat(e.id," url: ").concat(e.url,", track: ").concat(e.track));let{id:a,url:l}=e;if(this.mixedMusicMap.has(a))return;let d=this.cacheMusicMap.get(a);d?e.url?d.reset():(d.mixInput.replaceSource(e.track),d.mixInput.connect()):(d=new ZiA(e,o.audioManager),this.cacheMusicMap.set(a,d)),d.updateListener(e),d.updateSettings(e);try{yield d.play()}catch(h){yield this.handleAutoPlayFailed(d,e,h)}this.mixedMusicMap.set(a,d),d.mixInput.source.node&&this.core.room.audioManager.updateAudioReference({type:"add",audioReference:d.mixInput.source.node,refId:"ax-".concat(a)}),this.log.info("start mix audio track ".concat(a," success.")),si.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,o,a){return WA(this,null,function*(){if(a.name==="NotSupportedError")this.log.error("play failed, try to reload source. error: ".concat(a)),yield e.reload(o),yield e.play();else{if(a.name!=="NotAllowedError")throw a;if(this.core.room.enableAutoPlayDialog){let l=()=>{var d;(d=e.play())==null||d.finally(()=>{F.off("154",l,this)})};F.on("154",l,this),HC()}else this.core.trtc.emit(Ki.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>WA(this,null,function*(){return e.play()})})}})}update(e){return WA(this,null,function*(){let{id:o,operation:a,seekFrom:l,playbackRate:d}=e;this.log.info("update music source, ".concat(JSON.stringify(e)));let h=this.mixedMusicMap.get(o);h?(h.updateSettings(e),h.updateListener(e),Ke(a)||h.setOperation(a),Ke(l)||h.seek(l),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(e){return WA(this,arguments,function(o){var a=this;let{id:l}=o;return function*(){if(a.mixedMusicMap.has(l)){a.log.info("remove music source, music id: ".concat(l));let d=a.mixedMusicMap.get(l);d!=null&&d.mixInput.source.node&&a.core.room.audioManager.updateAudioReference({type:"remove",audioReference:d.mixInput.source.node,refId:"ax-".concat(l)}),d?.stop(),a.mixedMusicMap.delete(l)}l==="*"&&a.destroyAllMusic()}()})}kvUpload(e){let{track:o,loop:a,volume:l,playbackRate:d,operation:h,seekFrom:y,onTimeUpdate:S,onDurationChange:k,onEnded:V}=e;o&&si.addCount({key:502009}),a&&si.addCount({key:502001}),l&&si.addCount({key:502002}),d&&si.addCount({key:502003}),h&&si.addCount({key:502004}),y&&si.addCount({key:502005}),typeof S!="function"&&si.addCount({key:502007}),typeof V!="function"&&si.addCount({key:502008}),typeof k!="function"&&si.addCount({key:502006})}destroyAllMusic(){this.log.info("destroy all music source."),this.mixedMusicMap.forEach((e,o)=>{e!=null&&e.mixInput.track&&this.core.room.audioManager.updateAudioReference({type:"remove",audioReference:e.mixInput.track,refId:o}),this.stop({id:o})})}destroyAllCache(){this.log.info("destroy all music cache."),this.cacheMusicMap.clear()}destroy(){this.log.info("destroy audio mixer plugin."),this.destroyAllMusic(),this.destroyAllCache()}};Y(pL,"startValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},url:{type:"string",required:!1},track:{required:!1},loop:{type:"boolean"},volume:{type:"number"}},validate(A,e,o){if(A.url&&A.url!=="*"){let a=A.url.split("?")[0],l=["mp3","ogg","wav","flac"],d=a.split(".").pop(),h=l.indexOf(d)>=0,y=a.startsWith("blob"),S=a.startsWith("data");if(!(h||y||S))throw new _o({code:wo.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new _o({code:wo.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});m_("onTimeUpdate",A.onTimeUpdate),m_("onEnded",A.onEnded),m_("onDurationChange",A.onDurationChange)}}),Y(pL,"updateValidateRule",{name:"options",required:!0,type:"object",properties:{id:{type:"string",required:!0},loop:{type:"boolean"},volume:{type:"number"},seekFrom:{type:"number"},operation:{type:"string",values:["pause","resume","stop"]}},validate(A,e,o){m_("onTimeUpdate",A.onTimeUpdate),m_("onEnded",A.onEnded),m_("onDurationChange",A.onDurationChange)}}),Y(pL,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Y(pL,"Name","AudioMixer");var Dj,XiA=pL,Sj=0,v1=class xL{constructor(e){this.core=e,Y(this,"log"),Y(this,"audioContext",OI()),Y(this,"workletNode"),Y(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),Sj+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Sj)}),this.log.info("created id=".concat(this.getAlias()).concat(Sj))}static startValidateRule(e){return{name:"options",required:!0,type:"object",properties:{sdkAppId:{type:"number",required:!0},userId:{type:"string",required:!0},userSig:{type:"string",required:!0},mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}},validate(o,a,l,d){if(!e.room.audioManager.hasAudioTrack)throw new _o({code:wo.INVALID_OPERATION,extraCode:5106,fnName:l})}}}preload(e){return Dj||(Dj=this.doPreload(e)),Dj}doPreload(e){return WA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Vg(this.audioContext,a)}catch(l){throw this.log.error("load worklet failed",l),l}finally{URL.revokeObjectURL(a)}})}getName(){return xL.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(e){switch(e){case"start":return xL.startValidateRule(this.core);case"update":return xL.updateValidateRule;case"stop":return xL.stopValidateRule}}start(e){return WA(this,null,function*(){let{room:o,schedule:a}=this.core,{assetsPath:l=this.core.assetsPath}=e;if(!l)throw new _o({code:wo.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});if(this.core.validateSourceNode(),yield this.preload("".concat(l,"/denoiser-wasm").concat(UM()?"":"-nosimd",".js")),!this.workletNode){let d=String(Date.now()).slice(0,-3),{auth:h,sign:y,status:S,message:k}=yield function(V,J){return WA(this,arguments,function(cA,CA){let{sdkAppId:MA,userId:ie,userSig:pe,timestamp:qe}=CA;return function*(){try{let{data:{errCode:we,errMsg:Di,sign:Le,status:Qt}}=yield cA.getAbilityConfig(MA,cA.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:MA,userId:ie,userSig:pe,timestamp:qe});if(Qt==="1")return{auth:!0,sign:Le,status:Qt,message:Di};let Bi=Kd(MA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Si="Init RTCAIDenoiser failed.",Jo="";switch(we){case 1:Jo="Please check your params.";break;case 2:Jo="You need to buy packages. Refer to: ".concat(Bi);break;case 3:Jo="Server is invalid. Please contact our engineer. ";break;case 4:Jo="Your packages is not active. Refer to: ".concat(Bi);break;case 5:Jo="Your packages is expired. Refer to: ".concat(Bi);break;case 6:Jo="Your version is not supported."}return{auth:!1,status:Qt,message:Di?"".concat(Si," Reason: ").concat(Di,". ").concat(Jo):"".concat(Si,", ").concat(Jo)}}catch(we){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(we)}}}()})}(a,po(fi({},e),{timestamp:d}));if(!h)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(h,". Message: ").concat(k)),new _o({code:wo.INVALID_PARAMETER,message:k});this.workletNode=new AudioWorkletNode(this.audioContext,"trtc-denoiser-processor",{numberOfInputs:1,numberOfOutputs:1}),this.workletNode.port.postMessage({type:"init",data:{sdkAppId:String(e.sdkAppId),userId:e.userId,timestamp:d,sign:y,status:S}}),this.workletNode.port.onmessage=V=>{var J;let{data:cA}=V;if(cA.type==="cost"){let CA=cA?.max>20?"warn":cA?.max>10?"info":"debug";this.log[CA]("avg cost: ".concat(cA.value," max: ").concat(cA?.max,"(").concat(vb(new Date(cA?.maxCostTimestamp)),") hist: ").concat((J=cA?.hist)==null?void 0:J.join(" ")))}else cA.type==="log"&&this.log[cA.logLevel]("".concat(cA.value))}}this.updateConfig(e),this.workletNode.port.postMessage({type:"enable"}),o.audioManager.addDenoiser(this.workletNode),o.sendAbilityStatus({ai_denoise:1})})}update(e){return WA(this,null,function*(){this.updateConfig(e)})}stop(){return WA(this,null,function*(){if(!this.workletNode)return;let{room:e}=this.core;this.workletNode.port.postMessage({type:"disable"}),yield e.audioManager.removeDenoiser(this.workletNode)})}updateConfig(e){if(!this.workletNode)return;let o=!1;Ke(e.mode)||(e.mode===0?this.config.enableFarFieldReduce=!1:e.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),Ke(e.farFieldReduceThreshold)||(this.config.farFieldReduceThreshold=e.farFieldReduceThreshold,o=!0),o&&this.workletNode.port.postMessage({type:"setConfig",data:this.config})}destroy(){this.workletNode&&(this.workletNode.port.onmessage=null)}};Y(v1,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Y(v1,"stopValidateRule",{type:"object"}),Y(v1,"Name","AIDenoiser");var $iA=v1,AoA=gc(jl(),1),eoA=class extends AoA.EventEmitter{constructor(){super(),Y(this,"observer"),Y(this,"state","nominal"),this.onPressureChange=this.onPressureChange.bind(this)}get stateNum(){switch(this.state){case"nominal":return 1;case"fair":return 2;case"serious":return 3;case"critical":return 4}}start(){return WA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Ha&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){sn.uploadEvent({log:"stat-pressure-detector-start-failed",error:A})}})}onPressureChange(A){let e=this.stateNum,o=A[A.length-1];this.state=o.state,(this.stateNum>3||e>3)&&pA.info("".concat(o.source,": ").concat(o.state)),this.emit("state-changed",{type:o.source,state:this.state})}destroy(){var A;try{(A=this.observer)==null||A.disconnect(),this.observer=null}catch(e){sn.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:e})}}},xz=new eoA,Mj=0,vj=class nX{constructor(e){this.core=e,Y(this,"log"),Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_subStreamSeiMessageList",[]),Mj++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(Mj)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(Mj)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:o,mediaType:a}=e;try{return Nz({frame:o,seiMessageList:a===8?this._smallSeiMessageList:a===2?this._subStreamSeiMessageList:this._seiMessageList})}catch(l){this.log.warn(l)}return o}decode(e){let{frame:o,track:a}=e;return Gz({frame:o,onSEI:l=>{l.forEach(d=>{a!=null&&a.userId?this.core.trtc.emit(Ki.SEI_MESSAGE,{seiPayloadType:d.seiPayloadType,data:d.seiPayload.buffer,userId:a.userId,streamType:a.mediaType===2?"sub":"main"}):this.core.innerEmitter.emit(this.core.INNER_EVENT.SEI_MESSAGE,{room:this.core.room,nalu:d})})}})}destroy(){this.log.debug("destroy"),this.stop(),delete this.core}getValidateRule(e){switch(e){case"start":case"update":case"stop":return{type:"object"}}}start(){this.core.room.videoManager.addEncodeProcessor({processor:zp?this.encode:Nz,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:zp?this.decode:Gz,type:2})}stop(){this.core.room.videoManager.removeEncodeProcessor({type:2}),this.core.room.videoManager.removeDecodeProcessor({type:2})}update(e){let{buffer:o,options:a}=e;var l;let d=[a.seiPayloadType,o],h=!!a.small;a.toSubStream?this._subStreamSeiMessageList.push(d):(this._seiMessageList.push(d),h&&this._smallSeiMessageList.push(d)),(l=this.core.room.scriptTransformWorker)==null||l.postMessage({type:"sei",data:d,isMain:!a.toSubStream,small:h})}getName(){return nX.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Y(vj,"autoStart",!0),Y(vj,"Name","SEI");var R1,toA=vj,ioA=0,Rj=class rX{constructor(e){this.core=e,Y(this,"_core"),Y(this,"log"),Y(this,"dialog"),this._core=e,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(++ioA)}),this.log.info("created")}getName(){return rX.Name}getAlias(){return"dm"}getGroup(){return"dm"}getValidateRule(e){switch(e){case"start":return{name:"StartDebugOptions",required:!1};case"update":return{name:"UpdateDebugOptions",required:!1};case"stop":return{name:"StopDebugOptions",required:!1}}}start(){return WA(this,null,function*(){var e;!new URLSearchParams(location.search).has("trtcDebug")&&((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_ENABLE_DEBUG_PLUGIN"))!=="true"||(yield this.openDebugDiaLog())})}update(e){return WA(this,arguments,function(o){var a=this;let{visible:l}=o;return function*(){l?yield a.openDebugDiaLog():a.closeDebugDiaLog()}()})}stop(){this.closeDebugDiaLog()}destroy(){this.stop()}openDebugDiaLog(){return WA(this,null,function*(){var e;if(!this.dialog)try{if(R1)yield R1;else{let o=new URLSearchParams(location.search).get("trtcDebugDialogPath")||((e=window.sessionStorage)==null?void 0:e.getItem("TRTC_DEBUG_DIALOG_PATH"))||"https://unpkg.com/".concat("trtc-sdk-v5","@").concat(qd,"/assets/debug-dialog.js");R1=this._core.fileDownloader.loadScript(o),yield R1}this.dialog=new TRTCDebugDialog(this._core,this.log),this._core.kvStatManager.addSuccessEvent({key:592705})}catch(o){this._core.kvStatManager.addFailedEvent({key:592705}),this.log.error("load debug dialog script failed: ",JSON.stringify(o))}})}closeDebugDiaLog(){this.dialog&&(this.dialog.closeDialog(),this.dialog=null)}};Y(Rj,"Name","Debug"),Y(Rj,"autoStart",!0);var ooA=Rj,Yz=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},Vz=class{constructor(A,e,o){Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"type","auto"),Y(this,"config"),Y(this,"decoder"),Y(this,"_decodeSink");let{kvStatManager:a,trtc:l}=A;this.config=o.config,this.trackDoneOB=la(e,Zs.INIT),this.stopOB=hQ(),this.startOB=hQ(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let d=hQ();ma(this.startOB,$K(0),g1(h=>{let y=this.pipe(e);return d.next("STARTING"),e.log.info("decoder type: ".concat(this.type)),ma(y,dE(this.stopOB),Bl(()=>{},S=>{e.log.error(S),a.addFailedEvent({key:Yz(this.type),error:S}),h>4?this.startOB.error(S):this.startOB.next(h+1)})),ma(y,E_(1),ez(tj))}),dE(this.stopOB),Bl(()=>{e.player.setOutput(),d.next("STARTED")},h=>{d.next("FAILED")},()=>{a.addSuccessEvent({key:Yz(this.type)}),a.addSuccessEvent({key:504702})}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.startOB.next(0)}close(A){this.stopOB.next(A)}pipe(A){return nL()(e=>WA(this,null,function*(){this._decodeSink=e,e.defer(()=>{var a;(a=this.decoder)==null||a.close()});let{type:o}=this;try{o==="webCodecs"&&(this.decoder=new AudioDecoder({error:a=>{A.log.error(a),e.error(4)},output:a=>{this.decodedFrameCount++,e.next(a),A.player.write(a)}})),this.decoder.configure(this.config)}catch(a){A.log.error(a),e.error(o==="webCodecs"?2:6)}}))}decodeFrame(A){var e;this.inputFrameCount++,((e=this.decoder)==null?void 0:e.state)==="configured"&&this.decoder.decode(new EncodedAudioChunk({data:A.data,timestamp:A.timestamp,type:"key"}))}},soA={type:"object"},Jz=class $3{constructor(e){this.core=e,Y(this,"log"),Y(this,"contextMap",new Map),Y(this,"decodeProcessorMap",new WeakMap),this.log=e.log.createChild({id:"".concat(this.getAlias())})}getAlias(){return $3.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return $3.Name}getValidateRule(e){return soA}start(e){let{track:o}=e;this.decodeProcessorMap.set(o,this.decode(e)),this.core.room.audioManager.addDecodeProcessor({processor:a=>{let{frame:l,track:d}=a;return this.decodeProcessorMap.has(d)?this.decodeProcessorMap.get(d)({frame:l,track:d}):l},type:3})}decode(e){return o=>{let{frame:a,track:l}=o;if(l!==e.track)return a;if(this.contextMap.has(l))return this.contextMap.get(l).decodeFrame(a);let d=new Vz(this.core,l,e);return ma(d.trackDoneOB,E_(1),Bl(()=>{this.core.clearStarted(this,this.getGroup(e)),this.stop({track:l})})),this.contextMap.set(l,d),d.decodeFrame(a)}}stop(e){let{track:o}=e,a=this.contextMap.get(o);a&&(a.close("stop"),this.contextMap.delete(o),this.contextMap.size===0&&this.core.room.audioManager.removeDecodeProcessor({type:3}))}update(e){let o=this.contextMap.get(e.track);if(o){if(e.type==="mock")return void o.mock(10);o.close("update"),this.contextMap.set(e.track,new Vz(this.core,e.track,e))}}};Y(Jz,"Name","TRTCAudioDecoder");var Hz=Jz,noA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},roA=class{constructor(){Y(this,"log"),Y(this,"autoMode",{enabled:!1,instance:null,config:noA,sortedStreamList:[],currentQualityIndex:0}),Y(this,"switchControl",{isInternal:!1,isSwitching:!1,lastSwitchTime:0,boundOnStatistics:null}),Y(this,"networkMetrics",{frameRate:0,rtt:0,loss:0}),Y(this,"counters",{rttUnder:0,lossUnder:0,downgradeCondition:0,upgradeFail:0}),Y(this,"onStatistics",A=>{var e,o;if(!this.autoMode.instance)return;let{config:a}=this.autoMode;if(this.networkMetrics.rtt=A.rtt,this.networkMetrics.loss=A.downLoss,this.counters.rttUnder=A.rttV.userId===d);if((o=y?.video)==null||!o.length)return;let S=h==="sub"?"sub":"big",k=y.video.find(V=>V.videoType===S);k?(this.networkMetrics.frameRate=k.frameRate||0,this.checkAndSwitchQuality()):this.log.warn("onStatistics: videoStat not found for userId=".concat(d,", streamType=").concat(h))}),this.log=pA.createLogger({id:"pqs"})}getCurrentPlayingStream(A){var e,o;let a=A,l=a._playbackQualityList;if(!l||l.length===0)return this.log.warn("getCurrentPlayingStream: streamList is empty"),null;for(let d of l){let h=A.room.remotePublishedUserMap.get(d.userId);if(!h)continue;let y=(e=d.streamType)!=null?e:"main";if((y==="sub"?h.remoteAuxiliaryTrack:h.remoteVideoTrack).isPlayCalled){let S=(o=a._remoteVideoConfigMap.get("".concat(d.userId,"_").concat(y)))==null?void 0:o.config;if(S)return{userId:d.userId,streamType:y,config:S}}}return null}switchPlaybackQuality(A){return WA(this,null,function*(){var e;let{trtcInstance:o,streamList:a,quality:l}=A;this.log.info("switchPlaybackQuality quality: ".concat(l,", streamList: ").concat(JSON.stringify(a)));let d=o;if(a&&a.length>0&&(d._playbackQualityList=a.map(MA=>{var ie;return po(fi({},MA),{streamType:(ie=MA.streamType)!=null?ie:"main"})})),l==="auto")return void(yield this.startAutoMode(o));if(this.autoMode.enabled&&l&&!this.switchControl.isInternal&&this.stopAutoMode(),!l)return;if(!d._playbackQualityList||d._playbackQualityList.length<=0)return void this.log.warn("switchPlaybackQuality: streamList is empty, please call with streamList first");let h=d._playbackQualityList.find(MA=>MA.name===l);if(!h)return void this.log.warn('switchPlaybackQuality: quality "'.concat(l,'" not found in streamList'));let y=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(y?.userId,", streamType: ").concat(y?.streamType)),!y)return;let S=(e=h.streamType)!=null?e:"main";if(y.userId===h.userId&&y.streamType===S)return void this.log.info("switchPlaybackQuality: already playing target stream");let k=fi({},y.config);k.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(k.userId,!0));let V,J=new Promise(MA=>{V=MA}),cA=MA=>{MA.userId===h.userId&&MA.streamType===S&&MA.state==="PLAYING"&&MA.reason==="playing"&&V("success")};o.on(Ki.VIDEO_PLAY_STATE_CHANGED,cA);let CA=new Promise(MA=>setTimeout(()=>MA("timeout"),1e4));try{if(yield o.startRemoteVideo(po(fi({},y.config),{userId:h.userId,streamType:S,option:po(fi({},y.config.option),{isLiveStream:!0})})),(yield Promise.race([J,CA]))==="timeout"){this.log.error("switchPlaybackQuality: VIDEO_PLAY_STATE_CHANGED timeout, rollback");try{yield o.stopRemoteVideo({userId:h.userId,streamType:S})}catch(ie){this.log.warn("switchPlaybackQuality: rollback stopRemoteVideo failed",ie)}throw k.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(k.userId,!1).catch(ie=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",ie)})),new gi({code:Ct.SUBSCRIPTION_TIMEOUT,message:Xo({key:vo.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:h.userId}})})}let MA=o.stopRemoteVideo(k);k.streamType==="main"&&S==="main"?yield Promise.all([o.muteRemoteAudio(h.userId,!1).catch(ie=>{this.log.warn("muteRemoteAudio(new, false) failed",ie)}),MA]):yield MA,d._currentLiveUserId=h.userId,d._currentLiveStreamType=S}finally{o.off(Ki.VIDEO_PLAY_STATE_CHANGED,cA)}})}startAutoMode(A){return WA(this,null,function*(){if(this.autoMode.enabled)return void this.log.info("auto mode already enabled");let e=A;if(!e._playbackQualityList||e._playbackQualityList.length<=1)return void this.log.warn("startAutoMode: need at least 2 streams in streamList for auto mode");this.autoMode.enabled=!0,this.autoMode.instance=A,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.switchControl.lastSwitchTime=0;let o=e._playbackQualityList||[];this.autoMode.sortedStreamList=[...o].sort((l,d)=>d.bitrate-l.bitrate),this.log.info("auto mode streams: ".concat(this.autoMode.sortedStreamList.map(l=>"".concat(l.name,"(").concat(l.bitrate,"kbps)")).join(" > ")));let a=this.getCurrentPlayingStream(A);if(a){let{userId:l,streamType:d}=a,h=this.autoMode.sortedStreamList.findIndex(y=>{var S;return y.userId===l&&((S=y.streamType)!=null?S:"main")===d});this.autoMode.currentQualityIndex=h>=0?h:0}else this.autoMode.currentQualityIndex=0;this.switchControl.boundOnStatistics=this.onStatistics,A.on(Ki.STATISTICS,this.switchControl.boundOnStatistics),this.log.info("auto mode started")})}stopAutoMode(){this.autoMode.enabled&&(this.autoMode.instance&&this.switchControl.boundOnStatistics&&this.autoMode.instance.off(Ki.STATISTICS,this.switchControl.boundOnStatistics),this.switchControl.boundOnStatistics=null,this.autoMode.enabled=!1,this.autoMode.instance=null,this.autoMode.sortedStreamList=[],this.autoMode.currentQualityIndex=0,this.counters.rttUnder=0,this.counters.lossUnder=0,this.counters.downgradeCondition=0,this.counters.upgradeFail=0,this.networkMetrics.frameRate=0,this.networkMetrics.rtt=0,this.networkMetrics.loss=0,this.switchControl.isSwitching=!1,this.log.info("auto mode stopped"))}checkAndSwitchQuality(){var A;if(!this.autoMode.enabled||!this.autoMode.instance||this.switchControl.isSwitching)return;let{config:e}=this.autoMode,o=Date.now()-this.switchControl.lastSwitchTime0,h=this.networkMetrics.frameRate<=e.fpsPoorLimit,y=this.networkMetrics.loss>=e.lossPoorLimit||this.networkMetrics.rtt>=e.rttPoorLimit,S=h&&y;this.counters.downgradeCondition=S?this.counters.downgradeCondition+1:0;let k=this.counters.rttUnder>=e.goodCount&&this.counters.lossUnder>=e.goodCount,V=this.counters.upgradeFail{if(V.remoteAudioTrack.isAvailable){if(S.get(V.userId))return;let J=y.getPCM(cA=>{e.emit(Ki.AUDIO_FRAME,cA)},V.userId);S.set(V.userId,J)}});else{if(S.get(a))return;let V=y.getPCM(J=>{e.emit(Ki.AUDIO_FRAME,J)},a);S.set(a,V)}else if(a==="*")e.room.remotePublishedUserMap.forEach(V=>{if(V.remoteAudioTrack.isSubscribed){let{userId:J}=V,cA=S.get(J);cA?.abort("disable"),S.delete(J)}});else{let V=S.get(a);V?.abort("disable"),S.delete(a)}})}resumeRemotePlayer(A){return WA(this,null,function*(){if(A.userId==="*"){let o=[];return A.trtcInstance.room.remotePublishedUserMap.forEach(a=>{let{remoteAudioTrack:l,remoteVideoTrack:d,remoteAuxiliaryTrack:h}=a;A.streamType?A.streamType==="main"?(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume())):h.isAvailable&&o.push(h.player.resume()):(l.isAvailable&&o.push(l.player.resume()),d.isAvailable&&o.push(d.player.resume()),h.isAvailable&&o.push(h.player.resume()))}),Promise.all(o)}let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);if(e)return A.streamType==="main"?Promise.all([e.remoteAudioTrack.player.resume(),e.remoteVideoTrack.player.resume()]):e.remoteAuxiliaryTrack.player.resume()})}pauseRemotePlayer(A){if(A.userId==="*")A.trtcInstance.room.remotePublishedUserMap.forEach(e=>{let{remoteAudioTrack:o,remoteVideoTrack:a,remoteAuxiliaryTrack:l}=e;A.streamType?A.streamType==="main"?(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1)):l.isAvailable&&l.player.pause(!1):(o.isAvailable&&o.player.pause(),a.isAvailable&&a.player.pause(!1),l.isAvailable&&l.player.pause(!1))});else{let e=A.trtcInstance.room.remotePublishedUserMap.get(A.userId);e&&(A.streamType==="main"?(e.remoteAudioTrack.player.pause(),e.remoteVideoTrack.player.pause(!1)):e.remoteAuxiliaryTrack.player.pause(!1))}}requestPictureInPicture(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterPictureInPicture():e.remoteVideoTrack.player.exitPictureInPicture():Promise.reject(new gi({code:Ct.INVALID_OPERATION,message:"no available remote video"}))}requestFullScreen(A){let e=[...A.trtcInstance.room.remotePublishedUserMap.values()].find(o=>o.remoteVideoTrack.isAvailable);return e?A.enable?e.remoteVideoTrack.player.enterFullscreen():e.remoteVideoTrack.player.exitFullscreen():Promise.reject(new gi({code:Ct.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return WA(this,null,function*(){let e=A.trtcInstance;return e._playbackQualitySwitcher||(e._playbackQualitySwitcher=new roA),e._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return WA(this,null,function*(){let{trtcInstance:e}=A;return A.enable?e.room.prelink(A.sdkAppId,A.userId,A.userSig,fL.frameWorkType,A.roomId,A.strRoomId):e.room.closePrelink()})}};hi([cz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!0,type:"string"},sampleRate:{type:"number",values:[8e3,16e3,32e3,44100,48e3]},channelCount:{type:"number",values:[1,2]},port:{type:"messageport"}}})],wj.prototype,"enableAudioFrameEvent"),hi([cz({name:"options",type:"object",required:!0,properties:{enable:{required:!0,type:"boolean"},userId:{required:!1,type:"string"},sdkAppId:{required:!1,type:"number"},userSig:{required:!1,type:"string"},roomId:{required:!1,type:"number"},strRoomId:{required:!1,type:"string"}}})],wj.prototype,"prelink");var aoA=new wj,goA=gc(jl(),1),coA=class extends goA.EventEmitter{constructor(){super(),Y(this,"states",{}),Y(this,"permissionChangeHandler"),Y(this,"log"),this.log=pA.createLogger({id:"pm"}),this.permissionChangeHandler=()=>{var A,e;this.emit("permission-state-change",{camera:(A=this.states.camera)==null?void 0:A.state,microphone:(e=this.states.microphone)==null?void 0:e.state})}}request(A){return WA(this,null,function*(){if(this.log.info("request ".concat(A.join(", "))),A.length===0)return Promise.resolve();(yield navigator.mediaDevices.getUserMedia({video:A.includes("camera"),audio:A.includes("microphone")})).getTracks().forEach(e=>e.stop())})}get(A){return WA(this,null,function*(){try{return this.states[A]||(this.states[A]=yield navigator.permissions.query({name:A}),this.states[A].addEventListener("change",this.permissionChangeHandler)),this.log.info("get ".concat(A," permission state: ").concat(this.states[A].state)),this.states[A].state}catch(e){return this.log.error("get ".concat(A," permission failed, error: ").concat(e instanceof Error?e.message:e)),null}})}destroy(){Object.values(this.states).forEach(A=>{A?.removeEventListener("change",this.permissionChangeHandler)}),this.states={}}},w1=new coA,qz=0,mL=new Set,Xl=null;Yx(Oz),zA.checkStorage();var Ms=class gm extends BK.EventEmitter{constructor(e,o){super(),Y(this,"_room"),Y(this,"_eventListened",new Set),Y(this,"_localVideoTrack",null),Y(this,"_localAudioTrack",null),Y(this,"_localScreenTrack",null),Y(this,"_localScreenAudioTrack",null),Y(this,"_localVideoConfig",null),Y(this,"_localScreenConfig",null),Y(this,"_localAudioConfig",null),Y(this,"_remoteVideoConfigMap",new Map),Y(this,"_remoteAudioConfigMap",new Map),Y(this,"_remoteAudioVolumeMap",new Map),Y(this,"_remoteAudioMuteMap",new Map),Y(this,"_mediaTrackMap",new WeakMap),Y(this,"_log",pA.createLogger({id:"t".concat(++qz)})),Y(this,"_plugins",new Map),Y(this,"_networkQuality",null),Y(this,"_speakerId"),Y(this,"enterRoomParams"),Y(this,"_enableAutoSwitchWhenRecapturing",!0),Y(this,"_autoSubscribeDataChannel",!1),Y(this,"_playbackQualityList",[]),this._room=new e(fi({logger:this._log,frameWorkType:gm.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,Nr(o.enableAutoSwitchWhenRecapturing)&&(this._enableAutoSwitchWhenRecapturing=o.enableAutoSwitchWhenRecapturing),this._log.info("create() ".concat(JSON.stringify(o,(a,l)=>a==="plugins"?l.map(d=>d.Name):l))),Object.defineProperties(this,{dumpAudio:{enumerable:!1,value(a){return this._room.audioManager.dump(a)}}}),o.plugins&&o.plugins.forEach(a=>{this._use(a,o.assetsPath)}),this._use(XiA,o.assetsPath),this._use(ziA,o.assetsPath),this._use($iA,o.assetsPath),this._use(Hz,o.assetsPath),this._use(ooA),o.enableSEI&&Kk&&this._use(toA),this._room.on("audio-volume",a=>{var l,d;!a.find(h=>h.userId==="")&&this._localAudioTrack&&a.push({userId:"",volume:Math.floor(100*((l=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?l:this._localAudioTrack.getAudioLevel())),floatVolume:(d=this._localAudioTrack.getInternalAudioLevelAfter3A())!=null?d:this._localAudioTrack.getInternalAudioLevel()}),o.volumeType===1&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),o.enableDbVolume&&a.forEach(h=>{var y;let S=h.userId===""?this._localAudioTrack:(y=this.room.remotePublishedUserMap.get(h.userId))==null?void 0:y.remoteAudioTrack;S&&(h.volume=S.dbVolume)}),this.emit(Ki.AUDIO_VOLUME,{result:a.sort((h,y)=>y.volume-h.volume)})}),this._room.videoManager.on("error",a=>{this._log.error(new _o({code:wo.OPERATION_FAILED,extraCode:5504,message:a.message,originError:a}))}),this._listenEvents(),this._initActiveSpeaker(),((a,l)=>{let{emit:d}=a;a.emit=function(){for(var h=arguments.length,y=new Array(h),S=0;S{y&&QA.info(UC)})}})();let a=new nm(e,o||{});return dL.add(a),a.__v_skip=!0,a}get room(){return this._room}_listenEvents(){rd(this,this._room).add("peer-join",e=>{let{userId:o}=e;this.emit(Hi.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",e=>{let{userId:o,reason:a}=e;this.emit(Hi.REMOTE_USER_EXIT,{userId:o,reason:a})}).add("banned",e=>{hQ(!0),this._exitRoom().finally(()=>{this.emit(Hi.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Hi.ERROR,wo.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Hi.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let o=Qo(mi({},e),{uplinkRTT:Math.min(e.uplinkRTT,E0),downlinkRTT:Math.min(e.downlinkRTT,E0)});this.emit(Hi.NETWORK_QUALITY,o)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{rd(o,o).add("player-state-changed",a=>{let c=Qo(mi({},a),{userId:e.userId});o.kind===YA.VIDEO&&(c.streamType=eC(o.streamType)),this.emit(o.kind===YA.AUDIO?Hi.AUDIO_PLAY_STATE_CHANGED:Hi.VIDEO_PLAY_STATE_CHANGED,c)}).add("error",a=>{a.getCode()===dt.PLAY_NOT_ALLOWED&&this.emit(Hi.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{kn(o)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:o,muteState:a}=e,{userId:c}=a,d=o.audioAvailable,C=o.videoAvailable,{audioAvailable:y,videoAvailable:S}=a;y||this._remoteAudioConfigMap.delete(c),S||this._removeRemoteVideoConfig(c,"main"),a.hasAuxiliary||this._removeRemoteVideoConfig(c,"sub"),C!==S&&(S?this._onVideoAvailable({userId:c,streamType:"main"}):this._onVideoUnavailable({userId:c,streamType:"main"}),this.emit(S?Hi.REMOTE_VIDEO_AVAILABLE:Hi.REMOTE_VIDEO_UNAVAILABLE,{userId:c,streamType:"main"})),d!==y&&(y?this._onAudioAvailable({userId:c}):this._onAudioUnavailable({userId:c,muteState:a}),this.emit(y?Hi.REMOTE_AUDIO_AVAILABLE:Hi.REMOTE_AUDIO_UNAVAILABLE,{userId:c})),o.hasAuxiliary!==a.hasAuxiliary&&(a.hasAuxiliary?this._onVideoAvailable({userId:c,streamType:"sub"}):this._onVideoUnavailable({userId:c,streamType:"sub"}),this.emit(a.hasAuxiliary?Hi.REMOTE_VIDEO_AVAILABLE:Hi.REMOTE_VIDEO_UNAVAILABLE,{userId:c,streamType:"sub"})),o.hasDatachannel!==a.hasDatachannel&&a.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(Hi.SEI_MESSAGE,Qo(mi({},e),{streamType:eC(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Hi.ERROR,new wo({code:Ro.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,a,c,d,C,y,S;let k={2:"big",3:"small",7:"sub"},V={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((c=this._networkQuality)==null?void 0:c.downlinkRTT)||0,E0),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((C=this._networkQuality)==null?void 0:C.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((y=e.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((S=e.msg_up_stream_info.msg_audio_status)==null?void 0:S.uint32_audio_level)||0)/od},video:e.msg_up_stream_info.msg_video_status.filter(J=>k[J.uint32_video_stream_type]).map(J=>({bitrate:(J.uint32_video_codec_bitrate||0)/1e3,width:J.uint32_video_width,height:J.uint32_video_height,frameRate:J.uint32_video_enc_fps,videoType:k[J.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(J=>({userId:J.msg_user_info.str_identifier,audio:{bitrate:(J.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(J.msg_audio_status.uint32_audio_level||0)/od,point2pointDelay:(J.msg_audio_status.uint32_audio_p2p_delay||0)+(J.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:J.msg_audio_status.uint32_audio_cache_ms||0},video:J.msg_video_status.map(gA=>({bitrate:(gA.uint32_video_codec_bitrate||0)/1e3,width:gA.uint32_video_width,height:gA.uint32_video_height,frameRate:gA.uint32_video_dec_fps,videoType:k[gA.uint32_video_stream_type],point2pointDelay:(gA.uint32_video_p2p_delay||0)+(gA.uint32_video_cache_ms||0),jitterBufferDelay:gA.uint32_video_cache_ms||0,codec:gA.uint32_video_codec}))}))};this.emit(Hi.STATISTICS,V)}).add("custom-message",e=>{this.emit(Hi.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Hi.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Hi.FIRST_VIDEO_FRAME,Qo(mi({},e),{streamType:eC(e.streamType)}))}).add("audio-frame",e=>{this.emit(Hi.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,a,c,d,C;let{data:y}=e;if(y.sender==="")return;let S={segmentId:(o=y.payload)==null?void 0:o.roundid,speakerUserId:y.sender,sourceText:(a=y.payload)==null?void 0:a.text,translationTexts:(c=y.payload)==null?void 0:c.translate_msg,timestamp:(d=y.payload)==null?void 0:d.start_utc_ms,isCompleted:(C=y.payload)==null?void 0:C.end,robotId:y.robotid};S.sourceText!==""&&this.emit(Hi.REALTIME_TRANSCRIBER_MESSAGE,S)}).add("asr-robot-peer-join",e=>{this.emit(Hi.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(Hi.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),rd(this,Pc).add("audioInputAdded",e=>{this.emit(Hi.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Hi.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Hi.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Hi.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>KA(this,null,function*(){if(this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Zl&&Zl.deviceId===u0){let o=(yield YM()).find(a=>a.deviceId===u0);o&&Zl.groupId!==o.groupId&&(Zl=o,this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",e=>KA(this,null,function*(){this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let o=(yield YM())[0];if(!o||!Zl||Zl.groupId===o.groupId)return;let a=Zl.deviceId===e.deviceId,c=Zl.deviceId===u0&&Zl.deviceId===o.deviceId;(a||c)&&(Zl=o,this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),rd(this,Q1).add("permission-state-change",e=>{this.emit(Hi.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Hi.SEI_MESSAGE,e=>{var o;let a=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;a&&a.updateAlphaRenderInfo(e)})}getNetworkTime(){return Lf()}use(e){let o,a;return"plugin"in e?(o=e.plugin,a=e.assetsPath):o=e,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,a)}_use(e,o){let a=this._plugins.get(e.Name);if(a)return this._log.warn("duplicate install plugin",e.Name),a;let c=new e(QiA.call(this,{TRTC:nm,room:this._room,assetsPath:o,errorModule:{RtcError:wo,ErrorCode:Ro,CoreErrorCode:dt,ErrorCodeDictionary:r1}}));return this._plugins.set(e.Name,c),c.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),c}enterRoom(e){return KA(this,null,function*(){var o,a;this.enterRoomParams=e;let{scene:c="rtc",enableAutoPlayDialog:d=!0,autoReceiveAudio:C=!0,autoReceiveVideo:y=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Yn(e.proxy)&&e.proxy.turnServer&&((a=(o=this._room).setTurnServer)==null||a.call(o,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=d,this._room.autoReceiveAudio=C,this._room.autoReceiveVideo=y,Nr(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let S={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(S,c,nm.frameWorkType),this._checkTrackToPublish(),Bz.start()})}exitRoom(){return KA(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return KA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(o){if(!(o instanceof Mx)||o.code!==dt.API_CALL_TIMEOUT&&o.code!==dt.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===dt.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return KA(this,null,function*(){yield this.exitRoom();let o=mi(mi({},this.enterRoomParams),e);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let o=e.includes("main")?"main":"sub",a=e.split("_".concat(o))[0];a&&this._stopRemoteVideo({userId:a,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(e){let o=h_.get(e);o&&(o.forEach(a=>clearTimeout(a)),h_.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{kn(e.remoteAudioTrack),kn(e.remoteVideoTrack),kn(e.remoteAuxiliaryTrack)})}switchRole(e,o){return KA(this,null,function*(){o!=null&&o.privateMapKey&&(this._room.privateMapKey=o.privateMapKey),o!=null&&o.latencyLevel&&(this._room.latencyLevel=o.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var o;return(o=e.destroy)==null?void 0:o.call(e)}),this._plugins.clear(),kn(this),this.removeAllListeners(),this._room.destroy(),dL.delete(this),dL.size===0&&Bz.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return KA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:a=!0,mute:c,muteKeepVolumeDetection:d,option:C}=o,y=new HM(e._room.audioManager),S={},k={muted:!0};C&&(Je(C.microphoneId)?Je(C.audioTrack)||(S.customSource=C.audioTrack):S.deviceId=C.microphoneId,C&&bn(C.captureVolume)&&y.setCaptureVolume(C.captureVolume),Je(C.profile)||(Yn(C.profile)?Sp[C.profile]&&y.setProfile(Sp[C.profile]):y.setProfile(C.profile)),bn(C.earMonitorVolume)&&(k.muted=!(C.earMonitorVolume>0),k.volume=C.earMonitorVolume),Je(C.echoCancellation)||(y.profile.echoCancellation=C.echoCancellation),Je(C.noiseSuppression)||(y.profile.noiseSuppression=C.noiseSuppression),Je(C.autoGainControl)||(y.profile.autoGainControl=C.autoGainControl),Nr(e._enableAutoSwitchWhenRecapturing)&&(y.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),y.on("5",V=>{e.emit(Hi.ERROR,new wo({code:Ro.DEVICE_ERROR,extraCode:5309,messageParams:{error:V}}))}),y.on("2",V=>{e.emit(Hi.DEVICE_CHANGED,{type:"microphone",action:"active",device:V})}),y.on("4",V=>{let J;V.error&&(J=wo.convertFrom(V.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Qo(mi({},V),{error:J}))}),y.on("6",()=>{}),e._listenOutputTrackChanged(y),e._speakerId&&y.setAudioOutput(e._speakerId),yield y.capture(S),Je(c)||y.setMute(c,d),rd(y,y).add("player-state-changed",V=>{e.emit(Hi.AUDIO_PLAY_STATE_CHANGED,Qo(mi({},V),{userId:""}))}),a&&e._room.isJoined&&e._room.publish(y).catch(()=>{}),e._localAudioTrack=y,e._room.capturedLocalMainAudioTrack=y,e._localAudioConfig=Qo(mi({},o),{publish:a}),yield e._updateAudioPlayOption({playOption:k,track:y}),F.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return KA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:a,muteKeepVolumeDetection:c,option:d}=e,C={};d&&(d.microphoneId?yield this._localAudioTrack.switchDevice(d.microphoneId):Je(d.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(d.audioTrack)),Je(d.captureVolume)||this._localAudioTrack.setCaptureVolume(d.captureVolume),Je(d.earMonitorVolume)||(C.muted=!(d.earMonitorVolume>0),C.volume=d.earMonitorVolume),yield this._localAudioTrack.update3A(d)),this._room.isJoined&&!Je(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),Je(a)||this._localAudioTrack.setMute(a,c),yield this._updateAudioPlayOption({playOption:C,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Wh(this._localAudioConfig,e)})}stopLocalAudio(){return KA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),F.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),kn(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return KA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var a,c,d;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:C,publish:y=!0,capture:S=!0,mute:k,option:V,forcePublish:J=!1}=o,gA=y||J,CA=S,MA=new dQ(e._room.videoManager),$A={},Be={};if(V&&(Nr(V.avoidCropping)&&(MA.avoidCropping=V.avoidCropping),V.cameraId?$A.deviceId=V.cameraId:Je(V.useFrontCamera)?Je(V.videoTrack)||($A.customSource=V.videoTrack):$A.facingMode=V.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT,Je(V.retryWhenExactFailed)||($A.retryWhenExactFailed=V.retryWhenExactFailed),V.qosPreference&&($A.contentHint=a1(V.qosPreference)),Je(V.profile)||(Yn(V.profile)?kC[V.profile]&&MA.setProfile(kC[V.profile]):MA.setProfile(V.profile)),Je(V.fillMode)||(Be.objectFit=V.fillMode),Je(V.mirror)||(Be.mirror=V.mirror),Je(V.small)||(Je(V.smallMode)||(e._room.smallMode=V.smallMode),Nr(V.small)&&V.small===!1?MA.stopSmall():MA.updateSmallConfig(g1(V.small,!0))),Je(V.rotation)||MA.setRotation(V.rotation),Nr(e._enableAutoSwitchWhenRecapturing)&&(MA.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),MA.once("first-video-frame",Ye=>{e.emit(Hi.FIRST_VIDEO_FRAME,Qo(mi({},Ye),{streamType:eC(Ye.streamType)}))}),MA.on("5",Ye=>{e.emit(Hi.ERROR,new wo({code:Ro.DEVICE_ERROR,extraCode:5308,messageParams:{error:Ye}}))}),MA.on("2",Ye=>{e.emit(Hi.DEVICE_CHANGED,{type:"camera",action:"active",device:Ye})}),MA.on("4",Ye=>{let ve;Ye.error&&(ve=wo.convertFrom(Ye.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Qo(mi({},Ye),{error:ve}))}),MA.on("6",()=>{}),e._listenOutputTrackChanged(MA),$A.customSource&&_p($A.customSource)?(MA.setOutputMediaStreamTrack($A.customSource),CA=!1):CA?yield MA.capture($A):(a=MA.manager)==null||a.changeInput(MA),Je(k)||(yield MA.setMute(k)),rd(MA,MA).add("player-state-changed",Ye=>{e.emit(Hi.VIDEO_PLAY_STATE_CHANGED,Qo(mi({},Ye),{userId:"",streamType:"main"}))}).add("video-size-changed",Ye=>{e.emit(Hi.VIDEO_SIZE_CHANGED,Qo(mi({},Ye),{streamType:eC(Ye.streamType)}))}),gA){let Ye=e._localScreenTrack&&((c=e._localScreenConfig)==null?void 0:c.publish)&&e._localScreenConfig.streamType==="main";e._room.isJoined?!Ye||J?(e._room.publish(MA).catch(()=>{}),((d=e._localScreenConfig)==null?void 0:d.streamType)==="main"&&e._localScreenConfig&&(e._localScreenConfig.publish=!1)):(gA=!1,e._log.warn("main stream is already published, local video track will not publish")):Ye&&(gA=!1)}e._localVideoTrack=MA,e._room.capturedLocalMainVideoTrack=MA,e._localVideoConfig=Qo(mi({},o),{view:C,publish:gA,capture:CA}),yield e._updateVideoPlayOption({view:C,playOption:Be,track:MA})}()})}updateLocalVideo(e){return KA(this,null,function*(){var o,a,c,d,C,y,S;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:k,publish:V=!0,mute:J,capture:gA,option:CA,forcePublish:MA=!1}=e,$A=V||MA,Be=gA,Ye={};if(!this._localVideoConfig.capture&&_p((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(CA!=null&&CA.cameraId||CA!=null&&CA.videoTrack)&&this._localVideoTrack.outMediaTrack!==CA?.videoTrack&&(Be=!0),this._localVideoConfig.capture)Be!==!1?CA!=null&&CA.cameraId?yield this._localVideoTrack.switchDevice(CA?.cameraId):Je(CA?.useFrontCamera)?Je(CA?.videoTrack)||(_p(CA?.videoTrack)?CA?.videoTrack!==((a=this.localVideoTrack)==null?void 0:a.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(CA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(CA?.videoTrack)):yield this._localVideoTrack.switchDevice(CA!=null&&CA.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(Be){let ve={};ve.deviceId=CA?.cameraId||((c=this._localVideoConfig.option)==null?void 0:c.cameraId),ve.facingMode=CA!=null&&CA.useFrontCamera||(d=this._localVideoConfig.option)!=null&&d.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT,ve.customSource=CA!=null&&CA.videoTrack||!ve.deviceId?(C=this._localVideoConfig.option)==null?void 0:C.videoTrack:void 0,yield this._localVideoTrack.capture(ve)}CA&&(Je(CA.profile)||(Yn(CA.profile)?kC[CA.profile]&&this._localVideoTrack.setProfile(kC[CA.profile]):this._localVideoTrack.setProfile(CA.profile),(!CA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(CA.cameraId||CA.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),Je(CA.fillMode)||(Ye.objectFit=CA.fillMode),Je(CA.mirror)||(Ye.mirror=CA.mirror),Je(CA.rotation)||this._localVideoTrack.setRotation(CA.rotation),CA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(a1(CA.qosPreference)),Je(CA.small)||(Nr(CA.small)&&!CA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(g1(CA.small,!0)))),this._room.isJoined&&Je($A)&&this._localVideoConfig.publish&&Be&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&(($A??this._localVideoConfig.publish)||MA?this._localScreenTrack&&((y=this._localScreenConfig)!=null&&y.publish)&&this._localScreenConfig.streamType==="main"&&!MA?($A=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((S=this._localScreenConfig)==null?void 0:S.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),Je(J)||(yield this._localVideoTrack.setMute(J)),yield this._updateVideoPlayOption({view:k,playOption:Ye,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Wh(this._localVideoConfig,Qo(mi({},e),{publish:$A,capture:Be}))})}stopLocalVideo(){return KA(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&(e=this._localVideoConfig)!=null&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),kn(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return KA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var a,c,d;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:C=null,publish:y=!0,muteSystemAudio:S,option:k}=o,V=y,J=new qM(e._room.videoManager);J.on("4",Be=>{let Ye;Be.error&&(Ye=wo.convertFrom(Be.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Qo(mi({},Be),{error:Ye}))}),J.once("first-video-frame",Be=>{e.emit(Hi.FIRST_VIDEO_FRAME,Qo(mi({},Be),{streamType:eC(Be.streamType)}))}),e._listenOutputTrackChanged(J),o.streamType==="main"&&(J.mediaType=4);let gA=null,CA={},MA={};k&&(Je(k.profile)||(Yn(k.profile)?Sb[k.profile]&&J.setProfile(Sb[k.profile]):J.setProfile(k.profile)),k.systemAudio&&(CA.systemAudio=!0,CA.echoCancellation=k.echoCancellation,CA.noiseSuppression=k.noiseSuppression,CA.autoGainControl=k.autoGainControl),Je(k.fillMode)||(MA.objectFit=k.fillMode),k.videoTrack&&(CA.videoTrack=k.videoTrack),k.audioTrack&&(CA.audioTrack=k.audioTrack),k.captureElement&&(CA.captureElement=k.captureElement),k.preferDisplaySurface&&(CA.preferDisplaySurface=k.preferDisplaySurface),k.qosPreference&&(CA.contentHint=a1(k.qosPreference)));let $A=yield J.capture(CA);if(J.mediaTrack.addEventListener(YA.ENDED,()=>{e._stopScreenShare(),e.emit(Hi.SCREEN_SHARE_STOPPED)}),$A.getAudioTracks()[0]){gA=new ZK(e._room.audioManager);let Be=$A.getAudioTracks()[0];(a=o.option)!=null&&a.systemAudio&&!((c=o.option)!=null&&c.audioTrack)&&(gA.sourceTrack=Be),yield gA.setInputMediaStreamTrack(Be),Nr(S)&&gA.mediaTrack&&(gA.mediaTrack.enabled=!S),e._speakerId&&gA.setAudioOutput(e._speakerId)}if(rd(J,J).add("player-state-changed",Be=>{e.emit(Hi.VIDEO_PLAY_STATE_CHANGED,Qo(mi({},Be),{userId:"",streamType:"sub"}))}),V){let Be=e._localVideoTrack&&((d=e._localVideoConfig)==null?void 0:d.publish),Ye=!(o.streamType==="main"&&Be);e._room.isJoined?(Ye?e._room.publish(J).catch(()=>{}):(V=!1,e._log.warn("main stream is already published, screen share main will not publish")),gA&&(e._checkScreenAudioEchoCancellation(J,gA),e._room.publish(gA).catch(()=>{}))):Ye||(V=!1)}e._localScreenTrack=J,e._room.capturedLocalAuxVideoTrack=J,e._localScreenAudioTrack=gA,e._localScreenConfig=Qo(mi({},o),{view:C,publish:V}),yield e._updateVideoPlayOption({view:C,playOption:MA,track:J})}()})}updateScreenShare(e){return KA(this,null,function*(){var o,a;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:c,publish:d,muteSystemAudio:C,option:y}=e,S=d,k={};if(y){if(Je(y.fillMode)||(k.objectFit=y.fillMode),y.qosPreference){let V=a1(y.qosPreference);this._localScreenTrack.setContentHint(V)}y.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(y.videoTrack),y.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(y.audioTrack)}if(this._room.isJoined&&!Je(S)){if(S&&!this._localScreenConfig.publish){let V=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&V?(S=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!S){let V=[this._localScreenTrack];this._localScreenAudioTrack&&V.push(this._localScreenAudioTrack),V.forEach(J=>this._room.unpublish(J).catch(()=>{}))}}(a=this._localScreenAudioTrack)!=null&&a.mediaTrack&&Nr(C)&&(this._localScreenAudioTrack.mediaTrack.enabled=!C),yield this._updateVideoPlayOption({view:c,playOption:k,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Wh(this._localScreenConfig,Qo(mi({},e),{publish:S}))})}stopScreenShare(){return KA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return KA(this,null,function*(){let{view:o,userId:a,streamType:c,option:d}=e,C="".concat(a,"_").concat(c);if(this._remoteVideoConfigMap.has(C))return void this._log.warn("remote video has already started. userId:".concat(a,", streamType:").concat(c));let y=this._room.remotePublishedUserMap.get(a);if(!y)return;let S={},k=c==="main"?y.remoteVideoTrack:y.remoteAuxiliaryTrack,V=this._bindRemoteVideoTrackEvents(k);this._listenOutputTrackChanged(k),d&&(Je(d.fillMode)||(S.objectFit=d.fillMode),Je(d.mirror)||(S.mirror=d.mirror),Je(d.poster)||(S.poster=d.poster),S.canvasRender=d.canvasRender,c==="main"&&!Je(d.small)&&(!y.remoteVideoTrack.isSubscribing&&!y.remoteVideoTrack.isSubscribed&&y.remoteVideoTrack.setMediaType(d.small?8:4),this._room.changeType(d.small,k.user)),Je(d.draggable)||k.setDraggable(d.draggable)),S.isLiveStream=!!this._playbackQualityList.find(J=>J.userId===a&&J.streamType===c),yield this._room.subscribe(k),yield this._enableVideoDecodeFallback(k,c),yield this._updateVideoPlayOption({view:o,playOption:S,track:k}),this._emitTrackEvent(k),this._remoteVideoConfigMap.set(C,{config:e,handlers:V}),d&&!Je(d.receiveWhenViewVisible)&&this._observeView({remoteTrack:k,view:o,receiveWhenViewVisible:d.receiveWhenViewVisible,viewRoot:d?.viewRoot})})}updateRemoteVideo(e){return KA(this,null,function*(){var o,a;let{view:c,userId:d,streamType:C,option:y,mute:S}=e,k="".concat(d,"_").concat(C),V=this._remoteVideoConfigMap.get(k);if(!V||!this._room.remotePublishedUserMap.has(d))return;let J={};y&&(Je(y.fillMode)||(J.objectFit=y.fillMode),Je(y.mirror)||(J.mirror=y.mirror));let gA=null,CA=this._room.remotePublishedUserMap.get(d);if(C==="main"&&CA!=null&&CA.muteState.hasVideo&&(gA=CA.remoteVideoTrack),C==="sub"&&CA!=null&&CA.muteState.hasAuxiliary&&(gA=CA.remoteAuxiliaryTrack),!gA)return;let{config:MA}=V;C==="main"&&y&&!Je(y.small)&&this._room.changeType(y.small,gA.user),y&&!Je(y.draggable)&&gA.setDraggable(y.draggable),y&&(Nr(y.pictureInPicture)&&(y.pictureInPicture?yield gA.player.enterPictureInPicture():yield gA.player.exitPictureInPicture()),Nr(y.fullScreen)&&(y.fullScreen?yield gA.player.enterFullscreen():yield gA.player.exitFullscreen())),Nr(S)&&(gA.ignoreUpdatePlayingState=!0,S?(yield gA.player.pause(),yield this.room.unsubscribe(gA)):(yield this.room.subscribe(gA),yield gA.player.resume(!0))),yield this._updateVideoPlayOption({view:c,playOption:J,track:gA,prevConfig:MA}),Wh(MA,e);let $A=Je(y?.receiveWhenViewVisible)?(o=MA.option)==null?void 0:o.receiveWhenViewVisible:y.receiveWhenViewVisible,Be=Je(c)?MA.view:c,Ye=Je(y?.viewRoot)?(a=MA.option)==null?void 0:a.viewRoot:y.viewRoot;this._observeView({remoteTrack:gA,view:Be,receiveWhenViewVisible:$A,viewRoot:Ye})})}stopRemoteVideo(e){return KA(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return KA(this,null,function*(){let a=[],c=this._room.remotePublishedUserMap.get(e.userId);if(c){let{muteState:d,remoteVideoTrack:C,remoteAuxiliaryTrack:y}=c;e.streamType==="main"&&(C.stop(),d.hasVideo&&a.push(C)),e.streamType==="sub"&&(y.stop(),d.hasAuxiliary&&a.push(y))}for(let d of a)o&&(delete d.ignoreUpdatePlayingState,yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,o){let a="".concat(e,"_").concat(o),c=this._remoteVideoConfigMap.get(a);if(c&&(c.observer&&c.observer.disconnect(),c.handlers)){let d=this._room.remotePublishedUserMap.get(e);if(d){let C=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(C,c.handlers)}}this._remoteVideoConfigMap.delete(a)}_bindRemoteVideoTrackEvents(e){let o={onEnterPIP:()=>KA(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Hi.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Hi.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Hi.FULL_SCREEN_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Hi.FULL_SCREEN_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Hi.ERROR,new wo({code:Ro.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:a=>{this.emit(Hi.VIDEO_SIZE_CHANGED,Qo(mi({},a),{streamType:eC(a.streamType)}))}};return e.player.on(fo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.on(fo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.on(fo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.on(fo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.on("decode-failed",o.onDecodeFailed),e.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(e,o){e.player.off(fo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.off(fo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.off(fo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.off(fo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.off("decode-failed",o.onDecodeFailed),e.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(e,o){return KA(this,null,function*(){this._remoteAudioMuteMap.set(e,o);try{if(e==="*")if(o)yield this._stopRemoteAudio({userId:e});else{let a=[...this._room.remotePublishedUserMap.values()];for(let c of a)c.muteState.hasAudio&&!this._remoteAudioConfigMap.has(c.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:c.userId}))}else o?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(a){throw a.code!==Ro.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),a}})}setRemoteAudioVolume(e,o){if(e==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((c,d)=>this._remoteAudioVolumeMap.set(d,o));let a=[...this._room.remotePublishedUserMap.values()];for(let c of a)this._remoteAudioVolumeMap.set(c.userId,o),c.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:c.remoteAudioTrack})}else if(e){let a=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,o),a&&a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}}startPlugin(e,o){return KA(this,null,function*(){return e.start(o)})}updatePlugin(e,o){return KA(this,null,function*(){return e.update(o)})}stopPlugin(e,o){return KA(this,null,function*(){return e.stop(o)})}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(e,o)}on(e,o,a){if(this.listeners(e).includes(o))return this;if(this._log.debug("on",e),super.on(e,o,a),this._eventListened.add(e),this.listeners(Hi.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:c}=this.room.audioManager;c.get("")||c.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),c=1;c{d?.abort("off")}),c.clear()}return this}getAudioTrack(){let e,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},a=null,c="main",d=!1;if(Yn(o)?e=o:(e=o.userId,d=o.processed===!0,o.streamType&&(c=o.streamType)),e){let C=this._room.remotePublishedUserMap.get(e);C&&(a=C.remoteAudioTrack)}else a=c==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return a?d&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:a="main",processed:c=!1}=e,d=null;if(o==="")a==="main"&&this._localVideoTrack&&(d=this._localVideoTrack),a==="sub"&&this._localScreenTrack&&(d=this._localScreenTrack);else{let C=this._room.remotePublishedUserMap.get(o);C&&(d=a==="main"?C.remoteVideoTrack:C.remoteAuxiliaryTrack)}return d?c&&d.outMediaTrack&&d.outMediaTrack!==d.mediaTrack?d.outMediaTrack.clone():d.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:a="main"}=e;if(o){let c=this._room.remotePublishedUserMap.get(o);if(a==="main"&&c!=null&&c.muteState.hasVideo)return c.remoteVideoTrack.getVideoFrame();if(a==="sub"&&c!=null&&c.muteState.hasAuxiliary)return c.remoteAuxiliaryTrack.getVideoFrame()}else{if(a==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(a==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var o,a;this._speakerId=e,(o=this._localAudioTrack)==null||o.setAudioOutput(e),(a=this._localScreenAudioTrack)==null||a.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(c=>c.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return KA(this,null,function*(){(yield YM()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Zl=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: '.concat(qh,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return KA(this,null,function*(){var o;let{userId:a}=e;if(this._remoteAudioConfigMap.has(a))return void this._log.warn("remote audio has already started. userId:".concat(a));let c=this._room.remotePublishedUserMap.get(a);if(!c)return;let d={},C=c.remoteAudioTrack;C.on("decode-failed",y=>{this.emit(Hi.ERROR,new wo({code:Ro.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(C),this._speakerId&&C.setAudioOutput(this._speakerId);try{let y=(o=this._remoteAudioVolumeMap.get(a))!=null?o:this._remoteAudioVolumeMap.get("*"),S=bn(y)?y:100;d.volume=S,this._remoteAudioConfigMap.set(a,e),yield this._room.subscribe(C),ma(ca(C,"decode-failed"),EE(ca(C,Zs.INIT)),Bl(()=>{this.startPlugin(fz.Name,{track:C,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:d,track:C}),F.emit("115",{userId:a,room:this.room}),C.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:C.outMediaTrack,refId:"ra-".concat(a)})}catch(y){throw this._remoteAudioConfigMap.delete(a),y}this._emitTrackEvent(C)})}_stopRemoteAudio(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return KA(this,null,function*(){let a=this._room.remotePublishedUserMap.get(e.userId);a&&(a.remoteAudioTrack.stop(),a.muteState.hasAudio&&o&&(yield this._room.unsubscribe(a.remoteAudioTrack)),this._mediaTrackMap.delete(a.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),F.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})})}_enableVideoDecodeFallback(e,o){let a,c=this._room.videoDecodeFallbackType;c&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),ma(ca(e,"decode-failed"),EE(ca(e,Zs.INIT)),JK(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:c})}),e1(ca(e,"decode-downgrade-state-changed")),Bl(d=>{a=d.state,this.emit(Hi.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Qo(mi({},d),{streamType:o,userId:e.userId}))},d=>{e.log.error("fallback",d)},()=>{a==="STARTED"&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return KA(this,arguments,function(o){let{view:a,playOption:c,track:d,prevConfig:C}=o;return function*(){if(d.setMirror(c.mirror),Je(a)&&C&&C.view&&!S0(c)){let y=nM(C.view);y.length>0&&(yield d.play(y,c))}if(!Je(a)){let y=nM(a);y.length>0?yield d.play(y,c):d.stop()}}()})}_updateAudioPlayOption(e){return KA(this,arguments,function(o){var a=this;let{playOption:c={},track:d,prevConfig:C}=o;return function*(){if(!d.isPlayCalled)try{yield d.play(null,c)}catch{}if(Je(c.muted)||d.setPlayerMute(c.muted),Je(c.volume)||d.setAudioVolume(c.volume/100),d instanceof HM&&d.mediaTrack){let y=c.muted===!1&&!Je(c.volume)&&c.volume>0?"add":"remove";a.room.audioManager.updateAudioReference({type:y,audioReference:d.mediaTrack,refId:"em"})}else if(d instanceof s1){let y=c.muted?0:c.volume;if(Je(y))return;a.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(d.userId),volume:c.volume})}}()})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],a=e.isRemote?e.userId:"";e.outMediaTrack&&(o&&this._mediaTrackMap.get(e.outMediaTrack)===a||(this._mediaTrackMap.set(e.outMediaTrack,a),this.emit(Hi.TRACK,{userId:a,streamType:eC(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,o,a;let c=[];if((e=this._localAudioConfig)!=null&&e.publish&&this._localAudioTrack&&c.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&c.push(this._localVideoTrack),(a=this._localScreenConfig)!=null&&a.publish&&(this._localScreenTrack&&c.push(this._localScreenTrack),this._localScreenAudioTrack&&c.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),c.length!==0)return Promise.all(c.map(d=>this._room.publish(d).catch(()=>{})))}_observeView(e){let{remoteTrack:o,view:a,receiveWhenViewVisible:c,viewRoot:d}=e;if(Je(a)||Je(c))return;let C=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(eC(o.streamType)));if(!C)return;let y=C.observer||void 0;if(a===null||wa(a)&&a.length===0||!c)return y?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let S=C.visibleViewMap||new Map,k=-1;(!y||y.root!==d)&&(y?.disconnect(),S.clear(),y=new IntersectionObserver(J=>{J.forEach(gA=>{S.set(gA.target,gA.isIntersecting),o.log.info("view ".concat(gA.target.id," is").concat(gA.isIntersecting?"":" not"," visible"))}),clearTimeout(k),k=window.setTimeout(()=>{[...S.values()].find(gA=>gA)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:d}));let V=new Set(nM(a));S.forEach((J,gA)=>{V.has(gA)||(y.unobserve(gA),S.delete(gA))}),V.forEach(J=>{S.set(J,!0),y.observe(J)}),y.takeRecords().forEach(J=>{S.set(J.target,J.isIntersecting)}),C.visibleViewMap=S,C.observer=y}_exitRoom(){return KA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return KA(this,null,function*(){var e,o;if(this._localScreenTrack){if(this._room.isJoined){let a=[];(e=this._localScreenConfig)!=null&&e.publish&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),yield Promise.all(a.map(c=>this._room.unpublish(c).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((o=this._localScreenAudioTrack.trackSettings)==null?void 0:o.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),kn(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,o){return KA(this,null,function*(){var a,c;if(!e||!o)return;let d=(a=e.trackSettings)==null?void 0:a.displaySurface;if(((c=o.trackSettings)==null?void 0:c.echoCancellation)===!1&&(d==="monitor"||d==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(C){this._log.warn("start audioProcessor plugin failed: ",C)}}})}_onLocalTrackCaptured(e){let{track:o}=e;o.kind==="audio"&&(!Zl||Xk(Zl))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return KA(this,null,function*(){if(Zl&&!Xk(Zl))this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:Zl});else{let e=yield YM();e[0]&&!Xk(e[0])?(Zl=e[0],this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(e){let{userId:o}=e,a=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(a===!1||this._room.autoReceiveAudio&&!a)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(e){let{userId:o,streamType:a}=e;if(!this._room.autoReceiveVideo)return;let c=this._room.remotePublishedUserMap.get(o);if(c){let d=a==="main"?c.remoteVideoTrack:c.remoteAuxiliaryTrack,C=[d];this._room.autoReceiveAudio&&c.remoteAudioTrack.isAvailable&&C.push(c.remoteAudioTrack),this._room.subscribe(...C).then(()=>{this._emitTrackEvent(d)}).catch(()=>{})}}_onAudioUnavailable(e){let{userId:o,muteState:a}=e;a.hasAudio&&a.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(e){let{userId:o,streamType:a}=e;this._stopRemoteVideo({userId:o,streamType:a},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,o){var a;let c=this._plugins.get("SEI");c&&(c.update({buffer:e,options:Qo(mi({seiPayloadType:243},o),{small:!((a=this._localVideoTrack)==null||!a.small)})}),ii.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var o,a;(a=(o=this._room).sendCustomMessage)==null||a.call(o,e),ii.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,o){return KA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(o),")")),GiA.call(e,mi({trtcInstance:this},o))})}static setLogLevel(e,o){QA.setLogLevel(e),Je(o)||(o?QA.enableUploadLog():QA.disableUploadLog())}static isSupported(){return Nk(nm.frameWorkType)}static getPermissions(e){return KA(this,arguments,function(o){let{request:a=!0,types:c=["camera","microphone"]}=o;return function*(){a&&(yield Q1.request(c).catch(y=>{var S;return QA.error("getPermissions request failed, error: ".concat((S=y?.message)!=null?S:y))}));let[d,C]=yield Promise.all([Q1.get("camera"),Q1.get("microphone")]);return{camera:d,microphone:C}}()})}static getCameraList(){return $p(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return Xp(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return YM(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(e){return KA(this,null,function*(){if(Ha&&(e===lL.SPEAKER||e===lL.HEADSET)){let o=yield nm.getMicrophoneList(),a="";return o.forEach(c=>{c.label===e&&(a=c.deviceId)}),a?void dL.forEach(c=>KA(null,null,function*(){c._localAudioTrack&&(yield c.updateLocalAudio({option:{microphoneId:a}}))})):void 0}(yield YM()).forEach(o=>{o.deviceId===e&&(dL.forEach(a=>{a._setCurrentSpeaker(e),a.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Zl=o)})})}static _addKVStat(e){let{type:o,key:a,value:c,base:d,useUV:C,version:y,max:S}=e;switch(y&&(Zh.version=y),o){case"count":Zh.addCount({key:a,useUV:C});break;case"enum":Zh.addEnum({key:a,value:c,useUV:C});break;case"number":Zh.addNumber({key:a,value:c,split:d,max:S})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};Y(Ss,"VERSION",Cz),Y(Ss,"_loggerManager",QA),Y(Ss,"EVENT",Hi),Y(Ss,"ERROR_CODE",Ro),Y(Ss,"TYPE",lL),Y(Ss,"frameWorkType",30),Ci([fa({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],Ss.prototype,"use"),Ci([hu(zl.TRTC.enterRoom),WM("room",(A,e)=>{let[o]=A,[a]=e;return(o.roomId||o.strRoomId)===(a.roomId||a.strRoomId)&&o.userId===a.userId&&o.sdkAppId===a.sdkAppId}),jr(A=>function(e){return this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),A.call(this,e)}),fa()],Ss.prototype,"enterRoom"),Ci([fa()],Ss.prototype,"exitRoom"),Ci([hu(zl.TRTC.switchRoom),fa(),$k()],Ss.prototype,"switchRoom"),Ci([hu(zl.TRTC.switchRole),C_("room",{merge:(A,e)=>e}),fa()],Ss.prototype,"switchRole"),Ci([fa()],Ss.prototype,"destroy"),Ci([hu(zl.TRTC.startLocalAudio),WM("audio",(A,e)=>{let[o]=A,[a]=e;var c,d;return((c=o?.option)==null?void 0:c.microphoneId)===((d=a?.option)==null?void 0:d.microphoneId)}),fa()],Ss.prototype,"startLocalAudio"),Ci([hu(zl.TRTC.updateLocalAudio),C_("audio",{debounce:{delay:200,getKey:()=>"".concat(yz,"-localAudio"),isNeedToDebounce:A=>{var e;return!Je((e=A.option)==null?void 0:e.captureVolume)}}}),fa()],Ss.prototype,"updateLocalAudio"),Ci([zM("audio"),fa()],Ss.prototype,"stopLocalAudio"),Ci([hu(zl.TRTC.startLocalVideo),WM("video",(A,e)=>{let[o]=A,[a]=e;var c,d;return((c=o?.option)==null?void 0:c.cameraId)===((d=a?.option)==null?void 0:d.cameraId)}),fa()],Ss.prototype,"startLocalVideo"),Ci([hu(zl.TRTC.updateLocalVideo),C_("video"),fa()],Ss.prototype,"updateLocalVideo"),Ci([zM("video"),fa()],Ss.prototype,"stopLocalVideo"),Ci([hu(zl.TRTC.startScreenShare),WM("screen",()=>!0),fa()],Ss.prototype,"startScreenShare"),Ci([hu(zl.TRTC.updateScreenShare),C_("screen"),fa()],Ss.prototype,"updateScreenShare"),Ci([fa()],Ss.prototype,"stopScreenShare"),Ci([hu(zl.TRTC.startRemoteVideo),WM(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ss.prototype,"startRemoteVideo"),Ci([hu(zl.TRTC.updateRemoteVideo),C_(A=>"v".concat(A.userId).concat(A.streamType)),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ss.prototype,"updateRemoteVideo"),Ci([hu(zl.TRTC.stopRemoteVideo),jr(A=>function(e){return KA(this,null,function*(){if(e.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(a=>{this._remoteVideoConfigMap.has("".concat(a.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:a.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(a.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:a.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,e)})}),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ss.prototype,"stopRemoteVideo"),Ci([zM(A=>"v".concat(A.userId).concat(A.streamType))],Ss.prototype,"_stopRemoteVideo"),Ci([hu(...zl.TRTC.muteRemoteAudio),fa({getRemoteId:A=>A})],Ss.prototype,"muteRemoteAudio"),Ci([hz(...zl.TRTC.setRemoteAudioVolume),function(A,e){return jr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;C{var J;(J=h_.get(this))==null||J.delete(S)},A);y.set(S,V)}else{clearTimeout(k);let V=window.setTimeout(()=>{var J;o.apply(this,d),(J=h_.get(this))==null||J.delete(S)},A);y.set(S,V)}})}(200,A=>A),fa({getRemoteId:A=>A})],Ss.prototype,"setRemoteAudioVolume"),Ci([nj("start"),VM(A=>{var e;return(e=A.afterStart)==null?void 0:e.call(A)}),WM((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e)),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>_2[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],Ss.prototype,"startPlugin"),Ci([nj("update"),C_((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e),{merge:(A,e)=>(Wh(A[1],e[1]),A)}),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>uy[A.getName()]})],Ss.prototype,"updatePlugin"),Ci([nj("stop"),zM((A,e)=>{if(A.disableRandomCall)return null;let o=A.getGroup(e),a=A.getAlias();return o==="*"?new RegExp("".concat(a,".*")):a+o}),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>X0[A.getName()]})],Ss.prototype,"stopPlugin"),Ci([hz(...zl.TRTC.enableAudioVolumeEvaluation)],Ss.prototype,"enableAudioVolumeEvaluation"),Ci([fa()],Ss.prototype,"getVideoSnapshot"),Ci([fa()],Ss.prototype,"_setCurrentSpeaker"),Ci([WM(A=>"a".concat(A.userId),()=>!0)],Ss.prototype,"_startRemoteAudio"),Ci([jr(A=>function(e){return KA(this,null,function*(){return e.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Qo(mi({},e),{userId:o.userId})).catch(()=>{}))):A.call(this,e)})}),zM(A=>"a".concat(A.userId))],Ss.prototype,"_stopRemoteAudio"),Ci([zM("room")],Ss.prototype,"_exitRoom"),Ci([zM("screen")],Ss.prototype,"_stopScreenShare"),Ci([hu(...zl.TRTC.sendSEIMessage),Y5({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,e=new Array(A),o=0;oA.data.byteLength})],Ss.prototype,"sendCustomMessage"),Ci([fa()],Ss.prototype,"callExperimentalAPI"),Ci([ZM()],Ss,"create"),Ci([hu(zl.TRTC.create)],Ss,"_create"),Ci([ZM()],Ss,"setLogLevel"),Ci([ZM()],Ss,"isSupported"),Ci([ZM(),fa()],Ss,"getPermissions"),Ci([ZM()],Ss,"getCameraList"),Ci([ZM()],Ss,"getMicrophoneList"),Ci([ZM()],Ss,"getSpeakerList");var CL=Ss,LiA=class{constructor(){Y(this,"_set",new Set),F.on(nA.LEAVE_SUCCESS,this.delete,this),F.on(nA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let a=this.getKey(e.userId,o||e.roomId,e.sdkAppId,e.useStringRoomId);this._set.add(a)}delete(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let a=this.getKey(e.userId,e.roomId||o,e.sdkAppId,e.useStringRoomId);this._set.delete(a)}getKey(A,e,o,a){return"".concat(o,"_").concat(e,"_").concat(A,"_").concat(a)}isJoined(A){let{userId:e,roomId:o,sdkAppId:a,room:c}=A;return c.scene!=="rtc"&&this._set.has(this.getKey(e,o,a,c.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:e,currentRoomId:o,targetRoomId:a}=A;e.scene!=="rtc"&&(this._set.delete(this.getKey(e.userId,o,e.sdkAppId,e.useStringRoomId)),this._set.add(this.getKey(e.userId,a,e.sdkAppId,e.useStringRoomId)))}};function UiA(){return KA(this,null,function*(){let A,e;try{let CA=yield Xp();A=CA&&CA.length}catch{}try{let CA=yield $p();e=CA&&CA.length}catch{}let o={microphone:A,camera:e},{isH264EncodeSupported:a,isVp8EncodeSupported:c,isH264DecodeSupported:d,isVp8DecodeSupported:C,isH265EncodeSupported:y,isH265DecodeSupported:S}=this.checkSystemResult.detail,k=te.basis(),V={webRTC:k.isWebRTCSupported,getUserMedia:k.isGetUserMediaSupported,webSocket:k.isWebSocketsSupported,screenShare:k.isScreenShareSupported,webAudio:k.isWebAudioSupported,h264Encode:a,h264Decode:d,vp8Encode:c,vp8Decode:C,h265Encode:y,h265Decode:S},J={browser:k.browser,os:k.os,trtc:V,devices:o},gA={isWebCodecSupported:k.isWebCodecSupported,isMediaSessionSupported:k.isMediaSessionSupported,isWebTransportSupported:k.isWebTransportSupported};sn.uploadEvent({log:"trtcstats-".concat(JSON.stringify(J)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(J))),sn.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(gA)),userId:this.userId}),kM()})}var FiA=gc(Kl()),Dz="1",dj="2",hL="3",OiA="4",p1="5",PiA="6",m1="7",Sz="8",eB={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},xiA=[eB.UPDATE_REMOTE_MUTE_STAT,eB.UPLINK_NETWORK_STATS,eB.USER_LIST_RES,eB.MUTE_RESULT,eB.SERVER_FIRST_PACKAGE_RECEIVED,eB.RECEIVE_CUSTOM_MSG,eB.UPDATE_NETWORK_TIME_RESULT],ls={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Mz="publish_change",YiA="join",ViA="leave",JiA="quality_report",vz="mute_uplink",Rz="publish",Cj="publish_state_change",f1="unpublish",wz="subscribe",hj="unsubscribe",Bj="subscribe_change",HiA="start_publishing",qiA="stop_publishing",KiA="start_push_user_cdn",jiA="stop_push_user_cdn",WiA="start_mcu_mix",ziA="stop_mcu_mix",ZiA="start_publish_cdn_stream",XiA="update_publish_cdn_stream",$iA="stop_publish_cdn_stream",AoA="get_user_list",eoA="change_role",Qj="update_constraint_config",toA="rebuild_pc",ioA="join/v2",_z="publish/v2",Tz="subscribe/v3",ooA="ability_status_report",soA="reconnect",noA="channel_msg",roA="switch_room",aoA="update_network_time",goA=new Set([Rz,Mz,Cj,f1,wz,Bj,hj,_z,Tz]),y1=new Set,coA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],loA=0,Nz=class extends FiA.default{constructor(A){var e,o,a;super(),Y(this,"room"),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"url"),Y(this,"backupUrl"),Y(this,"destroyed",!1),Y(this,"_socketInUse"),Y(this,"_socket"),Y(this,"_backupSocket"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_seq",0),Y(this,"_log"),Y(this,"_lastMessageTime",-1),Y(this,"_connectStartTime",-1),Y(this,"_stopConnectRetry"),Y(this,"_isFirstConnect",!0),Y(this,"bytesSent",0),Y(this,"bytesReceived",0),Y(this,"keepAlive",!1),Y(this,"signalDomainWhenUnifiedProxy"),Y(this,"stopKeepAliveTimeout"),Y(this,"stopPrelinkTimeout"),Y(this,"rtt",0),Y(this,"prelink",!1),Y(this,"_prelinkConfig"),this.room=A.room,this.sdkAppId=A.sdkAppId,this.userId=A.userId,this.userSig=A.userSig,this.signalDomainWhenUnifiedProxy=A.signalDomainWhenUnifiedProxy,this.prelink=A.prelink||!1;let c=((o=(e=this.room.scheduleResult)==null?void 0:e.config)==null?void 0:o.keepAliveClient)||0;(a=this.room.joinParams)!=null&&a.keepAlive&&!c&&(c=1),c-y1.size>0&&this.room.enableSPC&&(this.keepAlive=!0,y1.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=QA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++loA),userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let A="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(A+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),this.prelink&&(A+="&prelink=1");let e=new URLSearchParams(location.search);return coA.forEach(o=>{let a=e.get("trtc_".concat(o));a&&(A+="&".concat(o,"=").concat(encodeURIComponent(a)))}),this.race?"".concat(A,"&race=1"):A}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return KA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return function*(){if(A.isConnected)return Promise.resolve();A._log.info("connect to [".concat(A.url,", ").concat(A.backupUrl,"] ").concat(A.race?"race":"").concat(e?" timeout: ".concat(e):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=ko();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:e})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:e})),A._socketInUse=yield oM(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?YA.BACKUP:YA.MAIN),A._isFirstConnect&&(ii.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:e,timeout:o,isMain:a}=A,c=new WebSocket(e);this.bindSocket(c),a?this._socket=c:this._backupSocket=c;let d=-1;return new Promise((C,y)=>{c.onclose=y,c.onerror=y,c.onopen=()=>C(c),o&&(d=setTimeout(()=>{this.unbindAndCloseSocket(a?YA.MAIN:YA.BACKUP),y(new ai({code:dt.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{c.onclose=null,c.onerror=null,c.onopen=null,clearTimeout(d)})}bindSocket(A){A.addEventListener("close",this.onclose),A.addEventListener("error",this.onerror),A.addEventListener("message",this.onmessage)}unbindSocket(A){A.removeEventListener("close",this.onclose),A.removeEventListener("error",this.onerror),A.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(A){if(A===YA.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(A){A.target===this._socketInUse&&(this._log.warn("".concat(A.target===this._socket?"main":"backup"," is closed code:").concat(A.code," ").concat(A.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!A.wasClean||A.code!==1e3&&A.code!==4013)&&this.startReconnection(),this.prelink&&A.code===4013&&this.room.clearNetworkQuality(),this.room.isJoining&&this.emit(p1,new ai({code:dt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(A){this._log.error("".concat(A.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),A.target===this._socketInUse&&(this.unbindAndCloseSocket(YA.MAIN),this.unbindAndCloseSocket(YA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(p1,new ai({code:dt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:e}=this;this._lastMessageTime=Date.now(),e||this.emit(Sz),this.bytesReceived+=v0(A.data);let o=JSON.parse(A.data),{cmd:a,data:c}=o,d=Object.values(eB),C=Object.keys(eB)[d.indexOf(a)],y=ls[C]||a;switch(xiA.includes(a)||(this._log.debug("received ".concat(a," msg: ").concat(A.data)),y&&this._log.info("Received event: [ ".concat(y," ]"))),a){case eB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=c.clientIp,this._signalInfo.signalIp=c.signalInnerIp,c.svrTime&&KB(c.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(ko()-this._connectStartTime)),ii.addSuccessEvent({key:521701,cost:ko()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Dz,{signalInfo:this._signalInfo});else{let S=new ai({code:dt.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:Xo({key:Mo.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),ii.addFailedEvent({key:521701,error:S}),this.emit(p1,S)}break;case eB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=c.relayOuterIp,this._signalInfo.relayInnerIp=c.relayInnerIp,this._signalInfo.bakRelayIps=c.bakRelayIps,this._signalInfo.relayPort=c.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=c.endReportExtend,this._signalInfo.reportToken=c.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(y,{data:o});break;default:this.emit(String(y),{data:o})}}reGetSignalChannelUrl(){return KA(this,null,function*(){try{if(!this.room.joinParams)return;hQ(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:e}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=e}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?YA.MAIN:YA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return KA(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:A,useStringRoomId:e}=this.room,{relayIp:o,relayInnerIp:a,relayPort:c}=this._signalInfo,{data:d}=yield this.sendWaitForResponse({command:soA,data:{roomId:A,useStringRoomId:e,relayInnerIp:a,relayOuterIp:o,relayPort:c},responseCommand:ls.CHANNEL_RECONNECT_RESULT});d.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),ii.addSuccessEvent({key:521702,cost:ko()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(ii.addFailedEvent({key:521702,error:d.code}),this._log.warn("reconnect failed, ".concat(d.code," ").concat(d.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:e,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},a=JSON.stringify(o);return this._socketInUse.send(a),goA.has(A)&&this._log.info("send",A,e),this.bytesSent+=v0(a),o.seq}}sendWaitForResponse(A){let{command:e,data:o,timeout:a=5e3,responseCommand:c,commandDesc:d,enableLog:C=!0,addReceiveTime:y=!1}=A;return new Promise((S,k)=>{let V=()=>{clearTimeout(J),k(new ai({code:dt.API_CALL_ABORTED,message:"".concat(e," aborted due to connection closed")}))};this.once(m1,V);let J=setTimeout(()=>{this.off(c,gA),this.off(m1,V);let MA=new ai({code:dt.API_CALL_TIMEOUT,message:Xo({key:Mo.API_CALL_TIMEOUT,data:{commandDesc:d,command:e}})});C&&this._log.warn(MA),k(MA)},a),gA=MA=>{MA.data.seq===CA&&(clearTimeout(J),this.off(c,gA),this.off(m1,V),y&&(MA.data.receiveTime=Date.now()),S(MA))};this.on(c,gA);let CA=this.send(e,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:e,command:o,retries:a=0,retryTimeout:c=0}=A;return gM({retryFunction:this.sendWaitForResponse,onError:d=>{let{retry:C,reject:y,error:S}=d;!this.room.isJoined||this.destroyed||S.code===dt.API_CALL_ABORTED?y(S):this.isOnline?C():(this._log.warn("retry ".concat(o," when connected")),this.once(Sz,C))},onRetrying:d=>{this._log.warn("".concat(e||o," timeout observed, retrying [").concat(d,"/").concat(a,"]"))},settings:{retries:a,timeout:c},context:this})(A)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),clearTimeout(this.stopPrelinkTimeout),y1.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(YA.MAIN),this.unbindAndCloseSocket(YA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(m1)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let e=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(A,"s")),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(A,"s")),this.close(),this.off(ls.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(ls.JOIN_ROOM_RESULT,e))};this.on(ls.JOIN_ROOM_RESULT,e)}}stopPrelinkIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:300;if(this.keepAlive)return;this._log.info("stopPrelink in ".concat(A,"s")),this.stopPrelinkTimeout=setTimeout(()=>{this._log.info("close prelink due to not used in ".concat(A,"s")),this.close(),this.room.clearNetworkQuality(),this.off(ls.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(ls.JOIN_ROOM_RESULT,e))};this.on(ls.JOIN_ROOM_RESULT,e)}markPrelinkConnected(A){this._prelinkConfig=Qo(mi({},A),{linkedTime:Date.now()})}isPrelinkValid(A,e,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||e!==this._prelinkConfig.userId||o!==this._prelinkConfig.userSig?(this._log.warn("prelink params not match"),!1):!!this.isConnected||(this._log.warn("prelink is not connected"),!1))}consumePrelink(){this.prelink=!1,this._prelinkConfig=void 0}emitConnectionStateChanged(A){if(A===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(A));let e={prevState:this._currentState,state:A};A==="CONNECTING"&&(e.isReconnecting=this._isReconnecting),this.emit(dj,e),this._currentState=A,A==="CONNECTED"?this.emit(hL):A==="DISCONNECTED"&&this.emit(PiA)}};Ci([$h({settings:{retries:1/0,timeout:2e3},onError(A,e){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(ii.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),e())},onRetrying(A,e){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),e&&(this._stopConnectRetry=e,(this.room.isDestroyed||this.destroyed)&&e())}})],Nz.prototype,"connect");var IoA=gc(Kl()),Gz=!1,tm=class{constructor(A){Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_signalChannel"),Y(this,"_isErrorObserved",!1),Y(this,"_waitForPeerConnectionConnectedPromise"),Y(this,"_waitForPeerConnectionConnectedPromiseReject",null),Y(this,"_peerConnection",null),Y(this,"_emitter",new IoA.default),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_reconnectionCount",0),Y(this,"_reconnectionTimer",-1),Y(this,"_isFirstConnection",!0),Y(this,"_prevTime",-1),Y(this,"_localAddress"),Y(this,"_remoteAddress"),Y(this,"isDestoyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=A.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=A.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=ko())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,ii.addSuccessEvent({key:521705,cost:Math.min(ko()-this._prevTime,3e4)})):this._isReconnecting&&ii.addSuccessEvent({key:521706,cost:ko()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,ii.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&ii.addFailedEvent({key:521706,error:A}),A}}initialize(){let A={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(A),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(A){this._log.info("close connection"),this._emitter.emit("closed",A),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}closePeerConnection(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,A&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new ai({code:dt.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Kh;let A=null;if(this._isUplink){if(!LI()||this._peerConnection.getSenders().length===0)return Kh;A=this._peerConnection.getSenders()[0].transport}else{if(!dy()||this._peerConnection.getReceivers().length===0)return Kh;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:Kh}onConnectionStateChange(A){let e=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(e,", DTLS: ").concat(o)),A.target.connectionState===Co.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===Co.FAILED||A.target.connectionState===Co.CLOSED){let a="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(e,", DTLS Transport state: ").concat(o),c=new ai({message:a,code:dt.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",c)}(A.target.connectionState===Co.CONNECTED||A.target.connectionState===Co.COMPLETED)&&(this.logSelectedCandidate(),sn.logSuccessEvent({userId:this._room.userId,eventType:Ja.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),Gz=!0),F.emit(nA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return KA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,e]of A)if(_M(e)){let o=A.get(e.localCandidateId),a=A.get(e.remoteCandidateId);o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat(o.candidateType==="relay"?"relayProtocol:".concat(o.relayProtocol):"")),this._localAddress="".concat(o.ip||o.address,":").concat(o.port)),a&&(this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port)),this._remoteAddress="".concat(a.protocol,":").concat(a.ip||a.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,e)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=e;let o=C=>{C.state==="CONNECTED"&&(clearTimeout(d),c(),A())},a=C=>{let{room:y}=C;y===this._room&&(clearTimeout(d),c(),e(new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.CONNECTION_ABORTED,data:"leave room"})})))},c=()=>{F.off(nA.LEAVE_SUCCESS,a,this),this._emitter.off("connection-state-changed",o,this)},d=setTimeout(()=>{c();let C=new ai({code:dt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(C)},Nb);F.on(nA.LEAVE_SUCCESS,a,this),this._emitter.on("connection-state-changed",o,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(hL,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=xf()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new ai({code:this._isUplink?dt.UPLINK_RECONNECTION_FAILED:dt.DOWNLINK_RECONNECTION_FAILED,message:Xo({key:this._isUplink?Mo.UPLINK_RECONNECTION_FAILED:Mo.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",A),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(hL,this.reconnect,this),-1)}on(A,e,o){this._emitter.on(A,e,o)}off(A,e,o){this._emitter.off(A,e,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}setOffer(A){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(A)}setAnswer(A){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(A)}};Ci([fy(521712,!1)],tm.prototype,"setOffer"),Ci([fy(521713,!1)],tm.prototype,"setAnswer");var bz=gc(Qb()),uc=function(A){return bz.default.parse(A)},vy=function(A){return bz.default.write(A)};function pj(A){return Object.keys(A).filter(e=>A[e])}var D1=class O9 extends tm{constructor(e){super(Qo(mi({},e),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"avPlayerStateSyncManager"),Y(this,"ssrc",{audio:0,video:0,auxiliary:0}),Y(this,"_isSDPExchanging",!1),Y(this,"_videoCodec"),Y(this,"fromType"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new s1(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new cL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new P5(this._room,this),this.avPlayerStateSyncManager=new ij({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var e,o;let a=(o=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null?void 0:o.sdp;return a?a.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return wp(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var o,a,c;e!==this._flag&&(this._flag=e,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(a=this.remoteVideoTrack)==null||a.onFlagChanged(),(c=this.remoteAuxiliaryTrack)==null||c.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===YA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,a;let c=this._currentState,d=super.emitConnectionStateChangedEvent(e);return d&&c!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:c,state:e}),(a=this.remoteAuxiliaryTrack)==null||a.emit("connection-state-changed",{prevState:c,state:e})),d}onTrack(e){let o=e.streams[0],{track:a}=e,c=o.id===uu?YA.MAIN:YA.AUXILIARY;this._log.debug("ontrack ".concat(c," ").concat(a.kind));let d=YA.AUDIO;a.kind===YA.VIDEO&&(d=c===YA.MAIN?YA.VIDEO:YA.AUXILIARY);let C=this.remoteAudioTrack;d===YA.VIDEO?C=this.remoteVideoTrack:d===YA.AUXILIARY&&(C=this.remoteAuxiliaryTrack),C.setInputMediaStreamTrack(a)}addRRTRLine(e){let o=e.split(`\r -`),a=new Map;o.forEach((d,C)=>{/^a=rtcp-fb:/.test(d)&&o[C+1]&&!/^a=rtcp-fb:/.test(o[C+1])&&a.set(C+1,"".concat(d.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let c=[...a];for(let d=0;d{a.type===YA.VIDEO&&a.fmtp.forEach(c=>{c.config+=";sps-pps-idr-in-keyframe=1"})}),vy(o)}removeSDESDescription(e){let o=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],a=uc(e);return a.media.forEach(c=>{c.ext&&(c.ext=c.ext.filter(d=>!o.includes(d.uri)))}),vy(a)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,o){return KA(this,null,function*(){var a,c;try{if((((a=this._peerConnection)==null?void 0:a.connectionState)===Co.NEW||((c=this._peerConnection)==null?void 0:c.connectionState)===Co.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(o," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let d="subscribe_change";Object.values(e).find(C=>C===!0)||(d="unsubscribe"),yield this.sendSubscription(d,e)}else this.initialize(),yield this.connect(e)}catch(d){throw this._room.isJoined&&this.isStreamUnpublished(o)?(this._log.warn("".concat(d.message," ").concat(JSON.stringify(this.muteState))),new ai({code:dt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):d}})}unsubscribe(e){return KA(this,arguments,function(o){var a=this;let{remoteTracks:c,streamType:d}=o;return function*(){if(a._currentState==="CONNECTED"&&(d==="main"&&!a.isMainStreamSubscribed||d==="auxiliary"&&!a.isAuxStreamSubscribed))return void a._log.info("".concat(d," stream already unsubscribed"));let C=mi({},a.subscribeState);c.forEach(S=>{switch(S.mediaType){case 1:C.audio=!1;break;case 4:C.video=!1;break;case 8:C.smallVideo=!1;break;case 2:C.auxiliary=!1}});let y="subscribe_change";Object.values(C).find(S=>S===!0)||(y="unsubscribe"),a._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(d," [").concat(pj(C),"]")),yield a.sendSubscription(y,C),y==="unsubscribe"&&(a.closePeerConnection(),a.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return KA(this,null,function*(){})}sendSubscription(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,a={srcTinyId:this.tinyId,srcUserId:this.userId},c=hj,d=ls.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(a={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},c=Bj,d=ls.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:c,data:a,responseCommand:d,timeout:1e4}).then(C=>{let{data:y}=C;if(y.code!==0){let S=new ai({code:y.code,message:Xo({key:Mo.ERROR_MESSAGE,data:{type:e,message:y.message}})});throw this._log.error(S),S}})}connect(){return KA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(o),yield e.waitForPeerConnectionConnected()}catch(a){throw e.closePeerConnection(!0),a}}()})}exchangeSDP(e){return KA(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:o,sdp:a}=this._peerConnection.localDescription,c={type:o,sdp:a,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},d=yield this._signalChannel.sendWaitForResponse({command:wz,commandDesc:"exchange sdp",data:c,responseCommand:ls.SUBSCRIBE_RESULT,timeout:Vx});if(!this._peerConnection){let C=new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.CONNECTION_CLOSED})});throw this._log.warn(C),C}yield this.onSubscribeResult(d),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return KA(this,null,function*(){let e={voiceActivityDetection:!1};Xd()&&this._sdpSemantics===zS?(this._peerConnection.addTransceiver(YA.AUDIO,{direction:zn.RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:zn.RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:zn.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(e);if(o.sdp){let{isH264DecodeSupported:a}=yield Tk();a||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(c){let d=uc(c);return d.media.forEach(C=>{var y,S;if(C.type===YA.VIDEO){let k=new Set;C.rtp.forEach(J=>{let{payload:gA,codec:CA}=J;return CA==="H264"&&k.add(gA)}),C.fmtp.forEach(J=>{let{payload:gA,config:CA}=J,MA=CA.match(/apt=(\d+)/);MA&&MA[1]&&k.has(Number(MA[1]))&&k.add(gA)});let V=J=>{let{payload:gA}=J;return!k.has(gA)};C.rtp=C.rtp.filter(V),C.rtcpFb=(y=C.rtcpFb)==null?void 0:y.filter(V),C.fmtp=C.fmtp.filter(V),C.payloads=(S=C.payloads)==null?void 0:S.split(" ").filter(J=>!k.has(Number(J))).join(" ")}}),vy(d)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(c){let d=uc(c);return d.media.forEach(C=>{C.type===YA.AUDIO&&C.fmtp.forEach(y=>{y.config+=";sprop-stereo=1;stereo=1"})}),vy(d)}(o.sdp),this._sdpSemantics===zS&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(e){return KA(this,null,function*(){let{code:o,message:a=""}=e&&e.data||{},{type:c,sdp:d}=e&&e.data&&e.data.data||{};if(o===I0)throw new ai({code:dt.NOT_SUPPORTED_H264,message:Xo({key:Mo.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new ai({code:o,message:Xo({key:Mo.EXCHANGE_SDP_FAILED,data:{errMsg:a}})});this._log.debug("accept remote answer: ".concat(d)),yield this.setAnswer({type:c,sdp:d}),this.updateSSRC(d)}catch(C){throw this._log.error(C),C}})}updateSSRC(e){try{uc(e).media.forEach(o=>{if(o.ssrcs)if(o.type===YA.AUDIO){let a=o.ssrcs.find(c=>{var d;return(d=c.value)==null?void 0:d.includes(uu)});a&&(this.ssrc.audio=Number(a.id))}else{let a=o.ssrcs.find(d=>{var C;return(C=d.value)==null?void 0:C.includes(uu)}),c=o.ssrcs.find(d=>{var C;return(C=d.value)==null?void 0:C.includes(Fx)});a&&(this.ssrc.video=Number(a.id)),c&&(this.ssrc.auxiliary=Number(c.id))}})}catch{}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return KA(this,null,function*(){if(!(NI(O9.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=Rp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:o,videoDelay:a}=e;this.remoteAudioTrack.stat.end2EndDelay=o,this.remoteVideoTrack.stat.end2EndDelay=a}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};Ci([jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=y=>{this._emitter.off("closed",C),d(new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this._emitter.off("closed",C)})})})],D1.prototype,"subscribe"),Ci([fy(521717,!1)],D1.prototype,"unsubscribe"),Ci([VM(tm.prototype.afterConnect),n5(tm.prototype.beforeConnect)],D1.prototype,"connect");var kz=D1,Lz={voiceActivityDetection:!1},S1=class P9 extends tm{constructor(e){super(Qo(mi({},e),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,o){var a,c,d;let C=this._currentState,y=super.emitConnectionStateChangedEvent(e);return y&&C!==e&&(o?o.emit("connection-state-changed",{prevState:C,state:e}):((a=this.localMainVideoTrack)==null||a.emit("connection-state-changed",{prevState:C,state:e}),(c=this.localAuxVideoTrack)==null||c.emit("connection-state-changed",{prevState:C,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:C,state:e}))),y}publish(e){return KA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,isAuxiliary:C}=o;return function*(){let y;a._peerConnection||a.initialize(),c&&(a._publishingLocalAudioTrack=c),d&&(a._publishingLocalVideoTrack=d),a._isPublishingAux=C,d&&!C&&d.small&&(y=a._room.videoManager.smallTrack),a.sendMediaSettings(),Xd()?yield a.publishByTransceiver({localAudioTrack:c,localVideoTrack:d,smallTrack:y,isAuxiliary:C}):yield a.publishByAddTrack({localAudioTrack:c,localVideoTrack:d,smallTrack:y}),a._publishingLocalAudioTrack=null,a._publishingLocalVideoTrack=null,a._isPublishingAux=!1,C?(d&&(a.localAuxVideoTrack=d),c&&(a.localAuxAudioTrack=c)):(d&&(a.localMainVideoTrack=d),c&&(a.localMainAudioTrack=c)),a.installTrackMuteEvents(c,d),a.sendMutedFlag()}()})}publishByTransceiver(e){return KA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,smallTrack:C,isAuxiliary:y}=o;return function*(){a._log.info("publish by transceiver");let S=new MediaStream,k=d?.outMediaTrack,V=c?.outMediaTrack;V&&S.addTrack(V),k&&S.addTrack(k);let J=a._peerConnection.getTransceivers();if(J.length===0)a._peerConnection.addTransceiver(V||YA.AUDIO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y?YA.VIDEO:k||YA.VIDEO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(C||YA.VIDEO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y&&k||YA.VIDEO,{direction:zn.SENDONLY,streams:[S]}),yield a.connect();else{let gA=[];if(V&&(J[0].sender.track||gA.push(0),yield J[0].sender.replaceTrack(V),yield a.setBandwidth({bandwidth:c?.profile.bitrate||40,type:YA.AUDIO})),k){let CA=y?3:1;yield J[CA].sender.replaceTrack(k),yield a.setBandwidth({bandwidth:d.profile.bitrate,type:YA.VIDEO,videoType:y?YA.AUXILIARY:YA.BIG}),gA.push(CA),C&&(yield J[2].sender.replaceTrack(C),yield a.setBandwidth({bandwidth:d.small.bitrate,type:YA.VIDEO,videoType:YA.SMALL}),gA.push(2))}yield a.setTransceiverDirection(zn.SENDONLY,gA),yield a.doPublishChange(),d?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),d?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(e){return KA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,smallTrack:C}=o;return function*(){a._log.info("publish by addtrack");let y=d?.outMediaTrack,S=c?.outMediaTrack;if(a._peerConnection&&a._peerConnection.connectionState!=="new")return c&&S&&(yield a.addTrack(c)),void(y&&(yield a.addTrack(d)));let k=new MediaStream;if(S&&k.addTrack(S),y&&k.addTrack(y),S&&a._peerConnection.addTrack(S,k),y&&(a._peerConnection.addTrack(y,k),C)){let V=new MediaStream;V.addTrack(C),a._peerConnection.addTrack(C,V)}yield a.connect()}()})}enableSmall(e){return KA(this,null,function*(){let o=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield o[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(zn.SENDONLY,[2])):(yield o[2].sender.replaceTrack(null),yield this.setTransceiverDirection(zn.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),a=0;a{c&&(c?.on("mute",this.sendMutedFlag,this),c?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),a=0;a{c&&(c?.off("mute",this.sendMutedFlag,this),c?.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return KA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d}=o;return function*(){if(!IQ())return c&&c.outMediaTrack&&!d&&a.localMainVideoTrack?(yield a.removeTrack(c),void(a.localMainAudioTrack=null)):d&&d.outMediaTrack&&!c&&a.localMainAudioTrack?(yield a.removeTrack(d),void(a.localMainVideoTrack=null)):(yield a.doUnpublish(),a.uninstallTrackMuteEvents(c,d),void a.emitConnectionStateChangedEvent("DISCONNECTED",d));let C=d&&d===a.localAuxVideoTrack,y=d?.outMediaTrack,S=a._peerConnection.getSenders(),k=[];c&&(C?a.localAuxAudioTrack=null:a.localMainAudioTrack=null,!a.localAuxAudioTrack&&!a.localMainAudioTrack&&(yield S[0].replaceTrack(null),k.push(0))),y&&(C?(yield S[3].replaceTrack(null),a.localAuxVideoTrack=null,a._mediaSettings=Qo(mi({},a._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),k.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),a.localMainVideoTrack=null,a._mediaSettings=Qo(mi({},a._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),k.push(1,2))),a.isMainStreamPublished||a.isAuxStreamPublished?(yield a.setTransceiverDirection(zn.INACTIVE,k),yield a.doPublishChange(!1)):yield a.doUnpublish(),a.uninstallTrackMuteEvents(c,d),d?.emit("connection-state-changed",{prevState:a._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return KA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},a=yield this._signalChannel.sendWaitForResponse({command:Cj,data:o,responseCommand:ls.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(a.data.code,a.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:f1,commandDesc:"unpublish",responseCommand:ls.UNPUBLISH_RESULT,enableLog:e}).catch(o=>{if(o.getCode()===dt.API_CALL_TIMEOUT)return Promise.resolve();throw o})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:o}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":o&&(this._mediaSettings.videoCodec="VP8");let a=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:c,localAuxVideoTrack:d}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?d=this._publishingLocalVideoTrack:c=this._publishingLocalVideoTrack),Cy){if(a&&a.outMediaTrack){let C=a.outMediaTrack.getSettings();this._mediaSettings.audioChannel=C.channelCount||1,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=C.sampleRate||0}if(c&&c.outMediaTrack){let C=c.outMediaTrack.getSettings();this._mediaSettings.videoWidth=C.width||0,this._mediaSettings.videoHeight=C.height||0,this._mediaSettings.videoFps=C.frameRate||0,this._mediaSettings.videoBps=1e3*c.profile.bitrate,c.small&&(this._mediaSettings.smallVideoWidth=c.small.width,this._mediaSettings.smallVideoHeight=c.small.height,this._mediaSettings.smallVideoFps=c.small.frameRate,this._mediaSettings.smallVideoBps=1e3*c.small.bitrate)}if(d&&d.outMediaTrack){let C=d.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=C.width||0,this._mediaSettings.auxVideoHeight=C.height||0,this._mediaSettings.auxVideoFps=C.frameRate||0,this._mediaSettings.auxVideoBps=1e3*d.profile.bitrate}}else a&&a.outMediaTrack&&(this._mediaSettings.audioChannel=a.profile.channelCount,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=a.profile.sampleRate),c&&c.outMediaTrack&&(this._mediaSettings.videoWidth=c.profile.width,this._mediaSettings.videoHeight=c.profile.height,this._mediaSettings.videoFps=c.profile.frameRate,this._mediaSettings.videoBps=1e3*c.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Qj,data:this._mediaSettings,responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return KA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(o?YA.AUXILIARY:YA.MAIN," stream")),Xd()?yield this.addTrackByTransceiver(e,o):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,o){return KA(this,null,function*(){var a;if(!e.mediaTrack)return;let c=this._peerConnection.getTransceivers();if(e.kind===YA.AUDIO)yield c[0].sender.replaceTrack(e.outMediaTrack);else{let d=o?3:1;yield c[d].sender.replaceTrack(e.outMediaTrack),d===1&&(a=this.localMainVideoTrack)!=null&&a.small&&(yield c[2].sender.replaceTrack(this._room.videoManager.smallTrack)),c[d].direction===zn.INACTIVE&&(yield this.setTransceiverDirection(zn.SENDONLY,[d]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return KA(this,null,function*(){if(!e.outMediaTrack)return;let o=e.outMediaTrack;IQ()&&this._peerConnection.getTransceivers().findIndex(c=>c.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",o));let a=this._peerConnection.getSenders().find(c=>c.track&&c.track.kind===o.kind);if(a&&a.track){this._log.warn("sender already exists, remove sender first");let c=a.track;this.removeSender(a),yield this.updateOffer("remove",c)}if(o&&this._peerConnection.addTrack(o,new MediaStream([o])),o.kind===YA.VIDEO&&e instanceof dQ&&e.small){let c=new MediaStream,{smallTrack:d}=this._room.videoManager;c.addTrack(d),this._peerConnection.addTrack(d,c)}yield this.updateOffer("add",o)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===l0||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,o=uc(e);for(let a=0;aa.sender&&a.sender.track===e.track)),this._peerConnection.removeTrack(e),o&&Ra(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(e){return KA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(o?YA.AUXILIARY:YA.MAIN," stream")),Xd()?yield this.removeTrackByTransceiver(e,o):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,o){return KA(this,null,function*(){if(!e.outMediaTrack)return;let a=this._peerConnection.getTransceivers();if(e.kind===YA.AUDIO)yield a[0].sender.replaceTrack(null);else{let c=o?3:1;yield a[c].sender.replaceTrack(null),c===1&&e.small&&(yield a[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(zn.INACTIVE,[c])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,o){return KA(this,null,function*(){if(!er)return;let a=!1,c=!1;this._log.info("setting transceiver ".concat(o.join(",")," direction to ").concat(e));let d=this._peerConnection.getTransceivers();if(o.forEach(S=>{d[S].direction!==e&&(d[S].direction=e,a=!0)}),a){this._log.info("updating offer");let S=yield this._peerConnection.createOffer();yield this.setOffer(S)}let C=-1,y=this._peerConnection.remoteDescription.sdp.split(`\r -`).map(S=>{if(S.match(new RegExp("a=(".concat(zn.INACTIVE,"|").concat(zn.RECVONLY,"|").concat(zn.SENDONLY,")")))&&C++,o.includes(C)){if(e===zn.INACTIVE&&S.includes("a=".concat(zn.RECVONLY)))return c=!0,"a=".concat(e);if(e===zn.SENDONLY&&S.includes("a=".concat(zn.INACTIVE)))return c=!0,"a=".concat(zn.RECVONLY)}return S}).join(`\r -`);c&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:y}))})}removeTrackBySender(e){return KA(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===YA.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let o=this._peerConnection.getSenders().find(a=>a.track===e.outMediaTrack);o&&(this.removeSender(o),e.kind===YA.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(a=>{a.track&&a.track.kind===YA.VIDEO&&this.removeSender(a)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return KA(this,null,function*(){var o;let a,c=(o=this._peerConnection)==null?void 0:o.getSenders();if(!c||c.length===0||!e.mediaTrack||(a=Xd()?e.kind===YA.AUDIO?c[0]:c[1]:c.find(C=>C.track&&C.track.kind===e.kind),!a))return!1;let d=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(d?YA.AUXILIARY:YA.MAIN," stream")),e.kind===YA.AUDIO?yield a.replaceTrack(e.outMediaTrack):e.kind===YA.VIDEO&&(d?c[3]&&(yield c[3].replaceTrack(e.outMediaTrack)):yield a.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,o){return KA(this,null,function*(){try{let a=yield this._peerConnection.createOffer(Lz);er&&a.sdp&&(a.sdp=this.setSDPDirection(a.sdp,"sendrecv")),yield this.setOffer(a);let c=this.updateMediaSettings(),d={action:e,trackId:o.id,kind:o.kind===YA.VIDEO?"bigVideo":o.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:c,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(d.sdp));let C=yield this._signalChannel.sendWaitForResponse({command:Mz,data:d,responseCommand:ls.UPDATE_OFFER_RESULT,timeout:Yx,commandDesc:"update offer"}),{code:y,message:S}=C.data;y!==0&&this.checkPublishResultCode(y,S),yield this.acceptAnswer(C.data.data),a.sdp&&this.updateSSRC(a.sdp)}catch(a){throw this._log.error(a),a}})}setBandwidth(e){return KA(this,arguments,function(o){var a=this;let{bandwidth:c,type:d,videoType:C,sdp:y}=o;return function*(){if(!Ok())return y?d===YA.VIDEO?a.updateVideoBandwidthRestriction(y,c,C):a.updateAudioBandwidthRestriction(y,c):void 0;let S,k=a._peerConnection.getSenders();if(Xd()){let V=0;d===YA.VIDEO&&(V=C===YA.SMALL?2:C===YA.AUXILIARY?3:1),S=k[V]}else S=k.find(V=>V.track&&V.track.kind===d);if(S){let V=S.getParameters();(!V.encodings||V.encodings.length===0)&&(V.encodings=[{}]),V.encodings[0].maxBitrate=1e3*c;try{return yield S.setParameters(V),a._log.info("".concat(C||"").concat(d," bandwidth ").concat(c," kbps")),y}catch(J){if(a._log.info("failed to set bandwidth by setting maxBitrate: ".concat(J)),y)return d===YA.VIDEO?a.updateVideoBandwidthRestriction(y,c,C):a.updateAudioBandwidthRestriction(y,c)}}return y}()})}updateVideoBandwidthRestriction(e,o,a){let c="AS";er&&(c="TIAS",o*=1e3);let d=0,C=-1;return a===YA.SMALL?d=1:a===YA.AUXILIARY&&(d=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,y=>(C+=1,C===d?"".concat(y,"b=").concat(c,":").concat(o,`\r -`):y)),e}updateAudioBandwidthRestriction(e,o){let a="AS";return er&&(a="TIAS",o*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r +`).concat(k.stack)),!1}}})(this,"trtc")}static create(e){}static _create(e,o){(function(){var l;if(Iz){Iz=!1,pA.getLogLevel()!==5&&(console.info("******************************************************************************"),console.info("* TRTC Web SDK"),console.info("* API Document: ".concat(Wh,"/en/index.html")),console.info("* Changelog: ".concat(Wh,"/en/tutorial-01-info-changelog.html")),console.info("* Report issues: https://github.com/LiteAVSDK/TRTC_Web/issues"),console.info("******************************************************************************")),pA.info("TRTC Web SDK Version:",qd),Yp||pA.debug("Build Time:","2026-02-28 12:18:13");let d="UA: ".concat(navigator.userAgent,` +CPU core: `).concat(navigator.hardwareConcurrency,", GPU: ").concat(Vp());if(eg&&window.screen&&(window.screen.width||window.screen.height)){let y="".concat(window.screen.width,"x").concat(window.screen.height,"@").concat(window.devicePixelRatio);d+=", screen: ".concat(y)}let h=navigator.deviceMemory;h&&(d+=", minRAM: ".concat(h,"GB")),pA.info(d),pA.info("URL: ".concat(location.href).concat(((l=self.frameElement)==null?void 0:l.tagName)==="IFRAME"?" in iframe":"")),SM().then(y=>{y&&pA.info(PC)})}})();let a=new gm(e,o||{});return mL.add(a),a.__v_skip=!0,a}get room(){return this._room}_listenEvents(){nd(this,this._room).add("peer-join",e=>{let{userId:o}=e;this.emit(Ki.REMOTE_USER_ENTER,{userId:o})}).add("peer-leave",e=>{let{userId:o,reason:a}=e;this.emit(Ki.REMOTE_USER_EXIT,{userId:o,reason:a})}).add("banned",e=>{pQ(!0),this._exitRoom().finally(()=>{this.emit(Ki.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Ki.ERROR,_o.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Ki.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let o=po(fi({},e),{uplinkRTT:Math.min(e.uplinkRTT,h0),downlinkRTT:Math.min(e.downlinkRTT,h0)});this.emit(Ki.NETWORK_QUALITY,o)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{nd(o,o).add("player-state-changed",a=>{let l=po(fi({},a),{userId:e.userId});o.kind===YA.VIDEO&&(l.streamType=eC(o.streamType)),this.emit(o.kind===YA.AUDIO?Ki.AUDIO_PLAY_STATE_CHANGED:Ki.VIDEO_PLAY_STATE_CHANGED,l)}).add("error",a=>{a.getCode()===Ct.PLAY_NOT_ALLOWED&&this.emit(Ki.AUTOPLAY_FAILED,{userId:o.userId,mediaType:o.strMediaType,resume:()=>o.player.resume()})})})}).add("remote-unpublished",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{Ln(o)})}).add("remote-publish-state-changed",e=>{let{prevMuteState:o,muteState:a}=e,{userId:l}=a,d=o.audioAvailable,h=o.videoAvailable,{audioAvailable:y,videoAvailable:S}=a;y||this._remoteAudioConfigMap.delete(l),S||this._removeRemoteVideoConfig(l,"main"),a.hasAuxiliary||this._removeRemoteVideoConfig(l,"sub"),h!==S&&(S?this._onVideoAvailable({userId:l,streamType:"main"}):this._onVideoUnavailable({userId:l,streamType:"main"}),this.emit(S?Ki.REMOTE_VIDEO_AVAILABLE:Ki.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"main"})),d!==y&&(y?this._onAudioAvailable({userId:l}):this._onAudioUnavailable({userId:l,muteState:a}),this.emit(y?Ki.REMOTE_AUDIO_AVAILABLE:Ki.REMOTE_AUDIO_UNAVAILABLE,{userId:l})),o.hasAuxiliary!==a.hasAuxiliary&&(a.hasAuxiliary?this._onVideoAvailable({userId:l,streamType:"sub"}):this._onVideoUnavailable({userId:l,streamType:"sub"}),this.emit(a.hasAuxiliary?Ki.REMOTE_VIDEO_AVAILABLE:Ki.REMOTE_VIDEO_UNAVAILABLE,{userId:l,streamType:"sub"})),o.hasDatachannel!==a.hasDatachannel&&a.hasDatachannel&&this._onDataChannelAvailable()}).add("sei-message",e=>{this.emit(Ki.SEI_MESSAGE,po(fi({},e),{streamType:eC(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Ki.ERROR,new _o({code:wo.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,a,l,d,h,y,S;let k={2:"big",3:"small",7:"sub"},V={rtt:Math.min(e.msg_up_stream_info.msg_network_status.uint32_rtt||((o=e.msg_down_stream_info[0])==null?void 0:o.msg_network_status.uint32_rtt)||((a=this._networkQuality)==null?void 0:a.uplinkRTT)||((l=this._networkQuality)==null?void 0:l.downlinkRTT)||0,h0),upLoss:((d=this._networkQuality)==null?void 0:d.uplinkLoss)||0,downLoss:((h=this._networkQuality)==null?void 0:h.downlinkLoss)||0,bytesSent:e.bytes_sent||0,bytesReceived:e.bytes_received||0,localStatistics:{audio:{bitrate:(((y=e.msg_up_stream_info.msg_audio_status)==null?void 0:y.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((S=e.msg_up_stream_info.msg_audio_status)==null?void 0:S.uint32_audio_level)||0)/id},video:e.msg_up_stream_info.msg_video_status.filter(J=>k[J.uint32_video_stream_type]).map(J=>({bitrate:(J.uint32_video_codec_bitrate||0)/1e3,width:J.uint32_video_width,height:J.uint32_video_height,frameRate:J.uint32_video_enc_fps,videoType:k[J.uint32_video_stream_type]}))},remoteStatistics:e.msg_down_stream_info.map(J=>({userId:J.msg_user_info.str_identifier,audio:{bitrate:(J.msg_audio_status.uint32_audio_codec_bitrate||0)/1e3,audioLevel:(J.msg_audio_status.uint32_audio_level||0)/id,point2pointDelay:(J.msg_audio_status.uint32_audio_p2p_delay||0)+(J.msg_audio_status.uint32_audio_cache_ms||0),jitterBufferDelay:J.msg_audio_status.uint32_audio_cache_ms||0},video:J.msg_video_status.map(cA=>({bitrate:(cA.uint32_video_codec_bitrate||0)/1e3,width:cA.uint32_video_width,height:cA.uint32_video_height,frameRate:cA.uint32_video_dec_fps,videoType:k[cA.uint32_video_stream_type],point2pointDelay:(cA.uint32_video_p2p_delay||0)+(cA.uint32_video_cache_ms||0),jitterBufferDelay:cA.uint32_video_cache_ms||0,codec:cA.uint32_video_codec}))}))};this.emit(Ki.STATISTICS,V)}).add("custom-message",e=>{this.emit(Ki.CUSTOM_MESSAGE,e)}).add("layerData",e=>this.emit(Ki.LAYER_DATA,e)).add("first-video-frame",e=>{this.emit(Ki.FIRST_VIDEO_FRAME,po(fi({},e),{streamType:eC(e.streamType)}))}).add("audio-frame",e=>{this.emit(Ki.AUDIO_FRAME,e)}).add("data-channel-message",e=>{var o,a,l,d,h;let{data:y}=e;if(y.sender==="")return;let S={segmentId:(o=y.payload)==null?void 0:o.roundid,speakerUserId:y.sender,sourceText:(a=y.payload)==null?void 0:a.text,translationTexts:(l=y.payload)==null?void 0:l.translate_msg,timestamp:(d=y.payload)==null?void 0:d.start_utc_ms,isCompleted:(h=y.payload)==null?void 0:h.end,robotId:y.robotid};S.sourceText!==""&&this.emit(Ki.REALTIME_TRANSCRIBER_MESSAGE,S)}).add("asr-robot-peer-join",e=>{this.emit(Ki.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"started",roomId:this.room.roomId,transcriberRobotId:e.userId})}).add("asr-robot-peer-leave",e=>{this.emit(Ki.REALTIME_TRANSCRIBER_STATE_CHANGED,{state:"stopped",roomId:this.room.roomId,transcriberRobotId:e.userId})}),nd(this,Pc).add("audioInputAdded",e=>{this.emit(Ki.DEVICE_CHANGED,{type:"microphone",action:"add",device:e})}).add("audioInputRemoved",e=>{this.emit(Ki.DEVICE_CHANGED,{type:"microphone",action:"remove",device:e})}).add("videoInputAdded",e=>{this.emit(Ki.DEVICE_CHANGED,{type:"camera",action:"add",device:e})}).add("videoInputRemoved",e=>{this.emit(Ki.DEVICE_CHANGED,{type:"camera",action:"remove",device:e})}).add("audioOutputAdded",e=>WA(this,null,function*(){if(this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),Xl&&Xl.deviceId===C0){let o=(yield HM()).find(a=>a.deviceId===C0);o&&Xl.groupId!==o.groupId&&(Xl=o,this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",e=>WA(this,null,function*(){this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let o=(yield HM())[0];if(!o||!Xl||Xl.groupId===o.groupId)return;let a=Xl.deviceId===e.deviceId,l=Xl.deviceId===C0&&Xl.deviceId===o.deviceId;(a||l)&&(Xl=o,this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),nd(this,w1).add("permission-state-change",e=>{this.emit(Ki.PERMISSION_STATE_CHANGE,e)}),this.room.enableSEI&&this.on(Ki.SEI_MESSAGE,e=>{var o;let a=(o=this.room.remotePublishedUserMap.get(e.userId))==null?void 0:o.remoteVideoTrack;a&&a.updateAlphaRenderInfo(e)})}getNetworkTime(){return Of()}use(e){let o,a;return"plugin"in e?(o=e.plugin,a=e.assetsPath):o=e,o.Name==="Chorus"&&(this.room.enableChorus=!0),this._use(o,a)}_use(e,o){let a=this._plugins.get(e.Name);if(a)return this._log.warn("duplicate install plugin",e.Name),a;let l=new e(jiA.call(this,{TRTC:gm,room:this._room,assetsPath:o,errorModule:{RtcError:_o,ErrorCode:wo,CoreErrorCode:Ct,ErrorCodeDictionary:h1}}));return this._plugins.set(e.Name,l),l.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),l}enterRoom(e){return WA(this,null,function*(){var o,a;this.enterRoomParams=e;let{scene:l="rtc",enableAutoPlayDialog:d=!0,autoReceiveAudio:h=!0,autoReceiveVideo:y=!1}=e;e.proxy&&(this._room.setProxyServer(e.proxy),!Vn(e.proxy)&&e.proxy.turnServer&&((a=(o=this._room).setTurnServer)==null||a.call(o,e.proxy.turnServer,e.proxy.iceTransportPolicy))),this._room.enableAutoPlayDialog=d,this._room.autoReceiveAudio=h,this._room.autoReceiveVideo=y,Nr(e.preferHW)&&(this._room.preferHW=e.preferHW),e.playoutDelay&&(this._room.playoutDelay=e.playoutDelay),e.jitterBufferDelay&&(this._room.jitterBufferDelay=e.jitterBufferDelay);let S={sdkAppId:e.sdkAppId,userId:e.userId,userSig:e.userSig,privateMapKey:e.privateMapKey||null,latencyLevel:e.latencyLevel,role:e.role==="audience"?21:20,roomId:e.roomId||0,strRoomId:e.strRoomId||"",businessInfo:e.businessInfo||null,streamId:null,userDefineRecordId:e.userDefineRecordId||null,enableDataChannel:this._plugins.has("RealtimeTranscriber"),frameWorkType:e.frameWorkType,component:e.component,language:e.language,priority:e.priority,useVp8:e.useVp8,useH265:e.useH265||!1,keepAlive:e.keepAlive};e.strRoomId&&!e.roomId?this._room.useStringRoomId=!0:this._room.useStringRoomId=!1,yield this._room.join(S,l,gm.frameWorkType),this._checkTrackToPublish(),xz.start()})}exitRoom(){return WA(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return WA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(o){if(!(o instanceof Ux)||o.code!==Ct.API_CALL_TIMEOUT&&o.code!==Ct.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===Ct.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return WA(this,null,function*(){yield this.exitRoom();let o=fi(fi({},this.enterRoomParams),e);yield this.enterRoom(o)})}_clearRemoteTracks(){new Set([...this._remoteAudioConfigMap.keys(),...this._remoteAudioMuteMap.keys()]).forEach(e=>{this._stopRemoteAudio({userId:e}).catch(()=>{})}),[...this._remoteVideoConfigMap.keys()].forEach(e=>{let o=e.includes("main")?"main":"sub",a=e.split("_".concat(o))[0];a&&this._stopRemoteVideo({userId:a,streamType:o}).catch(()=>{})}),this._remoteVideoConfigMap.clear(),this._remoteAudioConfigMap.clear(),this._remoteAudioMuteMap.clear(),function(e){let o=p_.get(e);o&&(o.forEach(a=>clearTimeout(a)),p_.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{Ln(e.remoteAudioTrack),Ln(e.remoteVideoTrack),Ln(e.remoteAuxiliaryTrack)})}switchRole(e,o){return WA(this,null,function*(){o!=null&&o.privateMapKey&&(this._room.privateMapKey=o.privateMapKey),o!=null&&o.latencyLevel&&(this._room.latencyLevel=o.latencyLevel),yield this._room.switchRole(e),e==="anchor"&&this._checkTrackToPublish()})}destroy(){this._plugins.forEach(e=>{var o;return(o=e.destroy)==null?void 0:o.call(e)}),this._plugins.clear(),Ln(this),this.removeAllListeners(),this._room.destroy(),mL.delete(this),mL.size===0&&xz.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),F.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return WA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0};return function*(){if(e._localAudioTrack)return void e._log.warn("local audio is already started");let{publish:a=!0,mute:l,muteKeepVolumeDetection:d,option:h}=o,y=new jM(e._room.audioManager),S={},k={muted:!0};h&&(Ke(h.microphoneId)?Ke(h.audioTrack)||(S.customSource=h.audioTrack):S.deviceId=h.microphoneId,h&&kn(h.captureVolume)&&y.setCaptureVolume(h.captureVolume),Ke(h.profile)||(Vn(h.profile)?Rp[h.profile]&&y.setProfile(Rp[h.profile]):y.setProfile(h.profile)),kn(h.earMonitorVolume)&&(k.muted=!(h.earMonitorVolume>0),k.volume=h.earMonitorVolume),Ke(h.echoCancellation)||(y.profile.echoCancellation=h.echoCancellation),Ke(h.noiseSuppression)||(y.profile.noiseSuppression=h.noiseSuppression),Ke(h.autoGainControl)||(y.profile.autoGainControl=h.autoGainControl),Nr(e._enableAutoSwitchWhenRecapturing)&&(y.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),y.on("5",V=>{e.emit(Ki.ERROR,new _o({code:wo.DEVICE_ERROR,extraCode:5309,messageParams:{error:V}}))}),y.on("2",V=>{e.emit(Ki.DEVICE_CHANGED,{type:"microphone",action:"active",device:V})}),y.on("4",V=>{let J;V.error&&(J=_o.convertFrom(V.error)),e.emit(Ki.PUBLISH_STATE_CHANGED,po(fi({},V),{error:J}))}),y.on("6",()=>{}),e._listenOutputTrackChanged(y),e._speakerId&&y.setAudioOutput(e._speakerId),yield y.capture(S),Ke(l)||y.setMute(l,d),nd(y,y).add("player-state-changed",V=>{e.emit(Ki.AUDIO_PLAY_STATE_CHANGED,po(fi({},V),{userId:""}))}),a&&e._room.isJoined&&e._room.publish(y).catch(()=>{}),e._localAudioTrack=y,e._room.capturedLocalMainAudioTrack=y,e._localAudioConfig=po(fi({},o),{publish:a}),yield e._updateAudioPlayOption({playOption:k,track:y}),F.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return WA(this,null,function*(){if(!this._localAudioTrack||!this._localAudioConfig)return;let{publish:o,mute:a,muteKeepVolumeDetection:l,option:d}=e,h={};d&&(d.microphoneId?yield this._localAudioTrack.switchDevice(d.microphoneId):Ke(d.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(d.audioTrack)),Ke(d.captureVolume)||this._localAudioTrack.setCaptureVolume(d.captureVolume),Ke(d.earMonitorVolume)||(h.muted=!(d.earMonitorVolume>0),h.volume=d.earMonitorVolume),yield this._localAudioTrack.update3A(d)),this._room.isJoined&&!Ke(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),Ke(a)||this._localAudioTrack.setMute(a,l),yield this._updateAudioPlayOption({playOption:h,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Xh(this._localAudioConfig,e)})}stopLocalAudio(){return WA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),F.emit("114",{userId:"",room:this.room}),this._localAudioTrack.stop(),this._localAudioTrack.close(),this._room.audioManager.removeInput(this._localAudioTrack),Ln(this._localAudioTrack),this._localAudioTrack=null,this._localAudioConfig=null,delete this._room.capturedLocalMainAudioTrack)})}startLocalVideo(){return WA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null,capture:!0};return function*(){var a,l,d;if(e._localVideoTrack)return void e._log.warn("local video is already started");let{view:h,publish:y=!0,capture:S=!0,mute:k,option:V,forcePublish:J=!1}=o,cA=y||J,CA=S,MA=new BQ(e._room.videoManager),ie={},pe={};if(V&&(Nr(V.avoidCropping)&&(MA.avoidCropping=V.avoidCropping),V.cameraId?ie.deviceId=V.cameraId:Ke(V.useFrontCamera)?Ke(V.videoTrack)||(ie.customSource=V.videoTrack):ie.facingMode=V.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT,Ke(V.retryWhenExactFailed)||(ie.retryWhenExactFailed=V.retryWhenExactFailed),V.qosPreference&&(ie.contentHint=B1(V.qosPreference)),Ke(V.profile)||(Vn(V.profile)?FC[V.profile]&&MA.setProfile(FC[V.profile]):MA.setProfile(V.profile)),Ke(V.fillMode)||(pe.objectFit=V.fillMode),Ke(V.mirror)||(pe.mirror=V.mirror),Ke(V.small)||(Ke(V.smallMode)||(e._room.smallMode=V.smallMode),Nr(V.small)&&V.small===!1?MA.stopSmall():MA.updateSmallConfig(Q1(V.small,!0))),Ke(V.rotation)||MA.setRotation(V.rotation),Nr(e._enableAutoSwitchWhenRecapturing)&&(MA.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),MA.once("first-video-frame",qe=>{e.emit(Ki.FIRST_VIDEO_FRAME,po(fi({},qe),{streamType:eC(qe.streamType)}))}),MA.on("5",qe=>{e.emit(Ki.ERROR,new _o({code:wo.DEVICE_ERROR,extraCode:5308,messageParams:{error:qe}}))}),MA.on("2",qe=>{e.emit(Ki.DEVICE_CHANGED,{type:"camera",action:"active",device:qe})}),MA.on("4",qe=>{let we;qe.error&&(we=_o.convertFrom(qe.error)),e.emit(Ki.PUBLISH_STATE_CHANGED,po(fi({},qe),{error:we}))}),MA.on("6",()=>{}),e._listenOutputTrackChanged(MA),ie.customSource&&Gp(ie.customSource)?(MA.setOutputMediaStreamTrack(ie.customSource),CA=!1):CA?yield MA.capture(ie):(a=MA.manager)==null||a.changeInput(MA),Ke(k)||(yield MA.setMute(k)),nd(MA,MA).add("player-state-changed",qe=>{e.emit(Ki.VIDEO_PLAY_STATE_CHANGED,po(fi({},qe),{userId:"",streamType:"main"}))}).add("video-size-changed",qe=>{e.emit(Ki.VIDEO_SIZE_CHANGED,po(fi({},qe),{streamType:eC(qe.streamType)}))}),cA){let qe=e._localScreenTrack&&((l=e._localScreenConfig)==null?void 0:l.publish)&&e._localScreenConfig.streamType==="main";e._room.isJoined?!qe||J?(e._room.publish(MA).catch(()=>{}),((d=e._localScreenConfig)==null?void 0:d.streamType)==="main"&&e._localScreenConfig&&(e._localScreenConfig.publish=!1)):(cA=!1,e._log.warn("main stream is already published, local video track will not publish")):qe&&(cA=!1)}e._localVideoTrack=MA,e._room.capturedLocalMainVideoTrack=MA,e._localVideoConfig=po(fi({},o),{view:h,publish:cA,capture:CA}),yield e._updateVideoPlayOption({view:h,playOption:pe,track:MA})}()})}updateLocalVideo(e){return WA(this,null,function*(){var o,a,l,d,h,y,S;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:k,publish:V=!0,mute:J,capture:cA,option:CA,forcePublish:MA=!1}=e,ie=V||MA,pe=cA,qe={};if(!this._localVideoConfig.capture&&Gp((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(CA!=null&&CA.cameraId||CA!=null&&CA.videoTrack)&&this._localVideoTrack.outMediaTrack!==CA?.videoTrack&&(pe=!0),this._localVideoConfig.capture)pe!==!1?CA!=null&&CA.cameraId?yield this._localVideoTrack.switchDevice(CA?.cameraId):Ke(CA?.useFrontCamera)?Ke(CA?.videoTrack)||(Gp(CA?.videoTrack)?CA?.videoTrack!==((a=this.localVideoTrack)==null?void 0:a.outMediaTrack)&&(yield this._localVideoTrack.setOutputMediaStreamTrack(CA?.videoTrack)):yield this._localVideoTrack.setInputMediaStreamTrack(CA?.videoTrack)):yield this._localVideoTrack.switchDevice(CA!=null&&CA.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(pe){let we={};we.deviceId=CA?.cameraId||((l=this._localVideoConfig.option)==null?void 0:l.cameraId),we.facingMode=CA!=null&&CA.useFrontCamera||(d=this._localVideoConfig.option)!=null&&d.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT,we.customSource=CA!=null&&CA.videoTrack||!we.deviceId?(h=this._localVideoConfig.option)==null?void 0:h.videoTrack:void 0,yield this._localVideoTrack.capture(we)}CA&&(Ke(CA.profile)||(Vn(CA.profile)?FC[CA.profile]&&this._localVideoTrack.setProfile(FC[CA.profile]):this._localVideoTrack.setProfile(CA.profile),(!CA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(CA.cameraId||CA.useFrontCamera?YA.FACING_MODE_USER:YA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),Ke(CA.fillMode)||(qe.objectFit=CA.fillMode),Ke(CA.mirror)||(qe.mirror=CA.mirror),Ke(CA.rotation)||this._localVideoTrack.setRotation(CA.rotation),CA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(B1(CA.qosPreference)),Ke(CA.small)||(Nr(CA.small)&&!CA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(Q1(CA.small,!0)))),this._room.isJoined&&Ke(ie)&&this._localVideoConfig.publish&&pe&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&((ie??this._localVideoConfig.publish)||MA?this._localScreenTrack&&((y=this._localScreenConfig)!=null&&y.publish)&&this._localScreenConfig.streamType==="main"&&!MA?(ie=!1,this._log.warn("main stream is already published, local video track will not publish")):(this._room.publish(this._localVideoTrack).catch(()=>{}),((S=this._localScreenConfig)==null?void 0:S.streamType)==="main"&&this._localScreenConfig&&(this._localScreenConfig.publish=!1)):this._room.unpublish(this._localVideoTrack).catch(()=>{})),Ke(J)||(yield this._localVideoTrack.setMute(J)),yield this._updateVideoPlayOption({view:k,playOption:qe,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Xh(this._localVideoConfig,po(fi({},e),{publish:ie,capture:pe}))})}stopLocalVideo(){return WA(this,null,function*(){var e;this._localVideoTrack&&(this._room.isJoined&&(e=this._localVideoConfig)!=null&&e.publish&&(yield this._room.unpublish(this._localVideoTrack).catch(()=>{})),this._localVideoTrack.stop(),this._localVideoTrack.close(),Ln(this._localVideoTrack),this._localVideoTrack=null,delete this._room.capturedLocalMainVideoTrack,this._localVideoConfig=null)})}startScreenShare(){return WA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{publish:!0,view:null};return function*(){var a,l,d;if(e._localScreenTrack)return void e._log.warn("screen share is already started");let{view:h=null,publish:y=!0,muteSystemAudio:S,option:k}=o,V=y,J=new WM(e._room.videoManager);J.on("4",pe=>{let qe;pe.error&&(qe=_o.convertFrom(pe.error)),e.emit(Ki.PUBLISH_STATE_CHANGED,po(fi({},pe),{error:qe}))}),J.once("first-video-frame",pe=>{e.emit(Ki.FIRST_VIDEO_FRAME,po(fi({},pe),{streamType:eC(pe.streamType)}))}),e._listenOutputTrackChanged(J),o.streamType==="main"&&(J.mediaType=4);let cA=null,CA={},MA={};k&&(Ke(k.profile)||(Vn(k.profile)?Tb[k.profile]&&J.setProfile(Tb[k.profile]):J.setProfile(k.profile)),k.systemAudio&&(CA.systemAudio=!0,CA.echoCancellation=k.echoCancellation,CA.noiseSuppression=k.noiseSuppression,CA.autoGainControl=k.autoGainControl),Ke(k.fillMode)||(MA.objectFit=k.fillMode),k.videoTrack&&(CA.videoTrack=k.videoTrack),k.audioTrack&&(CA.audioTrack=k.audioTrack),k.captureElement&&(CA.captureElement=k.captureElement),k.preferDisplaySurface&&(CA.preferDisplaySurface=k.preferDisplaySurface),k.qosPreference&&(CA.contentHint=B1(k.qosPreference)));let ie=yield J.capture(CA);if(J.mediaTrack.addEventListener(YA.ENDED,()=>{e._stopScreenShare(),e.emit(Ki.SCREEN_SHARE_STOPPED)}),ie.getAudioTracks()[0]){cA=new Ij(e._room.audioManager);let pe=ie.getAudioTracks()[0];(a=o.option)!=null&&a.systemAudio&&!((l=o.option)!=null&&l.audioTrack)&&(cA.sourceTrack=pe),yield cA.setInputMediaStreamTrack(pe),Nr(S)&&cA.mediaTrack&&(cA.mediaTrack.enabled=!S),e._speakerId&&cA.setAudioOutput(e._speakerId)}if(nd(J,J).add("player-state-changed",pe=>{e.emit(Ki.VIDEO_PLAY_STATE_CHANGED,po(fi({},pe),{userId:"",streamType:"sub"}))}),V){let pe=e._localVideoTrack&&((d=e._localVideoConfig)==null?void 0:d.publish),qe=!(o.streamType==="main"&&pe);e._room.isJoined?(qe?e._room.publish(J).catch(()=>{}):(V=!1,e._log.warn("main stream is already published, screen share main will not publish")),cA&&(e._checkScreenAudioEchoCancellation(J,cA),e._room.publish(cA).catch(()=>{}))):qe||(V=!1)}e._localScreenTrack=J,e._room.capturedLocalAuxVideoTrack=J,e._localScreenAudioTrack=cA,e._localScreenConfig=po(fi({},o),{view:h,publish:V}),yield e._updateVideoPlayOption({view:h,playOption:MA,track:J})}()})}updateScreenShare(e){return WA(this,null,function*(){var o,a;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:l,publish:d,muteSystemAudio:h,option:y}=e,S=d,k={};if(y){if(Ke(y.fillMode)||(k.objectFit=y.fillMode),y.qosPreference){let V=B1(y.qosPreference);this._localScreenTrack.setContentHint(V)}y.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(y.videoTrack),y.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(y.audioTrack)}if(this._room.isJoined&&!Ke(S)){if(S&&!this._localScreenConfig.publish){let V=this._localVideoTrack&&((o=this._localVideoConfig)==null?void 0:o.publish);this._localScreenConfig.streamType==="main"&&V?(S=!1,this._log.warn("main stream is already published, screen share main will not publish")):this._room.publish(this._localScreenTrack).catch(()=>{}),this._localScreenAudioTrack&&this._room.publish(this._localScreenAudioTrack).catch(()=>{})}if(this._localScreenConfig.publish&&!S){let V=[this._localScreenTrack];this._localScreenAudioTrack&&V.push(this._localScreenAudioTrack),V.forEach(J=>this._room.unpublish(J).catch(()=>{}))}}(a=this._localScreenAudioTrack)!=null&&a.mediaTrack&&Nr(h)&&(this._localScreenAudioTrack.mediaTrack.enabled=!h),yield this._updateVideoPlayOption({view:l,playOption:k,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Xh(this._localScreenConfig,po(fi({},e),{publish:S}))})}stopScreenShare(){return WA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return WA(this,null,function*(){let{view:o,userId:a,streamType:l,option:d}=e,h="".concat(a,"_").concat(l);if(this._remoteVideoConfigMap.has(h))return void this._log.warn("remote video has already started. userId:".concat(a,", streamType:").concat(l));let y=this._room.remotePublishedUserMap.get(a);if(!y)return;let S={},k=l==="main"?y.remoteVideoTrack:y.remoteAuxiliaryTrack,V=this._bindRemoteVideoTrackEvents(k);this._listenOutputTrackChanged(k),d&&(Ke(d.fillMode)||(S.objectFit=d.fillMode),Ke(d.mirror)||(S.mirror=d.mirror),Ke(d.poster)||(S.poster=d.poster),S.canvasRender=d.canvasRender,l==="main"&&!Ke(d.small)&&(!y.remoteVideoTrack.isSubscribing&&!y.remoteVideoTrack.isSubscribed&&y.remoteVideoTrack.setMediaType(d.small?8:4),this._room.changeType(d.small,k.user)),Ke(d.draggable)||k.setDraggable(d.draggable)),S.isLiveStream=!!this._playbackQualityList.find(J=>J.userId===a&&J.streamType===l),yield this._room.subscribe(k),yield this._enableVideoDecodeFallback(k,l),yield this._updateVideoPlayOption({view:o,playOption:S,track:k}),this._emitTrackEvent(k),this._remoteVideoConfigMap.set(h,{config:e,handlers:V}),d&&!Ke(d.receiveWhenViewVisible)&&this._observeView({remoteTrack:k,view:o,receiveWhenViewVisible:d.receiveWhenViewVisible,viewRoot:d?.viewRoot})})}updateRemoteVideo(e){return WA(this,null,function*(){var o,a;let{view:l,userId:d,streamType:h,option:y,mute:S}=e,k="".concat(d,"_").concat(h),V=this._remoteVideoConfigMap.get(k);if(!V||!this._room.remotePublishedUserMap.has(d))return;let J={};y&&(Ke(y.fillMode)||(J.objectFit=y.fillMode),Ke(y.mirror)||(J.mirror=y.mirror));let cA=null,CA=this._room.remotePublishedUserMap.get(d);if(h==="main"&&CA!=null&&CA.muteState.hasVideo&&(cA=CA.remoteVideoTrack),h==="sub"&&CA!=null&&CA.muteState.hasAuxiliary&&(cA=CA.remoteAuxiliaryTrack),!cA)return;let{config:MA}=V;h==="main"&&y&&!Ke(y.small)&&this._room.changeType(y.small,cA.user),y&&!Ke(y.draggable)&&cA.setDraggable(y.draggable),y&&(Nr(y.pictureInPicture)&&(y.pictureInPicture?yield cA.player.enterPictureInPicture():yield cA.player.exitPictureInPicture()),Nr(y.fullScreen)&&(y.fullScreen?yield cA.player.enterFullscreen():yield cA.player.exitFullscreen())),Nr(S)&&(cA.ignoreUpdatePlayingState=!0,S?(yield cA.player.pause(),yield this.room.unsubscribe(cA)):(yield this.room.subscribe(cA),yield cA.player.resume(!0))),yield this._updateVideoPlayOption({view:l,playOption:J,track:cA,prevConfig:MA}),Xh(MA,e);let ie=Ke(y?.receiveWhenViewVisible)?(o=MA.option)==null?void 0:o.receiveWhenViewVisible:y.receiveWhenViewVisible,pe=Ke(l)?MA.view:l,qe=Ke(y?.viewRoot)?(a=MA.option)==null?void 0:a.viewRoot:y.viewRoot;this._observeView({remoteTrack:cA,view:pe,receiveWhenViewVisible:ie,viewRoot:qe})})}stopRemoteVideo(e){return WA(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return WA(this,null,function*(){let a=[],l=this._room.remotePublishedUserMap.get(e.userId);if(l){let{muteState:d,remoteVideoTrack:h,remoteAuxiliaryTrack:y}=l;e.streamType==="main"&&(h.stop(),d.hasVideo&&a.push(h)),e.streamType==="sub"&&(y.stop(),d.hasAuxiliary&&a.push(y))}for(let d of a)o&&(delete d.ignoreUpdatePlayingState,yield this._room.unsubscribe(d),this._mediaTrackMap.delete(d.outMediaTrack));this._removeRemoteVideoConfig(e.userId,e.streamType)})}_removeRemoteVideoConfig(e,o){let a="".concat(e,"_").concat(o),l=this._remoteVideoConfigMap.get(a);if(l&&(l.observer&&l.observer.disconnect(),l.handlers)){let d=this._room.remotePublishedUserMap.get(e);if(d){let h=o==="main"?d.remoteVideoTrack:d.remoteAuxiliaryTrack;this._unbindRemoteVideoTrackEvents(h,l.handlers)}}this._remoteVideoConfigMap.delete(a)}_bindRemoteVideoTrackEvents(e){let o={onEnterPIP:()=>WA(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Ki.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Ki.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Ki.FULL_SCREEN_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Ki.FULL_SCREEN_STATE_CHANGED,{streamType:eC(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Ki.ERROR,new _o({code:wo.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:a=>{this.emit(Ki.VIDEO_SIZE_CHANGED,po(fi({},a),{streamType:eC(a.streamType)}))}};return e.player.on(yo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.on(yo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.on(yo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.on(yo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.on("decode-failed",o.onDecodeFailed),e.on("video-size-changed",o.onVideoSizeChanged),o}_unbindRemoteVideoTrackEvents(e,o){e.player.off(yo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.off(yo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.off(yo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.off(yo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.off("decode-failed",o.onDecodeFailed),e.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(e,o){return WA(this,null,function*(){this._remoteAudioMuteMap.set(e,o);try{if(e==="*")if(o)yield this._stopRemoteAudio({userId:e});else{let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)l.muteState.hasAudio&&!this._remoteAudioConfigMap.has(l.userId)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:l.userId}))}else o?yield this._stopRemoteAudio({userId:e}):!this._remoteAudioConfigMap.has(e)&&this.room.isJoined&&(yield this._startRemoteAudio({userId:e}))}catch(a){throw a.code!==wo.OPERATION_ABORT&&this._remoteAudioMuteMap.delete(e),a}})}setRemoteAudioVolume(e,o){if(e==="*"){this._remoteAudioVolumeMap.set("*",o),this._remoteAudioVolumeMap.forEach((l,d)=>this._remoteAudioVolumeMap.set(d,o));let a=[...this._room.remotePublishedUserMap.values()];for(let l of a)this._remoteAudioVolumeMap.set(l.userId,o),l.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:l.remoteAudioTrack})}else if(e){let a=this._room.remotePublishedUserMap.get(e);this._remoteAudioVolumeMap.set(e,o),a&&a.remoteAudioTrack.isSubscribed&&this._updateAudioPlayOption({playOption:{volume:o},track:a.remoteAudioTrack})}}startPlugin(e,o){return WA(this,null,function*(){return e.start(o)})}updatePlugin(e,o){return WA(this,null,function*(){return e.update(o)})}stopPlugin(e,o){return WA(this,null,function*(){return e.stop(o)})}enableAudioVolumeEvaluation(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this._room.enableAudioVolumeEvaluation(e,o)}on(e,o,a){if(this.listeners(e).includes(o))return this;if(this._log.debug("on",e),super.on(e,o,a),this._eventListened.add(e),this.listeners(Ki.AUDIO_FRAME).length>0){let{audioFrameEventConfigMap:l}=this.room.audioManager;l.get("")||l.set("",{enable:!0}),this._localAudioTrack&&this.room.audioManager.handleLocalTrackStarted({userId:"",room:this.room})}return e==="realtime-transcriber-message"&&this._room.subscribeDataChannel(),this}emit(e){for(var o=arguments.length,a=new Array(o>1?o-1:0),l=1;l{d?.abort("off")}),l.clear()}return this}getAudioTrack(){let e,o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},a=null,l="main",d=!1;if(Vn(o)?e=o:(e=o.userId,d=o.processed===!0,o.streamType&&(l=o.streamType)),e){let h=this._room.remotePublishedUserMap.get(e);h&&(a=h.remoteAudioTrack)}else a=l==="sub"?this._localScreenAudioTrack:this._localAudioTrack;return a?d&&a.outMediaTrack&&a.outMediaTrack!==a.mediaTrack?a.outMediaTrack.clone():a.mediaTrack:null}getVideoTrack(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{userId:"",streamType:"main"},{userId:o="",streamType:a="main",processed:l=!1}=e,d=null;if(o==="")a==="main"&&this._localVideoTrack&&(d=this._localVideoTrack),a==="sub"&&this._localScreenTrack&&(d=this._localScreenTrack);else{let h=this._room.remotePublishedUserMap.get(o);h&&(d=a==="main"?h.remoteVideoTrack:h.remoteAuxiliaryTrack)}return d?l&&d.outMediaTrack&&d.outMediaTrack!==d.mediaTrack?d.outMediaTrack.clone():d.mediaTrack:null}getVideoSnapshot(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{userId:o,streamType:a="main"}=e;if(o){let l=this._room.remotePublishedUserMap.get(o);if(a==="main"&&l!=null&&l.muteState.hasVideo)return l.remoteVideoTrack.getVideoFrame();if(a==="sub"&&l!=null&&l.muteState.hasAuxiliary)return l.remoteAuxiliaryTrack.getVideoFrame()}else{if(a==="main"&&this._localVideoTrack)return this._localVideoTrack.getVideoFrame();if(a==="sub"&&this._localScreenTrack)return this._localScreenTrack.getVideoFrame()}return""}_setCurrentSpeaker(e){var o,a;this._speakerId=e,(o=this._localAudioTrack)==null||o.setAudioOutput(e),(a=this._localScreenAudioTrack)==null||a.setAudioOutput(e),this._room.remotePublishedUserMap.forEach(l=>l.remoteAudioTrack.setAudioOutput(e))}setCurrentSpeaker(e){return WA(this,null,function*(){(yield HM()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),Xl=o)}),this._log.warn('the "setCurrentSpeaker" method of the instance will be deprecated in the future, please use "TRTC.setCurrentSpeaker" instead. For more information, please visit: '.concat(Wh,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return WA(this,null,function*(){var o;let{userId:a}=e;if(this._remoteAudioConfigMap.has(a))return void this._log.warn("remote audio has already started. userId:".concat(a));let l=this._room.remotePublishedUserMap.get(a);if(!l)return;let d={},h=l.remoteAudioTrack;h.on("decode-failed",y=>{this.emit(Ki.ERROR,new _o({code:wo.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(h),this._speakerId&&h.setAudioOutput(this._speakerId);try{let y=(o=this._remoteAudioVolumeMap.get(a))!=null?o:this._remoteAudioVolumeMap.get("*"),S=kn(y)?y:100;d.volume=S,this._remoteAudioConfigMap.set(a,e),yield this._room.subscribe(h),ma(la(h,"decode-failed"),dE(la(h,Zs.INIT)),Bl(()=>{this.startPlugin(Hz.Name,{track:h,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:d,track:h}),F.emit("115",{userId:a,room:this.room}),h.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:h.outMediaTrack,refId:"ra-".concat(a)})}catch(y){throw this._remoteAudioConfigMap.delete(a),y}this._emitTrackEvent(h)})}_stopRemoteAudio(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return WA(this,null,function*(){let a=this._room.remotePublishedUserMap.get(e.userId);a&&(a.remoteAudioTrack.stop(),a.muteState.hasAudio&&o&&(yield this._room.unsubscribe(a.remoteAudioTrack)),this._mediaTrackMap.delete(a.remoteAudioTrack.outMediaTrack)),this._remoteAudioConfigMap.delete("".concat(e.userId)),F.emit("116",{userId:e.userId,room:this.room}),this.room.audioManager.updateAudioReference({type:"remove",refId:"ra-".concat(e.userId)})})}_enableVideoDecodeFallback(e,o){let a,l=this._room.videoDecodeFallbackType;l&&this._plugins.has("TRTCVideoDecoder")&&(e.log.debug("remote video will fall back when decode failed",e.id),ma(la(e,"decode-failed"),dE(la(e,Zs.INIT)),sj(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:l})}),l1(la(e,"decode-downgrade-state-changed")),Bl(d=>{a=d.state,this.emit(Ki.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,po(fi({},d),{streamType:o,userId:e.userId}))},d=>{e.log.error("fallback",d)},()=>{a==="STARTED"&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return WA(this,arguments,function(o){let{view:a,playOption:l,track:d,prevConfig:h}=o;return function*(){if(d.setMirror(l.mirror),Ke(a)&&h&&h.view&&!R0(l)){let y=gM(h.view);y.length>0&&(yield d.play(y,l))}if(!Ke(a)){let y=gM(a);y.length>0?yield d.play(y,l):d.stop()}}()})}_updateAudioPlayOption(e){return WA(this,arguments,function(o){var a=this;let{playOption:l={},track:d,prevConfig:h}=o;return function*(){if(!d.isPlayCalled)try{yield d.play(null,l)}catch{}if(Ke(l.muted)||d.setPlayerMute(l.muted),Ke(l.volume)||d.setAudioVolume(l.volume/100),d instanceof jM&&d.mediaTrack){let y=l.muted===!1&&!Ke(l.volume)&&l.volume>0?"add":"remove";a.room.audioManager.updateAudioReference({type:y,audioReference:d.mediaTrack,refId:"em"})}else if(d instanceof d1){let y=l.muted?0:l.volume;if(Ke(y))return;a.room.audioManager.updateAudioReference({type:"updateVolume",refId:"ra-".concat(d.userId),volume:l.volume})}}()})}_listenOutputTrackChanged(e){e.listeners("output-media-track-changed").length===0&&e.on("output-media-track-changed",()=>this._emitTrackEvent(e,!1))}_emitTrackEvent(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],a=e.isRemote?e.userId:"";e.outMediaTrack&&(o&&this._mediaTrackMap.get(e.outMediaTrack)===a||(this._mediaTrackMap.set(e.outMediaTrack,a),this.emit(Ki.TRACK,{userId:a,streamType:eC(e.streamType),track:e.outMediaTrack,sourceTrack:e.mediaTrack})))}_checkTrackToPublish(){var e,o,a;let l=[];if((e=this._localAudioConfig)!=null&&e.publish&&this._localAudioTrack&&l.push(this._localAudioTrack),(o=this._localVideoConfig)!=null&&o.publish&&this._localVideoTrack&&l.push(this._localVideoTrack),(a=this._localScreenConfig)!=null&&a.publish&&(this._localScreenTrack&&l.push(this._localScreenTrack),this._localScreenAudioTrack&&l.push(this._localScreenAudioTrack),this._checkScreenAudioEchoCancellation(this._localScreenTrack,this._localScreenAudioTrack)),l.length!==0)return Promise.all(l.map(d=>this._room.publish(d).catch(()=>{})))}_observeView(e){let{remoteTrack:o,view:a,receiveWhenViewVisible:l,viewRoot:d}=e;if(Ke(a)||Ke(l))return;let h=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(eC(o.streamType)));if(!h)return;let y=h.observer||void 0;if(a===null||wa(a)&&a.length===0||!l)return y?.disconnect(),void(o.isSubscribed||(this._log.info("_observeView observer disconnect, resubscribe",o.userId,o.strMediaType),this._room.subscribe(o).catch(()=>{})));let S=h.visibleViewMap||new Map,k=-1;(!y||y.root!==d)&&(y?.disconnect(),S.clear(),y=new IntersectionObserver(J=>{J.forEach(cA=>{S.set(cA.target,cA.isIntersecting),o.log.info("view ".concat(cA.target.id," is").concat(cA.isIntersecting?"":" not"," visible"))}),clearTimeout(k),k=window.setTimeout(()=>{[...S.values()].find(cA=>cA)?o.isSubscribed||this._room.subscribe(o).catch(()=>{}):o.isSubscribed&&this._room.unsubscribe(o).catch(()=>{})},200)},{root:d}));let V=new Set(gM(a));S.forEach((J,cA)=>{V.has(cA)||(y.unobserve(cA),S.delete(cA))}),V.forEach(J=>{S.set(J,!0),y.observe(J)}),y.takeRecords().forEach(J=>{S.set(J.target,J.isIntersecting)}),h.visibleViewMap=S,h.observer=y}_exitRoom(){return WA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return WA(this,null,function*(){var e,o;if(this._localScreenTrack){if(this._room.isJoined){let a=[];(e=this._localScreenConfig)!=null&&e.publish&&a.push(this._localScreenTrack),this._localScreenAudioTrack&&a.push(this._localScreenAudioTrack),yield Promise.all(a.map(l=>this._room.unpublish(l).catch(()=>{})))}this._localScreenTrack.stop(),this._localScreenTrack.close(),this._localScreenAudioTrack&&(((o=this._localScreenAudioTrack.trackSettings)==null?void 0:o.echoCancellation)===!1&&this.stopPlugin("AudioProcessor"),this._localScreenAudioTrack.stop(),this._localScreenAudioTrack.close(),this._room.audioManager.removeInput(this._localScreenAudioTrack),this._localScreenAudioTrack=null),Ln(this._localScreenTrack),this._localScreenTrack=null,delete this._room.capturedLocalAuxVideoTrack,this._localScreenConfig=null}})}_checkScreenAudioEchoCancellation(e,o){return WA(this,null,function*(){var a,l;if(!e||!o)return;let d=(a=e.trackSettings)==null?void 0:a.displaySurface;if(((l=o.trackSettings)==null?void 0:l.echoCancellation)===!1&&(d==="monitor"||d==="browser"&&e.isShareCurrentTab)){this._log.warn("echoCancellation of screen audio track is disable. Try starting audioProcessor plugin");try{yield this.startPlugin("AudioProcessor",{sdkAppId:Number(this.room.sdkAppId),userId:this._room.userId,userSig:this.room.userSig,isScreenAudioNeedAudioProcess:!0,isLocalAudioNeedAudioProcess:!1})}catch(h){this._log.warn("start audioProcessor plugin failed: ",h)}}})}_onLocalTrackCaptured(e){let{track:o}=e;o.kind==="audio"&&(!Xl||oL(Xl))&&(this._initActiveSpeaker(),F.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return WA(this,null,function*(){if(Xl&&!oL(Xl))this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:Xl});else{let e=yield HM();e[0]&&!oL(e[0])?(Xl=e[0],this.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):F.on("102",this._onLocalTrackCaptured,this)}})}_onAudioAvailable(e){let{userId:o}=e,a=this._remoteAudioMuteMap.has(o)?this._remoteAudioMuteMap.get(o):this._remoteAudioMuteMap.get("*");(a===!1||this._room.autoReceiveAudio&&!a)&&this._doStartRemoteAudio({userId:o}).catch(()=>{})}_onVideoAvailable(e){let{userId:o,streamType:a}=e;if(!this._room.autoReceiveVideo)return;let l=this._room.remotePublishedUserMap.get(o);if(l){let d=a==="main"?l.remoteVideoTrack:l.remoteAuxiliaryTrack,h=[d];this._room.autoReceiveAudio&&l.remoteAudioTrack.isAvailable&&h.push(l.remoteAudioTrack),this._room.subscribe(...h).then(()=>{this._emitTrackEvent(d)}).catch(()=>{})}}_onAudioUnavailable(e){let{userId:o,muteState:a}=e;a.hasAudio&&a.audioMuted||this._stopRemoteAudio({userId:o},!1).catch(()=>{})}_onVideoUnavailable(e){let{userId:o,streamType:a}=e;this._stopRemoteVideo({userId:o,streamType:a},!1).catch(()=>{})}_onDataChannelAvailable(){if(this.listeners("realtime-transcriber-message").length>0)return this._room.subscribeDataChannel()}sendSEIMessage(e,o){var a;let l=this._plugins.get("SEI");l&&(l.update({buffer:e,options:po(fi({seiPayloadType:243},o),{small:!((a=this._localVideoTrack)==null||!a.small)})}),si.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var o,a;(a=(o=this._room).sendCustomMessage)==null||a.call(o,e),si.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,o){return WA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(o),")")),aoA.call(e,fi({trtcInstance:this},o))})}static setLogLevel(e,o){pA.setLogLevel(e),Ke(o)||(o?pA.enableUploadLog():pA.disableUploadLog())}static isSupported(){return Fk(gm.frameWorkType)}static getPermissions(e){return WA(this,arguments,function(o){let{request:a=!0,types:l=["camera","microphone"]}=o;return function*(){a&&(yield w1.request(l).catch(y=>{var S;return pA.error("getPermissions request failed, error: ".concat((S=y?.message)!=null?S:y))}));let[d,h]=yield Promise.all([w1.get("camera"),w1.get("microphone")]);return{camera:d,microphone:h}}()})}static getCameraList(){return tm(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return em(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getSpeakerList(){return HM(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static setCurrentSpeaker(e){return WA(this,null,function*(){if(Ha&&(e===hL.SPEAKER||e===hL.HEADSET)){let o=yield gm.getMicrophoneList(),a="";return o.forEach(l=>{l.label===e&&(a=l.deviceId)}),a?void mL.forEach(l=>WA(null,null,function*(){l._localAudioTrack&&(yield l.updateLocalAudio({option:{microphoneId:a}}))})):void 0}(yield HM()).forEach(o=>{o.deviceId===e&&(mL.forEach(a=>{a._setCurrentSpeaker(e),a.emit(Ki.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),Xl=o)})})}static _addKVStat(e){let{type:o,key:a,value:l,base:d,useUV:h,version:y,max:S}=e;switch(y&&(AB.version=y),o){case"count":AB.addCount({key:a,useUV:h});break;case"enum":AB.addEnum({key:a,value:l,useUV:h});break;case"number":AB.addNumber({key:a,value:l,split:d,max:S})}}get localVideoTrack(){return this._localVideoTrack}get localScreenTrack(){return this._localScreenTrack}get localScreenAudioTrack(){return this._localScreenAudioTrack}};Y(Ms,"VERSION",Oz),Y(Ms,"_loggerManager",pA),Y(Ms,"EVENT",Ki),Y(Ms,"ERROR_CODE",wo),Y(Ms,"TYPE",hL),Y(Ms,"frameWorkType",30),hi([fa({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],Ms.prototype,"use"),hi([Bu(Zl.TRTC.enterRoom),XM("room",(A,e)=>{let[o]=A,[a]=e;return(o.roomId||o.strRoomId)===(a.roomId||a.strRoomId)&&o.userId===a.userId&&o.sdkAppId===a.sdkAppId}),jr(A=>function(e){return this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),A.call(this,e)}),fa()],Ms.prototype,"enterRoom"),hi([fa()],Ms.prototype,"exitRoom"),hi([Bu(Zl.TRTC.switchRoom),fa(),sL()],Ms.prototype,"switchRoom"),hi([Bu(Zl.TRTC.switchRole),Q_("room",{merge:(A,e)=>e}),fa()],Ms.prototype,"switchRole"),hi([fa()],Ms.prototype,"destroy"),hi([Bu(Zl.TRTC.startLocalAudio),XM("audio",(A,e)=>{let[o]=A,[a]=e;var l,d;return((l=o?.option)==null?void 0:l.microphoneId)===((d=a?.option)==null?void 0:d.microphoneId)}),fa()],Ms.prototype,"startLocalAudio"),hi([Bu(Zl.TRTC.updateLocalAudio),Q_("audio",{debounce:{delay:200,getKey:()=>"".concat(qz,"-localAudio"),isNeedToDebounce:A=>{var e;return!Ke((e=A.option)==null?void 0:e.captureVolume)}}}),fa()],Ms.prototype,"updateLocalAudio"),hi([$M("audio"),fa()],Ms.prototype,"stopLocalAudio"),hi([Bu(Zl.TRTC.startLocalVideo),XM("video",(A,e)=>{let[o]=A,[a]=e;var l,d;return((l=o?.option)==null?void 0:l.cameraId)===((d=a?.option)==null?void 0:d.cameraId)}),fa()],Ms.prototype,"startLocalVideo"),hi([Bu(Zl.TRTC.updateLocalVideo),Q_("video"),fa()],Ms.prototype,"updateLocalVideo"),hi([$M("video"),fa()],Ms.prototype,"stopLocalVideo"),hi([Bu(Zl.TRTC.startScreenShare),XM("screen",()=>!0),fa()],Ms.prototype,"startScreenShare"),hi([Bu(Zl.TRTC.updateScreenShare),Q_("screen"),fa()],Ms.prototype,"updateScreenShare"),hi([fa()],Ms.prototype,"stopScreenShare"),hi([Bu(Zl.TRTC.startRemoteVideo),XM(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ms.prototype,"startRemoteVideo"),hi([Bu(Zl.TRTC.updateRemoteVideo),Q_(A=>"v".concat(A.userId).concat(A.streamType)),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ms.prototype,"updateRemoteVideo"),hi([Bu(Zl.TRTC.stopRemoteVideo),jr(A=>function(e){return WA(this,null,function*(){if(e.userId==="*"){let o=[];return this._room.remotePublishedUserMap.forEach(a=>{this._remoteVideoConfigMap.has("".concat(a.userId,"_main"))&&o.push(this.stopRemoteVideo({streamType:"main",userId:a.userId}).catch(()=>{})),this._remoteVideoConfigMap.has("".concat(a.userId,"_sub"))&&o.push(this.stopRemoteVideo({streamType:"sub",userId:a.userId}).catch(()=>{}))}),Promise.all(o)}return A.call(this,e)})}),fa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ms.prototype,"stopRemoteVideo"),hi([$M(A=>"v".concat(A.userId).concat(A.streamType))],Ms.prototype,"_stopRemoteVideo"),hi([Bu(...Zl.TRTC.muteRemoteAudio),fa({getRemoteId:A=>A})],Ms.prototype,"muteRemoteAudio"),hi([Pz(...Zl.TRTC.setRemoteAudioVolume),function(A,e){return jr((o,a)=>function(){for(var l=arguments.length,d=new Array(l),h=0;h{var J;(J=p_.get(this))==null||J.delete(S)},A);y.set(S,V)}else{clearTimeout(k);let V=window.setTimeout(()=>{var J;o.apply(this,d),(J=p_.get(this))==null||J.delete(S)},A);y.set(S,V)}})}(200,A=>A),fa({getRemoteId:A=>A})],Ms.prototype,"setRemoteAudioVolume"),hi([mj("start"),qM(A=>{var e;return(e=A.afterStart)==null?void 0:e.call(A)}),XM((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e)),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>P2[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],Ms.prototype,"startPlugin"),hi([mj("update"),Q_((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e),{merge:(A,e)=>(Xh(A[1],e[1]),A)}),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>Cy[A.getName()]})],Ms.prototype,"updatePlugin"),hi([mj("stop"),$M((A,e)=>{if(A.disableRandomCall)return null;let o=A.getGroup(e),a=A.getAlias();return o==="*"?new RegExp("".concat(a,".*")):a+o}),fa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>e_[A.getName()]})],Ms.prototype,"stopPlugin"),hi([Pz(...Zl.TRTC.enableAudioVolumeEvaluation)],Ms.prototype,"enableAudioVolumeEvaluation"),hi([fa()],Ms.prototype,"getVideoSnapshot"),hi([fa()],Ms.prototype,"_setCurrentSpeaker"),hi([XM(A=>"a".concat(A.userId),()=>!0)],Ms.prototype,"_startRemoteAudio"),hi([jr(A=>function(e){return WA(this,null,function*(){return e.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(po(fi({},e),{userId:o.userId})).catch(()=>{}))):A.call(this,e)})}),$M(A=>"a".concat(A.userId))],Ms.prototype,"_stopRemoteAudio"),hi([$M("room")],Ms.prototype,"_exitRoom"),hi([$M("screen")],Ms.prototype,"_stopScreenShare"),hi([Bu(...Zl.TRTC.sendSEIMessage),lz({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,e=new Array(A),o=0;oA.data.byteLength})],Ms.prototype,"sendCustomMessage"),hi([fa()],Ms.prototype,"callExperimentalAPI"),hi([Av()],Ms,"create"),hi([Bu(Zl.TRTC.create)],Ms,"_create"),hi([Av()],Ms,"setLogLevel"),hi([Av()],Ms,"isSupported"),hi([Av(),fa()],Ms,"getPermissions"),hi([Av()],Ms,"getCameraList"),hi([Av()],Ms,"getMicrophoneList"),hi([Av()],Ms,"getSpeakerList");var fL=Ms,loA=class{constructor(){Y(this,"_set",new Set),F.on(nA.LEAVE_SUCCESS,this.delete,this),F.on(nA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess,this)}add(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let a=this.getKey(e.userId,o||e.roomId,e.sdkAppId,e.useStringRoomId);this._set.add(a)}delete(A){let{room:e,roomId:o}=A;if(e.scene==="rtc")return;let a=this.getKey(e.userId,e.roomId||o,e.sdkAppId,e.useStringRoomId);this._set.delete(a)}getKey(A,e,o,a){return"".concat(o,"_").concat(e,"_").concat(A,"_").concat(a)}isJoined(A){let{userId:e,roomId:o,sdkAppId:a,room:l}=A;return l.scene!=="rtc"&&this._set.has(this.getKey(e,o,a,l.useStringRoomId))}handleSwitchRoomSuccess(A){let{room:e,currentRoomId:o,targetRoomId:a}=A;e.scene!=="rtc"&&(this._set.delete(this.getKey(e.userId,o,e.sdkAppId,e.useStringRoomId)),this._set.add(this.getKey(e.userId,a,e.sdkAppId,e.useStringRoomId)))}};function IoA(){return WA(this,null,function*(){let A,e;try{let CA=yield em();A=CA&&CA.length}catch{}try{let CA=yield tm();e=CA&&CA.length}catch{}let o={microphone:A,camera:e},{isH264EncodeSupported:a,isVp8EncodeSupported:l,isH264DecodeSupported:d,isVp8DecodeSupported:h,isH265EncodeSupported:y,isH265DecodeSupported:S}=this.checkSystemResult.detail,k=re.basis(),V={webRTC:k.isWebRTCSupported,getUserMedia:k.isGetUserMediaSupported,webSocket:k.isWebSocketsSupported,screenShare:k.isScreenShareSupported,webAudio:k.isWebAudioSupported,h264Encode:a,h264Decode:d,vp8Encode:l,vp8Decode:h,h265Encode:y,h265Decode:S},J={browser:k.browser,os:k.os,trtc:V,devices:o},cA={isWebCodecSupported:k.isWebCodecSupported,isMediaSessionSupported:k.isMediaSessionSupported,isWebTransportSupported:k.isWebTransportSupported};sn.uploadEvent({log:"trtcstats-".concat(JSON.stringify(J)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(J))),sn.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(cA)),userId:this.userId}),FM()})}var uoA=gc(jl()),Kz="1",_j="2",yL="3",EoA="4",_1="5",doA="6",T1="7",jz="8",oB={CLIENT_BANNED:9,CHANNEL_SETUP_RESULT:19,CHANNEL_RECONNECT_RESULT:514,JOIN_ROOM_RESULT:20,PEER_JOIN:4134,PEER_LEAVE:4135,STREAM_ADDED:16,STREAM_REMOVED:18,UPLINK_NETWORK_STATS:22,UPDATE_REMOTE_MUTE_STAT:23,PUBLISH_RESULT:4098,PUBLISH_STATE_CHANGE_RESULT:4112,UNPUBLISH_RESULT:4100,SUBSCRIBE_RESULT:4102,UNSUBSCRIBE_RESULT:4104,SUBSCRIBE_CHANGE_RESULT:4106,MUTE_RESULT:4108,UPDATE_OFFER_RESULT:4128,START_PUBLISH_TENCENT_CDN_RES:1286,STOP_PUBLISH_TENCENT_CDN_RES:1288,START_PUBLISH_GIVEN_CDN_RES:777,STOP_PUBLISH_GIVEN_CDN_RES:779,START_MIX_TRANSCODE_RES:781,STOP_MIX_TRANSCODE_RES:783,START_PUBLISH_CDN_STREAM_RES:8196,UPDATE_PUBLISH_CDN_STREAM_RES:8198,STOP_PUBLISH_CDN_STREAM_RES:8200,USER_LIST_RES:4137,SWITCH_ROLE_RES:4110,UPDATE_CONSTRAINT_CONFIG_RES:772,REBUILD_PEER_CONNECTION_RES:4150,SPC_PUBLISH_RESULT:4146,SPC_SUBSCRIBE_RESULT:4156,ABILITY_STATUS_REPORT_RESULT:4158,SERVER_FIRST_PACKAGE_RECEIVED:5e3,RECEIVE_CUSTOM_MSG:4140,FALLBACK_CODEC:66,SEND_SWITCH_ROOM_RES:4160,SEND_SWITCH_ROOM_SUBED_REQ:4161,UPDATE_NETWORK_TIME_RESULT:5001,CUSTOM_CMD_RES:8220},CoA=[oB.UPDATE_REMOTE_MUTE_STAT,oB.UPLINK_NETWORK_STATS,oB.USER_LIST_RES,oB.MUTE_RESULT,oB.SERVER_FIRST_PACKAGE_RECEIVED,oB.RECEIVE_CUSTOM_MSG,oB.UPDATE_NETWORK_TIME_RESULT],ls={CLIENT_BANNED:"client-banned",CHANNEL_SETUP_RESULT:"channel-setup-result",CHANNEL_RECONNECT_RESULT:"channel-reconnect-result",JOIN_ROOM_RESULT:"join-room-result",PEER_JOIN:"peer-join",PEER_LEAVE:"peer-leave",STREAM_ADDED:"stream-added",STREAM_REMOVED:"stream-removed",UPLINK_NETWORK_STATS:"uplink-network-stats",UPDATE_REMOTE_MUTE_STAT:"update-remote-mute-stat",PUBLISH_RESULT:"publish-result",PUBLISH_STATE_CHANGE_RESULT:"publish-state-change-result",UNPUBLISH_RESULT:"unpublish-result",SUBSCRIBE_RESULT:"subscribe-result",SUBSCRIBE_CHANGE_RESULT:"subscribe-change-result",UNSUBSCRIBE_RESULT:"unsubscribe-result",UPDATE_OFFER_RESULT:"update-offer-result",START_PUBLISH_TENCENT_CDN_RES:"start-publish-tencent-cdn-res",STOP_PUBLISH_TENCENT_CDN_RES:"stop-publish-tencent-cdn-res",START_PUBLISH_GIVEN_CDN_RES:"start-publish-given-cdn-res",STOP_PUBLISH_GIVEN_CDN_RES:"stop-publish-given-cdn-res",START_MIX_TRANSCODE_RES:"start-mix-transcode-res",STOP_MIX_TRANSCODE_RES:"stop-mix-transcode-res",START_PUBLISH_CDN_STREAM_RES:"start-publish-cdn-stream-res",UPDATE_PUBLISH_CDN_STREAM_RES:"update-publish-cdn-stream-res",STOP_PUBLISH_CDN_STREAM_RES:"stop-publish-cdn-stream-res",USER_LIST_RES:"user-list-res",SWITCH_ROLE_RES:"switch_role_res",MUTE_RESULT:"mute-result",UPDATE_CONSTRAINT_CONFIG_RES:"update-contraint-config-res",REBUILD_PEER_CONNECTION_RES:"rebuild-pc-res",SPC_PUBLISH_RESULT:"spc-publish-result",SPC_SUBSCRIBE_RESULT:"spc-subscribe-result",ABILITY_STATUS_REPORT_RESULT:"ability-status-report",SERVER_FIRST_PACKAGE_RECEIVED:"first-pkg-received",RECEIVE_CUSTOM_MSG:"receive-custom-msg",FALLBACK_CODEC:"fallback-codec",SEND_SWITCH_ROOM_RES:"send-switch-room-res",SEND_SWITCH_ROOM_SUBED_REQ:"send-switch-room-subed-res",UPDATE_NETWORK_TIME_RESULT:"update_network_time_result",CUSTOM_CMD_RES:"custom-cmd-res"},Wz="publish_change",hoA="join",BoA="leave",QoA="quality_report",zz="mute_uplink",Zz="publish",Tj="publish_state_change",N1="unpublish",Xz="subscribe",Nj="unsubscribe",Gj="subscribe_change",poA="start_publishing",moA="stop_publishing",foA="start_push_user_cdn",yoA="stop_push_user_cdn",DoA="start_mcu_mix",SoA="stop_mcu_mix",MoA="start_publish_cdn_stream",voA="update_publish_cdn_stream",RoA="stop_publish_cdn_stream",woA="get_user_list",_oA="change_role",bj="update_constraint_config",ToA="rebuild_pc",NoA="join/v2",$z="publish/v2",A8="subscribe/v3",GoA="ability_status_report",boA="reconnect",koA="channel_msg",LoA="switch_room",UoA="update_network_time",FoA=new Set([Zz,Wz,Tj,N1,Xz,Gj,Nj,$z,A8]),G1=new Set,OoA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],PoA=0,e8=class extends uoA.default{constructor(A){var e,o,a;super(),Y(this,"room"),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"url"),Y(this,"backupUrl"),Y(this,"destroyed",!1),Y(this,"_socketInUse"),Y(this,"_socket"),Y(this,"_backupSocket"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,bakRelayIps:[],reportToken:void 0}),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_seq",0),Y(this,"_log"),Y(this,"_lastMessageTime",-1),Y(this,"_connectStartTime",-1),Y(this,"_stopConnectRetry"),Y(this,"_isFirstConnect",!0),Y(this,"bytesSent",0),Y(this,"bytesReceived",0),Y(this,"keepAlive",!1),Y(this,"signalDomainWhenUnifiedProxy"),Y(this,"stopKeepAliveTimeout"),Y(this,"stopPrelinkTimeout"),Y(this,"rtt",0),Y(this,"prelink",!1),Y(this,"_prelinkConfig"),this.room=A.room,this.sdkAppId=A.sdkAppId,this.userId=A.userId,this.userSig=A.userSig,this.signalDomainWhenUnifiedProxy=A.signalDomainWhenUnifiedProxy,this.prelink=A.prelink||!1;let l=((o=(e=this.room.scheduleResult)==null?void 0:e.config)==null?void 0:o.keepAliveClient)||0;(a=this.room.joinParams)!=null&&a.keepAlive&&!l&&(l=1),l-G1.size>0&&this.room.enableSPC&&(this.keepAlive=!0,G1.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=pA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++PoA),userId:this.userId,sdkAppId:this.sdkAppId}),this.onmessage=this.onmessage.bind(this),this.onerror=this.onerror.bind(this),this.onclose=this.onclose.bind(this)}get race(){return this.room.enableSPC&&!this.room.proxy_ws}get urlParam(){let A="?sdkAppId=".concat(encodeURIComponent(this.sdkAppId),"&userId=").concat(encodeURIComponent(this.userId),"&userSig=").concat(encodeURIComponent(this.userSig),"&keepAlive=").concat(encodeURIComponent(Number(this.keepAlive)));this.signalDomainWhenUnifiedProxy&&(A+="&signalDomain=".concat(encodeURIComponent(this.signalDomainWhenUnifiedProxy))),this.prelink&&(A+="&prelink=1");let e=new URLSearchParams(location.search);return OoA.forEach(o=>{let a=e.get("trtc_".concat(o));a&&(A+="&".concat(o,"=").concat(encodeURIComponent(a)))}),this.race?"".concat(A,"&race=1"):A}get _urlWithParam(){return"".concat(this.url).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get _backupUrlWithParam(){return"".concat(this.backupUrl).concat(this.race?"/v2/ws":"").concat(this.urlParam)}get isConnected(){return this._currentState==="CONNECTED"}get isConnecting(){return this._currentState==="CONNECTING"}get isOnline(){return this._currentState==="CONNECTED"&&Date.now()-this._lastMessageTime<12e3}connect(){return WA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1e4;return function*(){if(A.isConnected)return Promise.resolve();A._log.info("connect to [".concat(A.url,", ").concat(A.backupUrl,"] ").concat(A.race?"race":"").concat(e?" timeout: ".concat(e):""," keepAlive: ").concat(Number(A.keepAlive))),A.emitConnectionStateChanged("CONNECTING"),A._connectStartTime=ko();let o=[A.connectWS({url:A._urlWithParam,isMain:!0,timeout:e})];A.race&&A._backupUrlWithParam!==A._urlWithParam&&o.push(A.connectWS({url:A._backupUrlWithParam,isMain:!1,timeout:e})),A._socketInUse=yield rM(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?YA.BACKUP:YA.MAIN),A._isFirstConnect&&(si.addSuccessEvent({key:521720}),A._isFirstConnect=!1),A.emitConnectionStateChanged("CONNECTED")}()})}connectWS(A){let{url:e,timeout:o,isMain:a}=A,l=new WebSocket(e);this.bindSocket(l),a?this._socket=l:this._backupSocket=l;let d=-1;return new Promise((h,y)=>{l.onclose=y,l.onerror=y,l.onopen=()=>h(l),o&&(d=setTimeout(()=>{this.unbindAndCloseSocket(a?YA.MAIN:YA.BACKUP),y(new gi({code:Ct.SIGNAL_CHANNEL_SETUP_FAILED,message:"ws connect timeout"}))},o))}).finally(()=>{l.onclose=null,l.onerror=null,l.onopen=null,clearTimeout(d)})}bindSocket(A){A.addEventListener("close",this.onclose),A.addEventListener("error",this.onerror),A.addEventListener("message",this.onmessage)}unbindSocket(A){A.removeEventListener("close",this.onclose),A.removeEventListener("error",this.onerror),A.removeEventListener("message",this.onmessage)}unbindAndCloseSocket(A){if(A===YA.MAIN){if(this._socket){this.unbindSocket(this._socket);try{this._socket.close(1e3)}catch{}this._socket=null}}else if(this._backupSocket){this.unbindSocket(this._backupSocket);try{this._backupSocket.close(1e3)}catch{}this._backupSocket=null}}onclose(A){A.target===this._socketInUse&&(this._log.warn("".concat(A.target===this._socket?"main":"backup"," is closed code:").concat(A.code," ").concat(A.reason)),this.emitConnectionStateChanged("DISCONNECTED"),(!A.wasClean||A.code!==1e3&&A.code!==4013)&&this.startReconnection(),this.prelink&&A.code===4013&&this.room.clearNetworkQuality(),this.room.isJoining&&this.emit(_1,new gi({code:Ct.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onclose"})))}onerror(A){this._log.error("".concat(A.target===this._socket?"main":"backup"," error observed")),this.emitConnectionStateChanged("DISCONNECTED"),A.target===this._socketInUse&&(this.unbindAndCloseSocket(YA.MAIN),this.unbindAndCloseSocket(YA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(_1,new gi({code:Ct.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:e}=this;this._lastMessageTime=Date.now(),e||this.emit(jz),this.bytesReceived+=_0(A.data);let o=JSON.parse(A.data),{cmd:a,data:l}=o,d=Object.values(oB),h=Object.keys(oB)[d.indexOf(a)],y=ls[h]||a;switch(CoA.includes(a)||(this._log.debug("received ".concat(a," msg: ").concat(A.data)),y&&this._log.info("Received event: [ ".concat(y," ]"))),a){case oB.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=l.clientIp,this._signalInfo.signalIp=l.signalInnerIp,l.svrTime&&zB(l.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(ko()-this._connectStartTime)),si.addSuccessEvent({key:521701,cost:ko()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(Kz,{signalInfo:this._signalInfo});else{let S=new gi({code:Ct.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:Xo({key:vo.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),si.addFailedEvent({key:521701,error:S}),this.emit(_1,S)}break;case oB.JOIN_ROOM_RESULT:o.code===0&&(this._signalInfo.relayIp=l.relayOuterIp,this._signalInfo.relayInnerIp=l.relayInnerIp,this._signalInfo.bakRelayIps=l.bakRelayIps,this._signalInfo.relayPort=l.relayPort,this._signalInfo.tinyId=o.tinyId,this._signalInfo.endReportExtend=l.endReportExtend,this._signalInfo.reportToken=l.reportToken,this._log.info("signalIp:".concat(this._signalInfo.signalIp," clientIp:").concat(this._signalInfo.clientIp," relayIp: ").concat(this._signalInfo.relayIp))),this.emit(y,{data:o});break;default:this.emit(String(y),{data:o})}}reGetSignalChannelUrl(){return WA(this,null,function*(){try{if(!this.room.joinParams)return;pQ(!0),yield this.room.schedule(this.room.joinParams);let{mainUrl:A,backupUrl:e}=this.room.getSignalChannelUrl();this.url=A,this.backupUrl=e}catch{}})}startReconnection(){if(!this._socketInUse)return;this._socketInUse.onclose=null,this._socketInUse.close(4011);let A=this._socketInUse===this._socket;this.unbindAndCloseSocket(A?YA.MAIN:YA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return WA(this,null,function*(){if(!this._isReconnecting){if(!this.room.isJoined&&this.keepAlive)return void this.close();this._isReconnecting=!0;try{this._log.warn("reconnect"),yield this.connect();let{roomId:A,useStringRoomId:e}=this.room,{relayIp:o,relayInnerIp:a,relayPort:l}=this._signalInfo,{data:d}=yield this.sendWaitForResponse({command:boA,data:{roomId:A,useStringRoomId:e,relayInnerIp:a,relayOuterIp:o,relayPort:l},responseCommand:ls.CHANNEL_RECONNECT_RESULT});d.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),si.addSuccessEvent({key:521702,cost:ko()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(si.addFailedEvent({key:521702,error:d.code}),this._log.warn("reconnect failed, ".concat(d.code," ").concat(d.message)),this.room.reJoin())}catch(A){this._log.error(A),this.room.reJoin()}}})}send(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.isConnected&&!this.room.isLeft){let o={cmd:A,data:e,userId:this.userId,tinyId:this._signalInfo.tinyId,seq:++this._seq},a=JSON.stringify(o);return this._socketInUse.send(a),FoA.has(A)&&this._log.info("send",A,e),this.bytesSent+=_0(a),o.seq}}sendWaitForResponse(A){let{command:e,data:o,timeout:a=5e3,responseCommand:l,commandDesc:d,enableLog:h=!0,addReceiveTime:y=!1}=A;return new Promise((S,k)=>{let V=()=>{clearTimeout(J),k(new gi({code:Ct.API_CALL_ABORTED,message:"".concat(e," aborted due to connection closed")}))};this.once(T1,V);let J=setTimeout(()=>{this.off(l,cA),this.off(T1,V);let MA=new gi({code:Ct.API_CALL_TIMEOUT,message:Xo({key:vo.API_CALL_TIMEOUT,data:{commandDesc:d,command:e}})});h&&this._log.warn(MA),k(MA)},a),cA=MA=>{MA.data.seq===CA&&(clearTimeout(J),this.off(l,cA),this.off(T1,V),y&&(MA.data.receiveTime=Date.now()),S(MA))};this.on(l,cA);let CA=this.send(e,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:e,command:o,retries:a=0,retryTimeout:l=0}=A;return IM({retryFunction:this.sendWaitForResponse,onError:d=>{let{retry:h,reject:y,error:S}=d;!this.room.isJoined||this.destroyed||S.code===Ct.API_CALL_ABORTED?y(S):this.isOnline?h():(this._log.warn("retry ".concat(o," when connected")),this.once(jz,h))},onRetrying:d=>{this._log.warn("".concat(e||o," timeout observed, retrying [").concat(d,"/").concat(a,"]"))},settings:{retries:a,timeout:l},context:this})(A)}getCurrentState(){return this._currentState}getSignalInfo(){return this._signalInfo}stopReconnection(){this._isReconnecting=!1,this._stopConnectRetry&&this._stopConnectRetry()}close(){this._log.info("closed"),clearTimeout(this.stopKeepAliveTimeout),clearTimeout(this.stopPrelinkTimeout),G1.delete(this),this.stopReconnection(),this._signalInfo={tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,bakRelayIps:[],endReportExtend:void 0,reportToken:void 0},this._socketInUse=null,this.bytesSent=0,this.bytesReceived=0,this._stopConnectRetry&&this._stopConnectRetry(),this.unbindAndCloseSocket(YA.MAIN),this.unbindAndCloseSocket(YA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(T1)}destroy(){this.close(),this.destroyed=!0}getBackupRelayIpPair(){var A;let e=(A=this._signalInfo.bakRelayIps)==null?void 0:A.shift();return e&&(e.relayPort=e.relayPort||this._signalInfo.relayPort),e}clearBakRelayIps(){this._signalInfo.bakRelayIps=[]}stopKeepAliveIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3600;if(this.keepAlive){this._log.info("stopKeepAlive in ".concat(A,"s")),this.stopKeepAliveTimeout=setTimeout(()=>{this.keepAlive=!1,this._log.info("close due to not used ".concat(A,"s")),this.close(),this.off(ls.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(ls.JOIN_ROOM_RESULT,e))};this.on(ls.JOIN_ROOM_RESULT,e)}}stopPrelinkIn(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:300;if(this.keepAlive)return;this._log.info("stopPrelink in ".concat(A,"s")),this.stopPrelinkTimeout=setTimeout(()=>{this._log.info("close prelink due to not used in ".concat(A,"s")),this.close(),this.room.clearNetworkQuality(),this.off(ls.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(ls.JOIN_ROOM_RESULT,e))};this.on(ls.JOIN_ROOM_RESULT,e)}markPrelinkConnected(A){this._prelinkConfig=po(fi({},A),{linkedTime:Date.now()})}isPrelinkValid(A,e,o){return!(!this.prelink||!this._prelinkConfig)&&(A!==this._prelinkConfig.sdkAppId||e!==this._prelinkConfig.userId||o!==this._prelinkConfig.userSig?(this._log.warn("prelink params not match"),!1):!!this.isConnected||(this._log.warn("prelink is not connected"),!1))}consumePrelink(){this.prelink=!1,this._prelinkConfig=void 0}emitConnectionStateChanged(A){if(A===this._currentState)return;this._log.info("".concat(this._currentState," -> ").concat(A));let e={prevState:this._currentState,state:A};A==="CONNECTING"&&(e.isReconnecting=this._isReconnecting),this.emit(_j,e),this._currentState=A,A==="CONNECTED"?this.emit(yL):A==="DISCONNECTED"&&this.emit(doA)}};hi([tB({settings:{retries:1/0,timeout:2e3},onError(A,e){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(si.addFailedEvent({key:521720,error:A}),this._isFirstConnect=!1),this.room.firewallDetector.increaseTimeoutCount(),e())},onRetrying(A,e){this._log.warn("retrying to connect ".concat(A)),A>=3&&A%3==0&&this.reGetSignalChannelUrl(),e&&(this._stopConnectRetry=e,(this.room.isDestroyed||this.destroyed)&&e())}})],e8.prototype,"connect");var xoA=gc(jl()),t8=!1,sm=class{constructor(A){Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_signalChannel"),Y(this,"_isErrorObserved",!1),Y(this,"_waitForPeerConnectionConnectedPromise"),Y(this,"_waitForPeerConnectionConnectedPromiseReject",null),Y(this,"_peerConnection",null),Y(this,"_emitter",new xoA.default),Y(this,"_currentState","DISCONNECTED"),Y(this,"_isReconnecting",!1),Y(this,"_reconnectionCount",0),Y(this,"_reconnectionTimer",-1),Y(this,"_isFirstConnection",!0),Y(this,"_prevTime",-1),Y(this,"_localAddress"),Y(this,"_remoteAddress"),Y(this,"isDestoyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=A.room.getLogger().createChild({id:"n-mpc",userId:this._room.userId,remoteUserId:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink}),this._signalChannel=A.signalChannel}beforeConnect(){this._prevTime<0&&(this._prevTime=ko())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,si.addSuccessEvent({key:521705,cost:Math.min(ko()-this._prevTime,3e4)})):this._isReconnecting&&si.addSuccessEvent({key:521706,cost:ko()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,si.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&si.addFailedEvent({key:521706,error:A}),A}}initialize(){let A={iceServers:this._room.getIceServers(),iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"};this._peerConnection=new RTCPeerConnection(A),this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this)}close(A){this._log.info("close connection"),this._emitter.emit("closed",A),this._isReconnecting&&this.stopReconnection(),this.closePeerConnection()}destroy(){this.isDestoyed=!0}closePeerConnection(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this._peerConnection&&(this._log.info("close pc"),this._peerConnection.onconnectionstatechange=null,this._peerConnection.close(),this._peerConnection=null,A&&this.emitConnectionStateChangedEvent("DISCONNECTED")),this._waitForPeerConnectionConnectedPromiseReject&&this._waitForPeerConnectionConnectedPromiseReject(new gi({code:Ct.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return zh;let A=null;if(this._isUplink){if(!UI()||this._peerConnection.getSenders().length===0)return zh;A=this._peerConnection.getSenders()[0].transport}else{if(!By()||this._peerConnection.getReceivers().length===0)return zh;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:zh}onConnectionStateChange(A){let e=this._peerConnection.iceConnectionState,o=this.getDTLSTransportState();if(this._log.info("connectionState: ".concat(A.target.connectionState,", ICE: ").concat(e,", DTLS: ").concat(o)),A.target.connectionState===ho.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===ho.FAILED||A.target.connectionState===ho.CLOSED){let a="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(e,", DTLS Transport state: ").concat(o),l=new gi({message:a,code:Ct.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",l)}(A.target.connectionState===ho.CONNECTED||A.target.connectionState===ho.COMPLETED)&&(this.logSelectedCandidate(),sn.logSuccessEvent({userId:this._room.userId,eventType:Ja.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),t8=!0),F.emit(nA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this._emitter.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}logSelectedCandidate(){return WA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,e]of A)if(GM(e)){let o=A.get(e.localCandidateId),a=A.get(e.remoteCandidateId);o&&(this._log.info("local candidate: ".concat(o.candidateType," ").concat(o.protocol,":").concat(o.ip||o.address,":").concat(o.port," ").concat(o.networkType||""," ").concat(o.candidateType==="relay"?"relayProtocol:".concat(o.relayProtocol):"")),this._localAddress="".concat(o.ip||o.address,":").concat(o.port)),a&&(this._log.info("remote candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port)),this._remoteAddress="".concat(a.protocol,":").concat(a.ip||a.address));break}})}getCurrentState(){return this._currentState}waitForPeerConnectionConnected(){return this._waitForPeerConnectionConnectedPromise||(this._waitForPeerConnectionConnectedPromise=new Promise((A,e)=>{if(this._currentState==="CONNECTED")return A();this._waitForPeerConnectionConnectedPromiseReject=e;let o=h=>{h.state==="CONNECTED"&&(clearTimeout(d),l(),A())},a=h=>{let{room:y}=h;y===this._room&&(clearTimeout(d),l(),e(new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.CONNECTION_ABORTED,data:"leave room"})})))},l=()=>{F.off(nA.LEAVE_SUCCESS,a,this),this._emitter.off("connection-state-changed",o,this)},d=setTimeout(()=>{l();let h=new gi({code:Ct.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(h)},Fb);F.on(nA.LEAVE_SUCCESS,a,this),this._emitter.on("connection-state-changed",o,this)}),this._waitForPeerConnectionConnectedPromise=this._waitForPeerConnectionConnectedPromise.finally(()=>{this._waitForPeerConnectionConnectedPromise=null,this._waitForPeerConnectionConnectedPromiseReject=null})),this._waitForPeerConnectionConnectedPromise}getReconnectionCount(){return this._reconnectionCount}startReconnection(){this._isReconnecting=!0,this.reconnect()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}stopReconnection(){this._log.info("stop reconnection"),this._isReconnecting=!1,this._reconnectionCount=0,this.clearReconnectionTimer(),this._signalChannel.off(yL,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Jf()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new gi({code:this._isUplink?Ct.UPLINK_RECONNECTION_FAILED:Ct.DOWNLINK_RECONNECTION_FAILED,message:Xo({key:this._isUplink?vo.UPLINK_RECONNECTION_FAILED:vo.DOWNLINK_RECONNECTION_FAILED})});return this.emitConnectionStateChangedEvent("DISCONNECTED"),this._emitter.emit("error",A),-1}return this._signalChannel.isConnected?(this._reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this._reconnectionCount,"]")),1):(this._log.warn("reconnect() signal channel is not connected, suspend reconnection until signal is connected"),this._signalChannel.once(yL,this.reconnect,this),-1)}on(A,e,o){this._emitter.on(A,e,o)}off(A,e,o){this._emitter.off(A,e,o)}getIsReconnecting(){return this._isReconnecting}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}setOffer(A){var e;return(e=this._peerConnection)==null?void 0:e.setLocalDescription(A)}setAnswer(A){var e;return(e=this._peerConnection)==null?void 0:e.setRemoteDescription(A)}};hi([Sy(521712,!1)],sm.prototype,"setOffer"),hi([Sy(521713,!1)],sm.prototype,"setAnswer");var i8=gc(Sb()),uc=function(A){return i8.default.parse(A)},_y=function(A){return i8.default.write(A)};function kj(A){return Object.keys(A).filter(e=>A[e])}var b1=class aX extends sm{constructor(e){super(po(fi({},e),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"avPlayerStateSyncManager"),Y(this,"ssrc",{audio:0,video:0,auxiliary:0}),Y(this,"_isSDPExchanging",!1),Y(this,"_videoCodec"),Y(this,"fromType"),this.flag=e.flag,this.isRobot=e.isRobot||!1,this.remoteAudioTrack=e.remoteAudioTrack||new d1(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new CL(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new gz(this._room,this),this.avPlayerStateSyncManager=new Bj({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player})}get videoCodec(){var e,o;let a=(o=(e=this._peerConnection)==null?void 0:e.remoteDescription)==null?void 0:o.sdp;return a?a.includes("H264")?"h264":"vp8":this._videoCodec||"h264"}set videoCodec(e){this._videoCodec=e}get subscribeState(){let e={audio:!1,video:!1,auxiliary:!1,smallVideo:!1};return this.remoteVideoTrack.isSubscribed&&(8&this.remoteVideoTrack.mediaType?e.smallVideo=!0:e.video=!0),this.remoteAudioTrack.isSubscribed&&(e.audio=!0),this.remoteAuxiliaryTrack.isSubscribed&&(e.auxiliary=!0),e}get muteState(){return Np(this.flag,this.userId)}get flag(){return this._flag}set flag(e){var o,a,l;e!==this._flag&&(this._flag=e,(o=this.remoteAudioTrack)==null||o.onFlagChanged(),(a=this.remoteVideoTrack)==null||a.onFlagChanged(),(l=this.remoteAuxiliaryTrack)==null||l.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(e){return e===YA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){super.initialize(),this.installEvents(),this._peerConnection.ontrack=this.onTrack.bind(this)}close(e){super.close(e),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents()}installEvents(){}uninstallEvents(){this._emitter.removeAllListeners()}emitConnectionStateChangedEvent(e){var o,a;let l=this._currentState,d=super.emitConnectionStateChangedEvent(e);return d&&l!==e&&((o=this.remoteVideoTrack)==null||o.emit("connection-state-changed",{prevState:l,state:e}),(a=this.remoteAuxiliaryTrack)==null||a.emit("connection-state-changed",{prevState:l,state:e})),d}onTrack(e){let o=e.streams[0],{track:a}=e,l=o.id===Eu?YA.MAIN:YA.AUXILIARY;this._log.debug("ontrack ".concat(l," ").concat(a.kind));let d=YA.AUDIO;a.kind===YA.VIDEO&&(d=l===YA.MAIN?YA.VIDEO:YA.AUXILIARY);let h=this.remoteAudioTrack;d===YA.VIDEO?h=this.remoteVideoTrack:d===YA.AUXILIARY&&(h=this.remoteAuxiliaryTrack),h.setInputMediaStreamTrack(a)}addRRTRLine(e){let o=e.split(`\r +`),a=new Map;o.forEach((d,h)=>{/^a=rtcp-fb:/.test(d)&&o[h+1]&&!/^a=rtcp-fb:/.test(o[h+1])&&a.set(h+1,"".concat(d.match(/^a=rtcp-fb:\d+/)[0]," rrtr"))});let l=[...a];for(let d=0;d{a.type===YA.VIDEO&&a.fmtp.forEach(l=>{l.config+=";sps-pps-idr-in-keyframe=1"})}),_y(o)}removeSDESDescription(e){let o=["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"],a=uc(e);return a.media.forEach(l=>{l.ext&&(l.ext=l.ext.filter(d=>!o.includes(d.uri)))}),_y(a)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,o){return WA(this,null,function*(){var a,l;try{if((((a=this._peerConnection)==null?void 0:a.connectionState)===ho.NEW||((l=this._peerConnection)==null?void 0:l.connectionState)===ho.CONNECTING)&&(yield this.waitForPeerConnectionConnected()),this.isSubscriptionStateNotChanged(e))return void(this._peerConnection||(this.initialize(),yield this.connect(e)));if(this._log.info("subscribe ".concat(o," ").concat(JSON.stringify(e))),this._peerConnection||this._isSDPExchanging){let d="subscribe_change";Object.values(e).find(h=>h===!0)||(d="unsubscribe"),yield this.sendSubscription(d,e)}else this.initialize(),yield this.connect(e)}catch(d){throw this._room.isJoined&&this.isStreamUnpublished(o)?(this._log.warn("".concat(d.message," ").concat(JSON.stringify(this.muteState))),new gi({code:Ct.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):d}})}unsubscribe(e){return WA(this,arguments,function(o){var a=this;let{remoteTracks:l,streamType:d}=o;return function*(){if(a._currentState==="CONNECTED"&&(d==="main"&&!a.isMainStreamSubscribed||d==="auxiliary"&&!a.isAuxStreamSubscribed))return void a._log.info("".concat(d," stream already unsubscribed"));let h=fi({},a.subscribeState);l.forEach(S=>{switch(S.mediaType){case 1:h.audio=!1;break;case 4:h.video=!1;break;case 8:h.smallVideo=!1;break;case 2:h.auxiliary=!1}});let y="subscribe_change";Object.values(h).find(S=>S===!0)||(y="unsubscribe"),a._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(d," [").concat(kj(h),"]")),yield a.sendSubscription(y,h),y==="unsubscribe"&&(a.closePeerConnection(),a.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return WA(this,null,function*(){})}sendSubscription(e){let o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,a={srcTinyId:this.tinyId,srcUserId:this.userId},l=Nj,d=ls.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(a={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},l=Gj,d=ls.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:l,data:a,responseCommand:d,timeout:1e4}).then(h=>{let{data:y}=h;if(y.code!==0){let S=new gi({code:y.code,message:Xo({key:vo.ERROR_MESSAGE,data:{type:e,message:y.message}})});throw this._log.error(S),S}})}connect(){return WA(this,arguments,function(){var e=this;let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState;return function*(){try{yield e.exchangeSDP(o),yield e.waitForPeerConnectionConnected()}catch(a){throw e.closePeerConnection(!0),a}}()})}exchangeSDP(e){return WA(this,null,function*(){try{this._isSDPExchanging=!0,yield this.createOffer(),this._log.info("createOffer success, sending offer");let{type:o,sdp:a}=this._peerConnection.localDescription,l={type:o,sdp:a,srcUserId:this.userId,srcTinyId:this.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo},d=yield this._signalChannel.sendWaitForResponse({command:Xz,commandDesc:"exchange sdp",data:l,responseCommand:ls.SUBSCRIBE_RESULT,timeout:$x});if(!this._peerConnection){let h=new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.CONNECTION_CLOSED})});throw this._log.warn(h),h}yield this.onSubscribeResult(d),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return WA(this,null,function*(){let e={voiceActivityDetection:!1};Xd()&&this._sdpSemantics===$S?(this._peerConnection.addTransceiver(YA.AUDIO,{direction:Xn.RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:Xn.RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:Xn.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(e);if(o.sdp){let{isH264DecodeSupported:a}=yield Uk();a||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(l){let d=uc(l);return d.media.forEach(h=>{var y,S;if(h.type===YA.VIDEO){let k=new Set;h.rtp.forEach(J=>{let{payload:cA,codec:CA}=J;return CA==="H264"&&k.add(cA)}),h.fmtp.forEach(J=>{let{payload:cA,config:CA}=J,MA=CA.match(/apt=(\d+)/);MA&&MA[1]&&k.has(Number(MA[1]))&&k.add(cA)});let V=J=>{let{payload:cA}=J;return!k.has(cA)};h.rtp=h.rtp.filter(V),h.rtcpFb=(y=h.rtcpFb)==null?void 0:y.filter(V),h.fmtp=h.fmtp.filter(V),h.payloads=(S=h.payloads)==null?void 0:S.split(" ").filter(J=>!k.has(Number(J))).join(" ")}}),_y(d)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(l){let d=uc(l);return d.media.forEach(h=>{h.type===YA.AUDIO&&h.fmtp.forEach(y=>{y.config+=";sprop-stereo=1;stereo=1"})}),_y(d)}(o.sdp),this._sdpSemantics===$S&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(e){return WA(this,null,function*(){let{code:o,message:a=""}=e&&e.data||{},{type:l,sdp:d}=e&&e.data&&e.data.data||{};if(o===d0)throw new gi({code:Ct.NOT_SUPPORTED_H264,message:Xo({key:vo.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new gi({code:o,message:Xo({key:vo.EXCHANGE_SDP_FAILED,data:{errMsg:a}})});this._log.debug("accept remote answer: ".concat(d)),yield this.setAnswer({type:l,sdp:d}),this.updateSSRC(d)}catch(h){throw this._log.error(h),h}})}updateSSRC(e){try{uc(e).media.forEach(o=>{if(o.ssrcs)if(o.type===YA.AUDIO){let a=o.ssrcs.find(l=>{var d;return(d=l.value)==null?void 0:d.includes(Eu)});a&&(this.ssrc.audio=Number(a.id))}else{let a=o.ssrcs.find(d=>{var h;return(h=d.value)==null?void 0:h.includes(Eu)}),l=o.ssrcs.find(d=>{var h;return(h=d.value)==null?void 0:h.includes(jx)});a&&(this.ssrc.video=Number(a.id)),l&&(this.ssrc.auxiliary=Number(l.id))}})}catch{}}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}reconnect(){return WA(this,null,function*(){if(!(GI(aX.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=Tp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}getIsReconnecting(){return this._isReconnecting}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}getCurrentState(){return this._currentState}setDelay(e){let{audioDelay:o,videoDelay:a}=e;this.remoteAudioTrack.stat.end2EndDelay=o,this.remoteVideoTrack.stat.end2EndDelay=a}get audioReceiver(){var e;return((e=this._peerConnection)==null?void 0:e.getReceivers()[0])||null}};hi([jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let h=y=>{this._emitter.off("closed",h),d(new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this._emitter.off("closed",h)})})})],b1.prototype,"subscribe"),hi([Sy(521717,!1)],b1.prototype,"unsubscribe"),hi([qM(sm.prototype.afterConnect),w5(sm.prototype.beforeConnect)],b1.prototype,"connect");var o8=b1,s8={voiceActivityDetection:!1},k1=class gX extends sm{constructor(e){super(po(fi({},e),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"ssrc",{audio:0,video:0,small:0,auxiliary:0}),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"flag",0)}get videoCodec(){return this._mediaSettings.videoCodec.toLowerCase()||"h264"}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}initialize(){super.initialize(),this.installEvents()}reset(){this._isReconnecting&&this.stopReconnection(),this.closePeerConnection(),this.uninstallEvents()}close(e){super.close(e),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this._emitter.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this._emitter.on("connection-state-changed",this.handleConnectionStateChange,this)}uninstallEvents(){this._emitter.off("connection-state-changed",this.handleConnectionStateChange,this)}emitConnectionStateChangedEvent(e,o){var a,l,d;let h=this._currentState,y=super.emitConnectionStateChangedEvent(e);return y&&h!==e&&(o?o.emit("connection-state-changed",{prevState:h,state:e}):((a=this.localMainVideoTrack)==null||a.emit("connection-state-changed",{prevState:h,state:e}),(l=this.localAuxVideoTrack)==null||l.emit("connection-state-changed",{prevState:h,state:e}),(d=this._publishingLocalVideoTrack)==null||d.emit("connection-state-changed",{prevState:h,state:e}))),y}publish(e){return WA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,isAuxiliary:h}=o;return function*(){let y;a._peerConnection||a.initialize(),l&&(a._publishingLocalAudioTrack=l),d&&(a._publishingLocalVideoTrack=d),a._isPublishingAux=h,d&&!h&&d.small&&(y=a._room.videoManager.smallTrack),a.sendMediaSettings(),Xd()?yield a.publishByTransceiver({localAudioTrack:l,localVideoTrack:d,smallTrack:y,isAuxiliary:h}):yield a.publishByAddTrack({localAudioTrack:l,localVideoTrack:d,smallTrack:y}),a._publishingLocalAudioTrack=null,a._publishingLocalVideoTrack=null,a._isPublishingAux=!1,h?(d&&(a.localAuxVideoTrack=d),l&&(a.localAuxAudioTrack=l)):(d&&(a.localMainVideoTrack=d),l&&(a.localMainAudioTrack=l)),a.installTrackMuteEvents(l,d),a.sendMutedFlag()}()})}publishByTransceiver(e){return WA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,smallTrack:h,isAuxiliary:y}=o;return function*(){a._log.info("publish by transceiver");let S=new MediaStream,k=d?.outMediaTrack,V=l?.outMediaTrack;V&&S.addTrack(V),k&&S.addTrack(k);let J=a._peerConnection.getTransceivers();if(J.length===0)a._peerConnection.addTransceiver(V||YA.AUDIO,{direction:Xn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y?YA.VIDEO:k||YA.VIDEO,{direction:Xn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(h||YA.VIDEO,{direction:Xn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(y&&k||YA.VIDEO,{direction:Xn.SENDONLY,streams:[S]}),yield a.connect();else{let cA=[];if(V&&(J[0].sender.track||cA.push(0),yield J[0].sender.replaceTrack(V),yield a.setBandwidth({bandwidth:l?.profile.bitrate||40,type:YA.AUDIO})),k){let CA=y?3:1;yield J[CA].sender.replaceTrack(k),yield a.setBandwidth({bandwidth:d.profile.bitrate,type:YA.VIDEO,videoType:y?YA.AUXILIARY:YA.BIG}),cA.push(CA),h&&(yield J[2].sender.replaceTrack(h),yield a.setBandwidth({bandwidth:d.small.bitrate,type:YA.VIDEO,videoType:YA.SMALL}),cA.push(2))}yield a.setTransceiverDirection(Xn.SENDONLY,cA),yield a.doPublishChange(),d?.emit("connection-state-changed",{prevState:"DISCONNECTED",state:"CONNECTING"}),d?.emit("connection-state-changed",{prevState:"CONNECTING",state:"CONNECTED"})}}()})}publishByAddTrack(e){return WA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d,smallTrack:h}=o;return function*(){a._log.info("publish by addtrack");let y=d?.outMediaTrack,S=l?.outMediaTrack;if(a._peerConnection&&a._peerConnection.connectionState!=="new")return l&&S&&(yield a.addTrack(l)),void(y&&(yield a.addTrack(d)));let k=new MediaStream;if(S&&k.addTrack(S),y&&k.addTrack(y),S&&a._peerConnection.addTrack(S,k),y&&(a._peerConnection.addTrack(y,k),h)){let V=new MediaStream;V.addTrack(h),a._peerConnection.addTrack(h,V)}yield a.connect()}()})}enableSmall(e){return WA(this,null,function*(){let o=this._peerConnection.getTransceivers();e?this._room.videoManager.smallTrack&&(yield o[2].sender.replaceTrack(this._room.videoManager.smallTrack),yield this.setTransceiverDirection(Xn.SENDONLY,[2])):(yield o[2].sender.replaceTrack(null),yield this.setTransceiverDirection(Xn.INACTIVE,[2])),this.updateMediaSettings(),yield this.doPublishChange()})}installTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),a=0;a{l&&(l?.on("mute",this.sendMutedFlag,this),l?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var e=arguments.length,o=new Array(e),a=0;a{l&&(l?.off("mute",this.sendMutedFlag,this),l?.off("unmute",this.sendMutedFlag,this))})}unpublish(e){return WA(this,arguments,function(o){var a=this;let{localAudioTrack:l,localVideoTrack:d}=o;return function*(){if(!dQ())return l&&l.outMediaTrack&&!d&&a.localMainVideoTrack?(yield a.removeTrack(l),void(a.localMainAudioTrack=null)):d&&d.outMediaTrack&&!l&&a.localMainAudioTrack?(yield a.removeTrack(d),void(a.localMainVideoTrack=null)):(yield a.doUnpublish(),a.uninstallTrackMuteEvents(l,d),void a.emitConnectionStateChangedEvent("DISCONNECTED",d));let h=d&&d===a.localAuxVideoTrack,y=d?.outMediaTrack,S=a._peerConnection.getSenders(),k=[];l&&(h?a.localAuxAudioTrack=null:a.localMainAudioTrack=null,!a.localAuxAudioTrack&&!a.localMainAudioTrack&&(yield S[0].replaceTrack(null),k.push(0))),y&&(h?(yield S[3].replaceTrack(null),a.localAuxVideoTrack=null,a._mediaSettings=po(fi({},a._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),k.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),a.localMainVideoTrack=null,a._mediaSettings=po(fi({},a._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),k.push(1,2))),a.isMainStreamPublished||a.isAuxStreamPublished?(yield a.setTransceiverDirection(Xn.INACTIVE,k),yield a.doPublishChange(!1)):yield a.doUnpublish(),a.uninstallTrackMuteEvents(l,d),d?.emit("connection-state-changed",{prevState:a._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let e=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return WA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},a=yield this._signalChannel.sendWaitForResponse({command:Tj,data:o,responseCommand:ls.PUBLISH_STATE_CHANGE_RESULT,enableLog:e});this.checkPublishResultCode(a.data.code,a.data.message)})}doUnpublish(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:N1,commandDesc:"unpublish",responseCommand:ls.UNPUBLISH_RESULT,enableLog:e}).catch(o=>{if(o.getCode()===Ct.API_CALL_TIMEOUT)return Promise.resolve();throw o})}updateMediaSettings(){let{detail:{isH264EncodeSupported:e,isVp8EncodeSupported:o}}=this._room.checkSystemResult;e?this._mediaSettings.videoCodec="H264":o&&(this._mediaSettings.videoCodec="VP8");let a=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:l,localAuxVideoTrack:d}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?d=this._publishingLocalVideoTrack:l=this._publishingLocalVideoTrack),Qy){if(a&&a.outMediaTrack){let h=a.outMediaTrack.getSettings();this._mediaSettings.audioChannel=h.channelCount||1,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=h.sampleRate||0}if(l&&l.outMediaTrack){let h=l.outMediaTrack.getSettings();this._mediaSettings.videoWidth=h.width||0,this._mediaSettings.videoHeight=h.height||0,this._mediaSettings.videoFps=h.frameRate||0,this._mediaSettings.videoBps=1e3*l.profile.bitrate,l.small&&(this._mediaSettings.smallVideoWidth=l.small.width,this._mediaSettings.smallVideoHeight=l.small.height,this._mediaSettings.smallVideoFps=l.small.frameRate,this._mediaSettings.smallVideoBps=1e3*l.small.bitrate)}if(d&&d.outMediaTrack){let h=d.outMediaTrack.getSettings();this._mediaSettings.auxVideoWidth=h.width||0,this._mediaSettings.auxVideoHeight=h.height||0,this._mediaSettings.auxVideoFps=h.frameRate||0,this._mediaSettings.auxVideoBps=1e3*d.profile.bitrate}}else a&&a.outMediaTrack&&(this._mediaSettings.audioChannel=a.profile.channelCount,this._mediaSettings.audioBps=1e3*a.profile.bitrate,this._mediaSettings.audioFs=a.profile.sampleRate),l&&l.outMediaTrack&&(this._mediaSettings.videoWidth=l.profile.width,this._mediaSettings.videoHeight=l.profile.height,this._mediaSettings.videoFps=l.profile.frameRate,this._mediaSettings.videoBps=1e3*l.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:bj,data:this._mediaSettings,responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return WA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is adding ".concat(e.kind," track to current published local ").concat(o?YA.AUXILIARY:YA.MAIN," stream")),Xd()?yield this.addTrackByTransceiver(e,o):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,o){return WA(this,null,function*(){var a;if(!e.mediaTrack)return;let l=this._peerConnection.getTransceivers();if(e.kind===YA.AUDIO)yield l[0].sender.replaceTrack(e.outMediaTrack);else{let d=o?3:1;yield l[d].sender.replaceTrack(e.outMediaTrack),d===1&&(a=this.localMainVideoTrack)!=null&&a.small&&(yield l[2].sender.replaceTrack(this._room.videoManager.smallTrack)),l[d].direction===Xn.INACTIVE&&(yield this.setTransceiverDirection(Xn.SENDONLY,[d]))}this.updateMediaSettings(),yield this.doPublishChange()})}addTrackBySender(e){return WA(this,null,function*(){if(!e.outMediaTrack)return;let o=e.outMediaTrack;dQ()&&this._peerConnection.getTransceivers().findIndex(l=>l.direction==="stopped")>=0&&(this._log.warn("transceiver is stopping, negotiate sdp first"),yield this.updateOffer("remove",o));let a=this._peerConnection.getSenders().find(l=>l.track&&l.track.kind===o.kind);if(a&&a.track){this._log.warn("sender already exists, remove sender first");let l=a.track;this.removeSender(a),yield this.updateOffer("remove",l)}if(o&&this._peerConnection.addTrack(o,new MediaStream([o])),o.kind===YA.VIDEO&&e instanceof BQ&&e.small){let l=new MediaStream,{smallTrack:d}=this._room.videoManager;l.addTrack(d),this._peerConnection.addTrack(d,l)}yield this.updateOffer("add",o)})}isNeedToResetOfferOrder(){if(this._sdpSemantics===E0||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,o=uc(e);for(let a=0;aa.sender&&a.sender.track===e.track)),this._peerConnection.removeTrack(e),o&&Ra(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(e){return WA(this,null,function*(){if(!this._peerConnection)return;let o=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;this._log.info("is removing ".concat(e.kind," track from current published local ").concat(o?YA.AUXILIARY:YA.MAIN," stream")),Xd()?yield this.removeTrackByTransceiver(e,o):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,o){return WA(this,null,function*(){if(!e.outMediaTrack)return;let a=this._peerConnection.getTransceivers();if(e.kind===YA.AUDIO)yield a[0].sender.replaceTrack(null);else{let l=o?3:1;yield a[l].sender.replaceTrack(null),l===1&&e.small&&(yield a[2].sender.replaceTrack(null)),yield this.setTransceiverDirection(Xn.INACTIVE,[l])}this.updateMediaSettings(),yield this.doPublishChange()})}setTransceiverDirection(e,o){return WA(this,null,function*(){if(!or)return;let a=!1,l=!1;this._log.info("setting transceiver ".concat(o.join(",")," direction to ").concat(e));let d=this._peerConnection.getTransceivers();if(o.forEach(S=>{d[S].direction!==e&&(d[S].direction=e,a=!0)}),a){this._log.info("updating offer");let S=yield this._peerConnection.createOffer();yield this.setOffer(S)}let h=-1,y=this._peerConnection.remoteDescription.sdp.split(`\r +`).map(S=>{if(S.match(new RegExp("a=(".concat(Xn.INACTIVE,"|").concat(Xn.RECVONLY,"|").concat(Xn.SENDONLY,")")))&&h++,o.includes(h)){if(e===Xn.INACTIVE&&S.includes("a=".concat(Xn.RECVONLY)))return l=!0,"a=".concat(e);if(e===Xn.SENDONLY&&S.includes("a=".concat(Xn.INACTIVE)))return l=!0,"a=".concat(Xn.RECVONLY)}return S}).join(`\r +`);l&&(this._log.info("updating answer"),yield this.setAnswer({type:"answer",sdp:y}))})}removeTrackBySender(e){return WA(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===YA.VIDEO&&this.isNeedToResetOfferOrder()&&this.localMainAudioTrack)return this.reset(),this.initialize(),void(yield this.publish({localAudioTrack:this.localMainAudioTrack,isAuxiliary:!1}));let o=this._peerConnection.getSenders().find(a=>a.track===e.outMediaTrack);o&&(this.removeSender(o),e.kind===YA.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(a=>{a.track&&a.track.kind===YA.VIDEO&&this.removeSender(a)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return WA(this,null,function*(){var o;let a,l=(o=this._peerConnection)==null?void 0:o.getSenders();if(!l||l.length===0||!e.mediaTrack||(a=Xd()?e.kind===YA.AUDIO?l[0]:l[1]:l.find(h=>h.track&&h.track.kind===e.kind),!a))return!1;let d=e===this.localAuxAudioTrack||e===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(e.kind," track on ").concat(d?YA.AUXILIARY:YA.MAIN," stream")),e.kind===YA.AUDIO?yield a.replaceTrack(e.outMediaTrack):e.kind===YA.VIDEO&&(d?l[3]&&(yield l[3].replaceTrack(e.outMediaTrack)):yield a.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,o){return WA(this,null,function*(){try{let a=yield this._peerConnection.createOffer(s8);or&&a.sdp&&(a.sdp=this.setSDPDirection(a.sdp,"sendrecv")),yield this.setOffer(a);let l=this.updateMediaSettings(),d={action:e,trackId:o.id,kind:o.kind===YA.VIDEO?"bigVideo":o.kind,type:"offer",sdp:this._peerConnection.localDescription.sdp,constraintConfig:l,state:this._room.publishState};this._log.info("createOffer success, sending updated offer to remote server"),this._log.debug("updatedOffer: ".concat(d.sdp));let h=yield this._signalChannel.sendWaitForResponse({command:Wz,data:d,responseCommand:ls.UPDATE_OFFER_RESULT,timeout:Xx,commandDesc:"update offer"}),{code:y,message:S}=h.data;y!==0&&this.checkPublishResultCode(y,S),yield this.acceptAnswer(h.data.data),a.sdp&&this.updateSSRC(a.sdp)}catch(a){throw this._log.error(a),a}})}setBandwidth(e){return WA(this,arguments,function(o){var a=this;let{bandwidth:l,type:d,videoType:h,sdp:y}=o;return function*(){if(!Hk())return y?d===YA.VIDEO?a.updateVideoBandwidthRestriction(y,l,h):a.updateAudioBandwidthRestriction(y,l):void 0;let S,k=a._peerConnection.getSenders();if(Xd()){let V=0;d===YA.VIDEO&&(V=h===YA.SMALL?2:h===YA.AUXILIARY?3:1),S=k[V]}else S=k.find(V=>V.track&&V.track.kind===d);if(S){let V=S.getParameters();(!V.encodings||V.encodings.length===0)&&(V.encodings=[{}]),V.encodings[0].maxBitrate=1e3*l;try{return yield S.setParameters(V),a._log.info("".concat(h||"").concat(d," bandwidth ").concat(l," kbps")),y}catch(J){if(a._log.info("failed to set bandwidth by setting maxBitrate: ".concat(J)),y)return d===YA.VIDEO?a.updateVideoBandwidthRestriction(y,l,h):a.updateAudioBandwidthRestriction(y,l)}}return y}()})}updateVideoBandwidthRestriction(e,o,a){let l="AS";or&&(l="TIAS",o*=1e3);let d=0,h=-1;return a===YA.SMALL?d=1:a===YA.AUXILIARY&&(d=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,y=>(h+=1,h===d?"".concat(y,"b=").concat(l,":").concat(o,`\r +`):y)),e}updateAudioBandwidthRestriction(e,o){let a="AS";return or&&(a="TIAS",o*=1e3),e=e.replace(/m=audio (.*)\r\nc=IN (.*)\r\n/,`m=audio $1\r c=IN $2\r b=`.concat(a,":").concat(o,`\r -`))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return KA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return KA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return KA(this,null,function*(){try{let e=yield this._peerConnection.createOffer(Lz);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Rz,responseCommand:ls.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof qM||this.localAuxVideoTrack instanceof qM,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then(o=>{let{code:a,message:c,data:d}=o.data;return a===0?this.acceptAnswer(d):this.checkPublishResultCode(a,c)})}setSDPDirection(e,o){let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",c=uc(e);return c.media.forEach(d=>{(a==="all"||d.type===a)&&(d.direction=o)}),vy(c)}acceptAnswer(e){return KA(this,null,function*(){var o,a,c,d,C;try{let y;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let k=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((a=this.localMainVideoTrack)==null?void 0:a.profile.bitrate),V=((c=this._publishingLocalAudioTrack)==null?void 0:c.profile.bitrate)||((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate);if(k){let J=this._isPublishingAux?YA.AUXILIARY:YA.BIG;y=yield this.setBandwidth({bandwidth:k,type:YA.VIDEO,sdp:y,videoType:J})}V&&(y=yield this.setBandwidth({bandwidth:V,type:YA.AUDIO,sdp:y}))}if(y=this.removeVideoOrientation(e.sdp),(C=this._publishingLocalVideoTrack)!=null&&C.small){let{smallStreamConfig:k}=this._room;y=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||k.bitrate,type:YA.VIDEO,videoType:YA.SMALL,sdp:y})}let S={type:e.type,sdp:y};yield this.setAnswer(S),this._log.debug("accepted answer: ".concat(y))}catch(y){throw this._log.error("failed to accept remote answer ".concat(y)),y}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(vz,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return KA(this,null,function*(){if(!(NI(P9.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:f1,responseCommand:ls.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch{let o=Rp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{uc(e).media.forEach((o,a)=>{if(o.type===YA.AUDIO){let c=o.ssrcs&&o.ssrcs[0];c&&(this.ssrc.audio=Number(c.id))}else{if(this._sdpSemantics===l0&&o.ssrcGroups)return void o.ssrcGroups.forEach((d,C)=>{let y=Number(d.ssrcs.split(" ")[0]);C===0?this.ssrc.video=y:C===1&&(this.ssrc.small=y)});let c=o.ssrcs&&o.ssrcs[0];if(!c)return;switch(a){case 1:this.ssrc.video=Number(c.id);break;case 2:this.ssrc.small=Number(c.id);break;case 3:this.ssrc.auxiliary=Number(c.id)}}})}catch{}}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:YA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(e===YA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(e===YA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&e===YA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&e===YA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,o){if(e!==0)throw e===I0?(this._log.error(cc.NOT_SUPPORTED_H264ENCODE),new ai({code:dt.NOT_SUPPORTED_H264,message:Xo({key:Mo.NOT_SUPPORTED_H264ENCODE})})):new ai({code:dt.UNKNOWN,message:Xo({key:Mo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.PUBLISH_RESULT,code:e,message:o}})})}};Ci([jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=y=>{this._emitter.off("closed",C),d(new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this._emitter.off("closed",C)})})})],S1.prototype,"publish"),Ci([fy(521715,!1)],S1.prototype,"unpublish"),Ci([VM(tm.prototype.afterConnect),n5(tm.prototype.beforeConnect)],S1.prototype,"connect");var M1=S1,uoA=class{constructor(A,e){this.room=A,Y(this,"_log"),Y(this,"_prevReportTime",0),Y(this,"_prevReport",{}),Y(this,"_prevStats",null),Y(this,"_prevEncoderImplementation",""),Y(this,"_prevAuxEncoderImpl",""),Y(this,"_prevQualityLimitationReason",""),Y(this,"_prevAuxQualityLimitationReason",""),Y(this,"_prevDecoderImplementationMap",new Map),Y(this,"_decodeMap",new Map),Y(this,"_prevQpSum",0),Y(this,"_prevAuxQpSum",0),Y(this,"totalBytesSent",0),Y(this,"totalBytesReceived",0),Y(this,"_spcStats",null),this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return KA(this,null,function*(){var e,o,a,c,d,C,y;let S={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},k=A.getPeerConnection(),V=A.getSSRC();if(k)try{if((this._spcStats||(yield k.getStats())).forEach(J=>{var gA,CA,MA,$A,Be,Ye,ve,yi,Ge,Bt,hi,Di,Vo;let Jo,Qn;if(J.type==="outbound-rtp")if((J.mediaType||J.kind)===YA.VIDEO){if(J.ssrc===V.video?(Jo=YA.VIDEO,Qn=A.localMainVideoTrack):J.ssrc===V.small?Jo=YA.SMALL:J.ssrc===V.auxiliary&&(Qn=A.localAuxVideoTrack,Jo=YA.AUXILIARY),!Jo)return;S[Jo].bytesSent=J.bytesSent,S[Jo].packetsSent=J.packetsSent,S[Jo].framesEncoded=J.framesEncoded,Je(J.keyFramesEncoded)||(S[Jo].keyFramesEncoded=J.keyFramesEncoded),Je(J.nackCount)||(S[Jo].nackCount=J.nackCount),Je(J.pliCount)||(S[Jo].pliCount=J.pliCount),Je(J.retransmittedPacketsSent)||(S[Jo].retransmittedPacketsSent=J.retransmittedPacketsSent),Je(J.totalEncodeTime)||(S[Jo].totalEncodeTime=J.totalEncodeTime),Je(J.totalPacketSendDelay)||(S[Jo].totalPacketSendDelay=J.totalPacketSendDelay);let Ho=0;if(!Je(J.qpSum)&&!Je(J.framesEncoded)&&J.framesEncoded>0){let Ns=J.qpSum,pg=J.framesEncoded,ya=Jo===YA.VIDEO?this._prevQpSum:this._prevAuxQpSum,Bu=Jo===YA.VIDEO?((CA=(gA=A.localMainVideoTrack)==null?void 0:gA.stat)==null?void 0:CA.framesEncoded)||0:(($A=(MA=A.localAuxVideoTrack)==null?void 0:MA.stat)==null?void 0:$A.framesEncoded)||0;if(pg>Bu&&Ns>ya){let BL=Ns-ya,m_=pg-Bu;Ho=Math.round(BL/m_),Ho>35&&A.videoCodec==="h264"&&this._log.warn("".concat(Jo===YA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(Ho,", resolution: ").concat(J.frameWidth,"x").concat(J.frameHeight,", codec: ").concat(A.videoCodec,", "))}Jo===YA.VIDEO?this._prevQpSum=Ns:Jo===YA.AUXILIARY&&(this._prevAuxQpSum=Ns)}if(!Je(J.encoderImplementation)&&(Jo===YA.VIDEO&&this._prevEncoderImplementation!==J.encoderImplementation||Jo===YA.AUXILIARY&&this._prevAuxEncoderImpl!==J.encoderImplementation)){let Ns=2,pg=this._prevEncoderImplementation;Jo===YA.AUXILIARY&&(Ns=7,pg=this._prevAuxEncoderImpl),F.emit("262",{userId:A.userId,streamType:Ns,prevImplementation:pg,implementation:J.encoderImplementation,codec:A.videoCodec,isHWCodec:J.powerEfficientEncoder}),this[Jo===YA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=J.encoderImplementation,Qn?.log.info("encoderImplementation change to ".concat(J.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(J.powerEfficientEncoder))}J.ssrc===V.video?!Je(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevQualityLimitationReason!==J.qualityLimitationReason&&(Qn?.log.info("qualityLimitationReason change to ".concat(J.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(Be=A.localMainVideoTrack)==null?void 0:Be.isQosClearFirst}),this._prevQualityLimitationReason=J.qualityLimitationReason):J.ssrc===V.auxiliary&&!Je(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevAuxQualityLimitationReason!==J.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(J.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(Ye=A.localAuxVideoTrack)==null?void 0:Ye.isQosClearFirst}),this._prevAuxQualityLimitationReason=J.qualityLimitationReason)}else S.audio.bytesSent=J.bytesSent,S.audio.packetsSent=J.packetsSent;else if(J.type==="candidate-pair")_M(J)&&(this.totalBytesSent=J.bytesSent,bn(J.currentRoundTripTime)&&(S.rtt=Math.floor(1e3*J.currentRoundTripTime)));else if(J.type==="media-source"){if(J.kind===YA.AUDIO)S.audio.audioLevel=J.audioLevel||0,S.audio.totalAudioEnergy=J.totalAudioEnergy||0,J.echoReturnLoss,Je((Ge=(yi=(ve=A.localMainAudioTrack)==null?void 0:ve.sourceTrack)==null?void 0:yi.stats)==null?void 0:Ge.deliveredFramesDuration)?J.totalSamplesDuration&&(S.audio.totalSamplesDuration=J.totalSamplesDuration):S.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(J.kind===YA.VIDEO)if(J.trackIdentifier===A.getVideoTrackId(YA.VIDEO))if((Di=(hi=(Bt=A.localMainVideoTrack)==null?void 0:Bt.sourceTrack)==null?void 0:hi.stats)!=null&&Di.deliveredFrames){let{deliveredFrames:Ho}=A.localMainVideoTrack.sourceTrack.stats;S.video.framesCaptured=Ho,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&Ho>=A.localMainVideoTrack.stat.framesCaptured?S.video.fpsCapture=Math.floor((Ho-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):S.video.fpsCapture=J.framesPerSecond}else S.video.fpsCapture=J.framesPerSecond;else J.trackIdentifier===A.getVideoTrackId(YA.AUXILIARY)?S.auxiliary.fpsCapture=J.framesPerSecond:S.small.fpsCapture=J.framesPerSecond}if(!Je(J.audioLevel)&&(Vo=A.localMainAudioTrack)!=null&&Vo.mediaTrack&&J.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(S.audio.audioLevel=J.audioLevel||0),!Je(J.frameWidth)){let Ho=YA.SMALL;J.trackIdentifier===A.getVideoTrackId(YA.VIDEO)||J.ssrc===V.video?Ho=YA.VIDEO:(J.trackIdentifier===A.getVideoTrackId(YA.AUXILIARY)||J.ssrc===V.auxiliary)&&(Ho=YA.AUXILIARY),S[Ho].frameWidth=J.frameWidth,S[Ho].frameHeight=J.frameHeight,S[Ho].framesSent=J.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let J=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(J){let gA=J.getInternalAudioLevel(),CA=J.getInternalAudioLevelAfter3A();S.audio.audioCaptureEnergyAfter3a=CA,S.audio.micAudioLevel=gA,S.audio.audioLevel===0&&A.localMainAudioTrack&&(S.audio.audioLevel=CA??gA),!A.localMainAudioTrack&&!Je((o=(e=J.sourceTrack)==null?void 0:e.stats)==null?void 0:o.deliveredFramesDuration)&&(S.audio.totalSamplesDuration=J.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let J=A.getRoom().capturedLocalMainVideoTrack;if((c=(a=J?.sourceTrack)==null?void 0:a.stats)!=null&&c.deliveredFrames){let{deliveredFrames:gA}=J.sourceTrack.stats;S.video.framesCaptured=gA,J.stat.framesCaptured&&J.stat.framesCaptured>0&&gA>=J.stat.framesCaptured&&(S.video.fpsCapture=Math.floor((gA-J.stat.framesCaptured)/this.statInterval)),J.stat.framesCaptured=gA}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let J=A.getRoom().capturedLocalAuxVideoTrack;if((C=(d=J?.sourceTrack)==null?void 0:d.stats)!=null&&C.deliveredFrames){let{deliveredFrames:gA}=J.sourceTrack.stats;S.auxiliary.framesCaptured=gA,J.stat.framesCaptured&&J.stat.framesCaptured>0&&gA>=J.stat.framesCaptured&&(S.auxiliary.fpsCapture=Math.floor((gA-J.stat.framesCaptured)/this.statInterval)),J.stat.framesCaptured=gA}}this.totalBytesSent||(this.totalBytesSent+=S.audio.bytesSent+S.video.bytesSent+S.auxiliary.bytesSent),Object.keys(S).forEach(J=>{J===YA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=S[J]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=S[J])):J===YA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=S[J]):J===YA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=S[J])})}catch(J){this._log.warn("failed to getStats on sender connection ".concat(J))}return S.rtt===0&&(S.rtt=((y=this.room.networkQuality)==null?void 0:y.uplinkRTT)||0),S})}getReceiverStats(A){return KA(this,null,function*(){var e,o,a;let c={tinyId:A.tinyId,userId:A.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,avSyncDelay:0,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},d=A.getPeerConnection();if(d)try{let{ssrc:C}=A,{muteState:y,subscribeState:S}=A;(this._spcStats||(yield d.getStats())).forEach(J=>{var gA,CA;if(J.type==="codec"&&this._decodeMap.set(J.id,J),J.type==="inbound-rtp"){let MA=(J.mediaType||J.kind)===YA.AUDIO;if(MA){if(J.ssrc!==C.audio||!y.hasAudio)return;c.audio.packetsReceived=J.packetsReceived,c.audio.bytesReceived=J.bytesReceived,c.audio.packetsLost=J.packetsLost,J.insertedSamplesForDeceleration&&(c.audio.insertedSamplesForDeceleration=J.insertedSamplesForDeceleration),J.removedSamplesForAcceleration&&(c.audio.removedSamplesForAcceleration=J.removedSamplesForAcceleration),J.totalSamplesDuration&&(c.audio.totalSamplesDuration=J.totalSamplesDuration),J.totalSamplesReceived&&(c.audio.totalSamplesReceived=J.totalSamplesReceived),J.concealedSamples&&(c.audio.concealedSamples=J.concealedSamples),J.silentConcealedSamples&&(c.audio.silentConcealedSamples=J.silentConcealedSamples);let{remoteAudioTrack:$A}=A;$A.stat.packetsReceived=J.packetsReceived,$A.stat.bytesReceived=J.bytesReceived,$A.stat.packetsLost=J.packetsLost,c.audio.p2pDelay=$A.stat.end2EndDelay,c.hasAudio=!0}else{if(er&&J.bytesReceived===0)return;let $A;J.ssrc===C.video&&y.hasVideo&&(c.video.packetsReceived=J.packetsReceived,c.video.bytesReceived=J.bytesReceived,c.video.packetsLost=J.packetsLost,c.video.framesReceived=J.framesReceived,c.video.framesDecoded=J.framesDecoded,c.video.fpsDecoded=J.framesPerSecond,c.hasVideo=!0,A.videoCodec=Cl[(gA=this._decodeMap.get(J.codecId))==null?void 0:gA.mimeType.split("/")[1]]||"h264",c.video.codec=A.videoCodec,$A=A.remoteVideoTrack,y.hasSmall&&S.smallVideo&&(c.isSmallSubscribed=!0),J.decoderImplementation&&(!this._prevDecoderImplementationMap.has(c.userId)||this._prevDecoderImplementationMap.get(c.userId)!==J.decoderImplementation)&&($A.log.info("decoderImplementation change to ".concat(J.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(J.powerEfficientDecoder)),F.emit("262",{userId:this.room.userId,remoteUserId:c.userId,prevImplementation:this._prevDecoderImplementationMap.get(c.userId),implementation:J.decoderImplementation,codec:A.videoCodec,isHWCodec:J.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(c.userId,J.decoderImplementation)),Je(J.keyFramesDecoded)||$A.updateKeyFramesDecoded(J.keyFramesDecoded)),J.ssrc===C.auxiliary&&y.hasAuxiliary&&(c.auxiliary.packetsReceived=J.packetsReceived,c.auxiliary.bytesReceived=J.bytesReceived,c.auxiliary.packetsLost=J.packetsLost,c.auxiliary.framesReceived=J.framesReceived,c.auxiliary.framesDecoded=J.framesDecoded,c.auxiliary.fpsDecoded=J.framesPerSecond,$A=A.remoteAuxiliaryTrack,c.auxiliary.p2pDelay=$A.stat.end2EndDelay,c.hasAuxiliary=!0,c.video.codec=((CA=this._decodeMap.get(J.codecId))==null?void 0:CA.mimeType.split("/")[1].toLowerCase())||"h264",Je(J.keyFramesDecoded)||$A.updateKeyFramesDecoded(J.keyFramesDecoded)),$A&&($A.stat.packetsReceived=J.packetsReceived,$A.stat.bytesReceived=J.bytesReceived,$A.stat.packetsLost=J.packetsLost,$A.stat.framesReceived=J.framesReceived,$A.stat.framesDecoded=J.framesDecoded,J.jitterBufferDelay&&($A.stat.jitterBufferDelay=Math.floor(J.jitterBufferDelay/J.jitterBufferEmittedCount*1e3)),c.video.p2pDelay=$A.stat.end2EndDelay)}J.jitterBufferDelay&&(MA?(c.audio.totalJitter=J.jitterBufferDelay,c.audio.totalJitterCount=J.jitterBufferEmittedCount,c.audio.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===C.video&&y.hasVideo?(c.video.totalJitter=J.jitterBufferDelay,c.video.totalJitterCount=J.jitterBufferEmittedCount,c.video.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===C.auxiliary&&y.hasAuxiliary&&(c.auxiliary.totalJitter=J.jitterBufferDelay,c.auxiliary.totalJitterCount=J.jitterBufferEmittedCount))}else J.type==="candidate-pair"&&_M(J)&&(this.totalBytesReceived=J.bytesReceived,bn(J.currentRoundTripTime)&&(c.rtt=Math.floor(1e3*J.currentRoundTripTime)));Je(J.frameWidth)||((J.trackIdentifier===A.getMainStreamVideoTrackId()||J.ssrc===C.video)&&(c.video.frameWidth=J.frameWidth,c.video.frameHeight=J.frameHeight,A.remoteVideoTrack.stat.frameWidth=J.frameWidth,A.remoteVideoTrack.stat.frameHeight=J.frameHeight),(J.trackIdentifier===A.getAuxStreamVideoTrackId()||J.ssrc===C.auxiliary)&&(c.auxiliary.frameWidth=J.frameWidth,c.auxiliary.frameHeight=J.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=J.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=J.frameHeight)),!Je(J.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&J.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(c.audio.audioLevel=J.audioLevel||0,c.audio.totalAudioEnergy=J.totalAudioEnergy||0)}),c.audio.audioLevel===0&&A.muteState.audioAvailable&&(c.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=c.audio.bytesReceived+c.video.bytesReceived+c.auxiliary.bytesReceived),Je((e=A.remoteVideoTrack.player.stat)==null?void 0:e.fps)||(c.video.fpsRender=A.remoteVideoTrack.player.stat.fps),Je((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(c.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let k=c.audio.estimatedPlayoutTimestamp,V=c.video.estimatedPlayoutTimestamp;if(k&&V&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let J=V-k;Math.abs(J)<=1e4&&(c.avSyncDelay=J,Math.abs(J)>150&&this._log.warn("av sync delay",J))}}catch(C){this._log.warn("failed to getStats on receiver connection ".concat(C))}return c.rtt===0&&(c.rtt=((a=this.room.networkQuality)==null?void 0:a.uplinkRTT)||0),c})}getStats(A,e){return KA(this,null,function*(){let o,a={},c=[];if(this.room.singlePC){let d=this.room.singlePC.getPeerConnection();if(!d)return{senderStats:a,receiverStats:c};let C=ko(),y=yield d.getStats(),S=ko();S-C>2e3&&this._log.warn("getStats cost ".concat(S-C,"ms"));let k=[],V=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);y.forEach(J=>V.has(J.type)&&k.push(J)),this._spcStats=k}A&&(a=yield this.getSenderStats(A));for(let[d,C]of e){let y=yield this.getReceiverStats(C);y&&c.push(y)}return e.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:a,receiverStats:c,mediaPlayoutStats:o}})}getDifferenceValue(A,e){if(Am(A))return e;let o=e-A;return o<0?0:o}prepareReport(A){let{stats:e,report:o,freezeMap:a,uplinkConnection:c}=A;var d,C,y,S,k,V,J,gA,CA;if(!Am(e.senderStats)){let Ge={uint32_audio_level:e.senderStats.audio.audioLevel*od,uint32_audio_energy:1e6*(e.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent};e.senderStats.audio.micAudioLevel&&(Ge.uint32_mic_audio_level=e.senderStats.audio.micAudioLevel*od),Je(e.senderStats.audio.audioCaptureEnergyAfter3a)||(Ge.uint32_audio_capture_energy_after3a=e.senderStats.audio.audioCaptureEnergyAfter3a*od),e.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=e.senderStats.audio.totalSamplesDuration);let Bt=[];if(e.senderStats.video.bytesSent){let Di={uint32_video_stream_type:2,uint32_video_codec_fps:e.senderStats.video.framesSent,uint32_video_capture_fps:e.senderStats.video.fpsCapture,uint32_video_width:e.senderStats.video.frameWidth,uint32_video_height:e.senderStats.video.frameHeight,uint32_video_codec_bitrate:e.senderStats.video.bytesSent,uint32_video_enc_fps:e.senderStats.video.framesEncoded,uint32_key_frame_count:e.senderStats.video.keyFramesEncoded,uint32_nack_count:e.senderStats.video.nackCount,uint32_pli_count:e.senderStats.video.pliCount,uint32_encode_cost:1e3*(e.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.video.retransmittedPacketsSent};Bt.push(Di)}if(e.senderStats.small.bytesSent){let Di={uint32_video_stream_type:3,uint32_video_codec_fps:e.senderStats.small.framesSent||0,uint32_video_capture_fps:e.senderStats.small.fpsCapture||0,uint32_video_width:e.senderStats.small.frameWidth||0,uint32_video_height:e.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.small.bytesSent,uint32_video_enc_fps:e.senderStats.small.framesEncoded||0,uint32_key_frame_count:e.senderStats.small.keyFramesEncoded,uint32_nack_count:e.senderStats.small.nackCount,uint32_pli_count:e.senderStats.small.pliCount,uint32_encode_cost:1e3*(e.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.small.retransmittedPacketsSent};Bt.push(Di)}if(e.senderStats.auxiliary.bytesSent){let Di={uint32_video_stream_type:7,uint32_video_codec_fps:e.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:e.senderStats.auxiliary.fpsCapture||0,uint32_video_width:e.senderStats.auxiliary.frameWidth||0,uint32_video_height:e.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:e.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:e.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:e.senderStats.auxiliary.nackCount,uint32_pli_count:e.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(e.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.auxiliary.retransmittedPacketsSent};Bt.push(Di)}let hi={uint32_bitrate:0,uint32_lost:0,uint32_rtt:e.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:Ge,msg_video_status:Bt,msg_network_status:hi}}let{statInterval:MA}=this;o.msg_down_stream_info=[],e.receiverStats.forEach(Ge=>{let Bt={msg_user_info:{str_identifier:Ge.userId,uint64_tinyid:Ge.tinyId},msg_network_status:{uint32_rtt:Ge.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(Ge.hasAudio){let hi={uint32_audio_p2p_delay:Ge.audio.p2pDelay,uint32_audio_cache_ms:Ge.audio.totalJitter,uint32_audio_cache_ms_count:Ge.audio.totalJitterCount,uint32_audio_codec_bitrate:Ge.audio.bytesReceived,uint32_audio_total_bitrate:Ge.audio.bytesReceived,uint32_audio_level:1e8*Ge.audio.audioLevel,uint32_audio_energy:1e6*Ge.audio.totalAudioEnergy,uint32_audio_receive:Ge.audio.packetsReceived,uint32_audio_origin_lost:Ge.audio.packetsLost};Bt.msg_audio_status=hi}if(Ge.hasVideo){let hi=a.get("".concat(Ge.userId,"_").concat(a0)),Di=hi?hi.duration:0,Vo={uint32_video_stream_type:Ge.isSmallSubscribed?3:2,uint32_video_receive_fps:Ge.video.framesReceived,uint32_video_width:Ge.video.frameWidth,uint32_video_height:Ge.video.frameHeight,uint32_video_codec_bitrate:Ge.video.bytesReceived,uint32_video_receive:Ge.video.packetsReceived,uint32_video_origin_lost:Ge.video.packetsLost,uint32_video_block_time:Di,uint32_video_dec_fps:Ge.video.framesDecoded,uint32_video_codec_fps:Ge.video.fpsRender,uint32_video_cache_ms:Ge.video.totalJitter,uint32_video_cache_ms_count:Ge.video.totalJitterCount,uint32_video_p2p_delay:Ge.video.p2pDelay,uint32_video_codec:Ge.video.codec,int32_video_audio_relative_delay:Ge.avSyncDelay+5e3};Bt.msg_video_status.push(Vo)}if(Ge.hasAuxiliary){let hi=a.get("".concat(Ge.userId,"_").concat(Rb)),Di=hi?hi.duration:0,Vo={uint32_video_stream_type:7,uint32_video_receive_fps:Ge.auxiliary.framesReceived,uint32_video_width:Ge.auxiliary.frameWidth,uint32_video_height:Ge.auxiliary.frameHeight,uint32_video_codec_bitrate:Ge.auxiliary.bytesReceived,uint32_video_receive:Ge.auxiliary.packetsReceived+Ge.auxiliary.packetsLost,uint32_video_origin_lost:Ge.auxiliary.packetsLost,uint32_video_block_time:Di,uint32_video_dec_fps:Ge.auxiliary.framesDecoded,uint32_video_codec_fps:Ge.video.fpsRender,uint32_video_cache_ms:Ge.auxiliary.totalJitter,uint32_video_cache_ms_count:Ge.auxiliary.totalJitterCount,uint32_video_p2p_delay:Ge.auxiliary.p2pDelay,uint32_video_codec:Ge.video.codec};Bt.msg_video_status.push(Vo)}o.msg_down_stream_info.push(Bt)}),e.mediaPlayoutStats&&!Am(e.mediaPlayoutStats)&&(e.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,e.mediaPlayoutStats.totalSamplesDuration*=1e3);let $A=this._prevReport,Be=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(e)),o.msg_up_stream_info.msg_audio_status&&$A.msg_up_stream_info.msg_audio_status){let Ge=$A.msg_up_stream_info.msg_audio_status,Bt=o.msg_up_stream_info.msg_audio_status;if(Ge.uint32_audio_codec_bitrate===0)Bt.uint32_audio_codec_bitrate=0;else{let hi=this.getDifferenceValue(Ge.uint32_audio_codec_bitrate,Bt.uint32_audio_codec_bitrate);Bt.uint32_audio_codec_bitrate=Math.round(8*hi/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Bt.uint32_audio_codec_bitrate}(d=$A.msg_device_info)!=null&&d.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue($A.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/MA),o.msg_device_info.uint32_audio_capture_cost>0&&((y=c?.localMainAudioTrack)==null||y.updateAfter3aSilenceStartTime((C=e.senderStats.audio.audioCaptureEnergyAfter3a)!=null?C:e.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let Ye=$A.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(Ge=>{let Bt=Ye.find(Qn=>Qn.uint32_video_stream_type===Ge.uint32_video_stream_type);if(!Bt||Bt.uint32_video_codec_bitrate===0)return Ge.uint32_video_codec_bitrate=0,Ge.uint32_video_enc_fps=0,void(Ge.uint32_video_codec_fps=0);let hi=0,Di=0,Vo=0;Bt&&Ge.uint32_video_codec_bitrate>=Bt.uint32_video_codec_bitrate&&(hi=Bt.uint32_video_codec_bitrate,Di=Bt.uint32_video_enc_fps,Vo=Bt.uint32_video_codec_fps);let Jo=this.getDifferenceValue(hi,Ge.uint32_video_codec_bitrate);Ge.uint32_video_codec_bitrate=Math.round(8*Jo/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Ge.uint32_video_codec_bitrate,Ge.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Di,Ge.uint32_video_enc_fps)/MA),Ge.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Vo,Ge.uint32_video_codec_fps)/MA),Bt.uint32_video_width===0&&Bt.uint32_video_height===0&&Bt.uint32_video_codec_fps===0&&(Ge.uint32_video_codec_fps=Ge.uint32_video_enc_fps),Je(Bt.uint32_key_frame_count)||(Ge.uint32_key_frame_count=Math.round(this.getDifferenceValue(Bt.uint32_key_frame_count,Ge.uint32_key_frame_count))),Je(Bt.uint32_nack_count)||(Ge.uint32_nack_count=Math.round(this.getDifferenceValue(Bt.uint32_nack_count,Ge.uint32_nack_count))),Je(Bt.uint32_pli_count)||(Ge.uint32_pli_count=Math.round(this.getDifferenceValue(Bt.uint32_pli_count,Ge.uint32_pli_count))),Je(Bt.uint32_video_arq_packets)||(Ge.uint32_video_arq_packets=Math.round(this.getDifferenceValue(Bt.uint32_video_arq_packets,Ge.uint32_video_arq_packets))),Je(Bt.uint32_encode_cost)||(Ge.uint32_encode_cost=Math.round(this.getDifferenceValue(Bt.uint32_encode_cost,Ge.uint32_encode_cost)/MA)),Je(Bt.uint32_send_packet_cost)||(Ge.uint32_send_packet_cost=Math.round(this.getDifferenceValue(Bt.uint32_send_packet_cost,Ge.uint32_send_packet_cost)/MA))});let ve=$A.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(Ge=>ve.find(Bt=>Bt.msg_user_info.uint64_tinyid===Ge.msg_user_info.uint64_tinyid));let yi=o.msg_down_stream_info;if(yi.forEach(Ge=>{let Bt=ve.find(hi=>hi.msg_user_info.uint64_tinyid===Ge.msg_user_info.uint64_tinyid);if(Am(Ge.msg_audio_status)||Am(Bt.msg_audio_status))Ge.msg_audio_status={};else{let hi=Ge.msg_audio_status,Di=Bt.msg_audio_status,Vo=this.getDifferenceValue(Di.uint32_audio_cache_ms_count,hi.uint32_audio_cache_ms_count);delete hi.uint32_audio_cache_ms_count,hi.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Di.uint32_audio_cache_ms,hi.uint32_audio_cache_ms)/Vo)||0;let Jo=this.room.remotePublishedUserMap.get(Ge.msg_user_info.str_identifier);Jo&&(Jo.remoteAudioTrack.stat.jitterBufferDelay=hi.uint32_audio_cache_ms),hi.uint32_audio_origin_lost=this.getDifferenceValue(Di.uint32_audio_origin_lost,hi.uint32_audio_origin_lost),hi.uint32_audio_receive=this.getDifferenceValue(Di.uint32_audio_receive,hi.uint32_audio_receive),hi.uint32_audio_receive+=hi.uint32_audio_origin_lost;let Qn=this.getDifferenceValue(Di.uint32_audio_codec_bitrate,hi.uint32_audio_codec_bitrate);hi.uint32_audio_codec_bitrate=Math.round(8*Qn/MA),hi.uint32_audio_total_bitrate=Math.round(8*Qn/MA)}if(Ge.msg_video_status&&Bt.msg_video_status){let hi=Bt.msg_video_status;Ge.msg_video_status=Ge.msg_video_status.filter(Di=>hi.find(Vo=>Vo.uint32_video_stream_type===Di.uint32_video_stream_type)),Ge.msg_video_status.forEach(Di=>{let Vo=hi.find(m_=>m_.uint32_video_stream_type===Di.uint32_video_stream_type),Jo=Vo.uint32_video_receive,Qn=Vo.uint32_video_origin_lost,Ho=Vo.uint32_video_codec_bitrate,Ns=Vo.uint32_video_receive_fps,pg=Vo.uint32_video_dec_fps;Di.uint32_video_origin_lost=this.getDifferenceValue(Qn,Di.uint32_video_origin_lost),Di.uint32_video_receive=this.getDifferenceValue(Jo,Di.uint32_video_receive)+Di.uint32_video_origin_lost;let ya=this.getDifferenceValue(Ho,Di.uint32_video_codec_bitrate);Di.uint32_video_codec_bitrate=Math.round(8*ya/MA);let Bu=this.getDifferenceValue(Ns,Di.uint32_video_receive_fps);Di.uint32_video_receive_fps=Math.round(Bu/MA),Di.uint32_video_dec_fps=Math.round(this.getDifferenceValue(pg,Di.uint32_video_dec_fps)/MA);let BL=this.getDifferenceValue(Vo.uint32_video_cache_ms_count,Di.uint32_video_cache_ms_count);delete Di.uint32_video_cache_ms_count,Di.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Vo.uint32_video_cache_ms,Di.uint32_video_cache_ms)/BL)||0})}}),!Je((S=Be?.mediaPlayoutStats)==null?void 0:S.totalSamplesDuration)&&!Je((k=e.mediaPlayoutStats)==null?void 0:k.totalSamplesDuration)){let Ge=2*Math.floor(this.getDifferenceValue((V=Be?.mediaPlayoutStats)==null?void 0:V.synthesizedSamplesDuration,(J=e.mediaPlayoutStats)==null?void 0:J.synthesizedSamplesDuration)/MA),Bt=2*Math.floor(this.getDifferenceValue((gA=Be?.mediaPlayoutStats)==null?void 0:gA.totalSamplesDuration,(CA=e.mediaPlayoutStats)==null?void 0:CA.totalSamplesDuration)/MA);o.msg_device_info.uint32_audio_play_cost=Bt-Ge}return Be&&e.receiverStats.forEach(Ge=>{if(Ge.audio.concealedSamples&&Ge.audio.totalSamplesReceived){let Bt=Be.receiverStats.find(hi=>hi.userId===Ge.userId);if(Bt&&Bt.audio.concealedSamples&&Bt.audio.totalSamplesReceived){let hi=(Ge.audio.silentConcealedSamples||0)-(Bt.audio.silentConcealedSamples||0),Di=Ge.audio.concealedSamples-Bt.audio.concealedSamples,Vo=Ge.audio.totalSamplesReceived-Bt.audio.totalSamplesReceived,Jo=Math.floor((Di-hi)/Vo*1e3*MA);if(Jo>1e3*MA/5){let Qn=yi.find(Ho=>Ho.msg_user_info.str_identifier===Ge.userId);Qn&&(Qn.msg_audio_status.uint32_audio_block_time=Jo)}}}}),o.msg_down_stream_info.forEach(Ge=>{Ge.msg_video_status.forEach(Bt=>{Bt.uint32_video_codec_bitrate===0&&Bt.uint32_video_receive_fps===0&&(Bt.uint32_video_width=0,Bt.uint32_video_height=0)})}),o}getStatsReport(A){return KA(this,arguments,function(e){var o=this;let{uplinkConnection:a,downlinkConnections:c,freezeMap:d}=e;return function*(){let C={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0,uint32_video_codec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},y=yield o.getStats(a,c);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(C))),o.prepareReport({stats:y,report:C,freezeMap:d,uplinkConnection:a}),o._prevReportTime=Date.now(),C}()})}getMediaPlayoutStats(A){let e;if(wa(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:a,totalSamplesDuration:c}=o;e={synthesizedSamplesDuration:a,totalSamplesDuration:c};break}return e}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(A=>{A!=null&&A.stat&&(A.stat.framesCaptured=0)})}},EoA=gc(Kl());function doA(A){return new Promise(e=>KA(null,null,function*(){let o=setTimeout(()=>{e({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),a=Date.now(),c="https://".concat(A,"/?t=").concat(a);try{yield fetch(c)}catch{}clearTimeout(o);let d=function(C){let y={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let S=performance.getEntriesByType("resource").reverse();for(let k of S)if(k.name===C){let V=Math.round(k.duration),J=Math.max(Math.round(k.domainLookupStart-k.startTime),0),gA=k.redirectStart>0?Math.max(Math.round(k.redirectEnd-k.redirectStart),0):0,CA=k.fetchStart>0?Math.max(Math.round(k.domainLookupStart-k.fetchStart),0):0,MA=Math.round(k.domainLookupEnd-k.domainLookupStart),$A=Math.round(k.requestStart-k.secureConnectionStart),Be=Math.round(k.secureConnectionStart-k.connectStart),Ye=Math.round(k.responseStart-k.requestStart),ve=Math.round(k.responseEnd-(k.responseStart||k.startTime));y=Qo(mi({},y),{totalCost:V,local:J,redirect:gA,httpCache:CA,dns:MA,tcp:Be,tls:$A,request:Ye,response:ve});break}}catch{}return y}(c);d.totalCost===0&&(d.totalCost=Date.now()-a),e(d)}))}var v1=class T_ extends EoA.default{constructor(e){let{signalChannel:o,room:a}=e;super(),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_log"),Y(this,"uplinkRTT",0),Y(this,"uplinkLoss",0),Y(this,"downlinkRTT",0),Y(this,"downlinkLoss",0),Y(this,"pingResults",{}),Y(this,"_downlinkPrevStatMap",new Map),Y(this,"_downlinkLossAndRTTMap",new Map),Y(this,"_interval",-1),Y(this,"_uplinkNetworkQuality",0),Y(this,"_downlinkNetworkQuality",0),Y(this,"_uplinkQualityHistory",[]),Y(this,"_downlinkQualityHistory",[]),this._room=a,this._signalChannel=o,this._log=QA.createLogger({parent:a.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e,this._uplinkQualityHistory.push(e),this._uplinkQualityHistory.length>T_.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:o,loss:a}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(o,", loss: ").concat(a," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e,this._downlinkQualityHistory.push(e),this._downlinkQualityHistory.length>T_.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(ls.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(dj,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var o,a;if(e.data.code!==0)return;let c=e.data.data;if(c.delay&&this.updateDelay(c.delay),this._room.signalChannel&&c.wsRtt&&(this._room.signalChannel.rtt=c.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let d=(a=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:a.getPeerConnection();if(d&&this.isPeerConnectionDisconnected(d))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let C=c.expectAudPkg+c.expectVidPkg,y=c.recvAudPkg+c.recvVidPkg,S=C-y;C===0&&y===0||(this.uplinkLoss=S<=0?0:Math.round(S/C*100),this.uplinkRTT=c.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return KA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],o=new Set,a=e.filter(y=>{let S=y.getPeerConnection();return!(!S||o.has(S))&&(o.add(S),!0)}),c=a.filter(y=>{var S;return((S=y.getPeerConnection())==null?void 0:S.connectionState)===Co.CONNECTED});if(a.filter(y=>this.isPeerConnectionDisconnected(y.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let y=0;y{this.isPeerConnectionDisconnected(y)&&(this._downlinkPrevStatMap.delete(y),this._downlinkLossAndRTTMap.delete(y))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:d,loss:C}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=d,this.downlinkLoss=C,this.downlinkNetworkQuality=this.getNetworkQuality(C,d)})}getStat(e){return KA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!dy())return o;let a=e.getReceivers();try{for(let c=0;c{d.type==="candidate-pair"&&bn(d.currentRoundTripTime)&&(o.rtt=Math.round(1e3*d.currentRoundTripTime)),d.type==="inbound-rtp"&&(d.mediaType===YA.AUDIO||d.mediaType===YA.VIDEO)&&(o.totalPacketsLost+=d.packetsLost,o.totalPacketsReceived+=d.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(e){let o={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(a=>{o.rtt+=a.rtt,o.loss+=a.loss}),Object.keys(o).forEach(a=>{o[a]=Math.round(o[a]/e.length)})),o}getNetworkQuality(e,o){return e>50||o>500?5:e>30||o>350?4:e>20||o>200?3:e>10||o>100?2:e>=0||o>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(e){let{state:o}=e;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==Co.DISCONNECTED&&e.connectionState!==Co.FAILED&&e.connectionState!==Co.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=Gr.run("ric",()=>{var e;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];F.emit(nA.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let a=(e=this._room.scheduleResult.config)==null?void 0:e.pingDomainInfo,c={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};a&&(c=Qo(mi({},c),{pingResults:this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold?this.pingResults:{}})),this.emit(T_.EVENT_NETWORK_QUALITY,c);let d=Date.now();if(a&&(this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold)&&d-T_.lastPingTime>1e3*a.interval){T_.lastPingTime=Date.now();let C=a.domain.map(y=>doA(y).then(S=>({domain:y,cost:S.totalCost})));Promise.all(C).then(y=>{this.pingResults.isPoorNetwork=y.some(S=>S.cost>700),this.pingResults.timestamp=d,this.pingResults.data=y,y.forEach(S=>{ii.addSuccessEvent({key:521718,cost:S.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(y)))}).catch(y=>{this._log.warn("Error during pinging domains: ".concat(y))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>e)}hadRecentBadDownlink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>e)}stop(){this._log.debug("stopped"),this._interval!==-1&&(Gr.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:o}=this._room;e.forEach(a=>{let{srcTinyId:c,videoDelay:d,audioDelay:C}=a,y=o.get(c);if(y){let S=this._room.remotePublishedUserMap.get(y);S?.setDelay({videoDelay:d,audioDelay:C})}})}};Y(v1,"HISTORY_SIZE",10),Y(v1,"EVENT_NETWORK_QUALITY","0"),Y(v1,"lastPingTime",0);var Uz=v1,Fz=class{constructor(A){Y(this,"_frameWorkType"),Y(this,"_component"),Y(this,"_language"),Y(this,"connectionType"),Y(this,"_room"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),Y(this,"_keyPrefix"),Y(this,"_log"),Y(this,"_intervalId"),Y(this,"_firstPublishedUserList"),Y(this,"_networkQuality"),Y(this,"_basicInfo"),Y(this,"_pathJoinRoom"),Y(this,"_pathLeaveRoom"),Y(this,"_pathMainVideoMap"),Y(this,"_pathMainAudioMap"),Y(this,"_pathAuxiliaryMap"),Y(this,"_remoteStreamStatMap"),Y(this,"_localStreamStat"),Y(this,"_eventMap",new Map),Y(this,"_captureCostSum",0),Y(this,"_captureCostCount",0),Y(this,"isDestroyed",!1),this._frameWorkType=A.frameWorkType||30,this._component=A.component||0,this.connectionType=A.connectionType||1,this._language=A.language||0,this._room=A.room,this._keyPrefix="key_point",this._log=QA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Ra(this[e])&&(this[e]=function(o){let{fn:a,context:c}=o;return function(){try{for(var d=arguments.length,C=new Array(d),y=0;yQA.error("".concat(a.name,"() error observed ").concat(k))):S}catch(S){QA.error("".concat(a.name,"() error observed ").concat(S))}}}({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:qd,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,fM().then(()=>{this._basicInfo.string_os_version=Yp(),this._basicInfo.string_device_name=rQ()||this._basicInfo.string_os_version})}addEvent(A,e){return this._eventMap.set(A,e),F.on(A,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(nA.JOIN_START,this.handleJoinStart).addEvent(nA.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(nA.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(nA.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(nA.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(nA.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(nA.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(nA.JOIN_FAILED,this.handleJoinFailed).addEvent(nA.LEAVE_START,this.handleLeaveStart).addEvent(nA.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(nA.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(nA.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(nA.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(nA.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(nA.PUBLISH_START,this.handlePublishStart).addEvent(nA.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(nA.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(nA.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(nA.PLAY_TRACK_START,this.handlePlayStart).addEvent(nA.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(nA.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,type:a}=A;!e.isRemote||!this.hitTest(e.room)||o==="PLAYING"&&(a===YA.AUDIO?this.handleAudioPlaying(e):this.handleVideoPlaying(e))}).addEvent(nA.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(nA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(nA.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(nA.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(nA.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(nA.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;if(!this.hitTest(e))return;let c=o.hasAudio||o.hasVideo||o.hasSmall,d=o.hasAuxiliary,C=a.hasAudio||a.hasVideo||a.hasSmall,y=a.hasAuxiliary;!c&&C&&this.handleRemoteStreamAdded(a.userId,"main"),!d&&y&&this.handleRemoteStreamAdded(a.userId,"auxiliary")}).addEvent(nA.SINGLE_CONNECTION_STAT,A=>{let{room:e,stat:o}=A;this.hitTest(e)&&(this._pathJoinRoom.int32_ice_cost=o.ice,this._pathJoinRoom.int32_dtls_cost=o.dtls,this._pathJoinRoom.int32_peer_connection_cost=o.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((A,e)=>F.off(e,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Gr.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(A){this.hitTest(A.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),A.params&&(Je(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Je(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),Je(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:e,detailCost:o}=A;if(this.hitTest(e)&&o){let{totalCost:a,local:c,dns:d,tcp:C,tls:y,request:S,response:k}=o;this._pathJoinRoom.int32_schedule_cost=a,this._pathJoinRoom.int32_schedule_local=c,this._pathJoinRoom.int32_schedule_dns=d,this._pathJoinRoom.int32_schedule_tcp=C,this._pathJoinRoom.int32_schedule_tls=y,this._pathJoinRoom.int32_schedule_request=S,this._pathJoinRoom.int32_schedule_response=k}}handleSignalConnectionStart(A){let{room:e}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(A){let{room:e,error:o}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),o&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=o instanceof ai?Number(o.getExtraCode()||o.getCode()):dt.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=A.code,A.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=A.room.getSignalInfo())}handleJoinFailed(A){let{room:e,error:o}=A;this.hitTest(e)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=o.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=A.publishedUserList||[])}handleSendFirstVideoFrame(A){let{room:e}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(A){var e;if(this.hitTest(A.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let o=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=ko()-o)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(A){if(this.hitTest(A.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess(A){let{room:e}=A;if(this.hitTest(e)&&this._pathJoinRoom.uint64_end_time===0){let o=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=o,this._pathJoinRoom.uint64_end_time=o,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(A){let{room:e,error:o}=A;if(this.hitTest(e)){let a=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=a,this._pathJoinRoom.uint64_end_time=a,o&&(this._pathJoinRoom.int32_end_ret=o instanceof ai?Number(o.getExtraCode()||o.getCode()):dt.UNKNOWN)}}handleRemoteStreamAdded(A,e){var o;let a="".concat(A,"_").concat(e);if(!this._remoteStreamStatMap.has(a)){let c={userId:A,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:Qo(mi({},CoA),{msg_user_info:new mj({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};c.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(a,c)}}handleSubscribeStart(A){let{room:e,remotePublishedUser:o,streamType:a,subscribeState:c}=A;if(!this.hitTest(e))return;let{userId:d,tinyId:C,role:y}=o,S=new mj({userId:d,tinyId:C,role:y==="anchor"?20:21}),k=Date.now(),V="".concat(d,"_").concat(a),J=this._remoteStreamStatMap.get(V);J&&J.subscribeStartTime===0&&(J.subscribeStartTime=k),a==="main"?(o.muteState.hasVideo&&(c.video||c.smallVideo)&&!this._pathMainVideoMap.has(V)&&this._pathMainVideoMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:d,sendSubscribeCMDTime:k}),o.muteState.hasAudio&&c.audio&&!this._pathMainAudioMap.has(V)&&this._pathMainAudioMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:d,sendSubscribeCMDTime:k})):o.muteState.hasAuxiliary&&c.auxiliary&&!this._pathAuxiliaryMap.has(V)&&this._pathAuxiliaryMap.set(V,{sendSubscribeCMDTime:k})}handleSubscribed(A){let{room:e,remotePublishedUser:o,streamType:a}=A;if(this.hitTest(e)){let c="".concat(o.userId,"_").concat(a),d=this._remoteStreamStatMap.get(c);d&&d.subscribedTime===0&&(d.subscribedTime=Date.now())}}handlePlayStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),a=this._remoteStreamStatMap.get(o);a?.playStreamTime===0&&(a.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),a=this._pathMainVideoMap.get(o);a&&a.statsToReport.uint64_combine_first_frame_time===0&&(a.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),a=this._pathMainVideoMap.get(e),c=this._remoteStreamStatMap.get(e);if(c){let{statsToReport:d}=c;if(d.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let C=o-this._pathJoinRoom.uint64_start_time;d.uint32_video_render_first=C,ii.addNumber({key:516820,value:C})}}a?.statsToReport.uint64_render_first_frame_time===0&&(a.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(e);o&&o.statsToReport.uint64_play_first_frame_time===0&&(o.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(A){this.hitTest(A.room)&&(this._networkQuality.totalUplinkLoss+=A.uplink.loss,this._networkQuality.totalUplinkRTT+=A.uplink.rtt,this._networkQuality.count++,A.downlinks.forEach(e=>{let{rtt:o,loss:a,userId:c,videoDelay:d,audioDelay:C}=e,y=this._networkQuality.totalDownlinkRTTAndLossMap.get(c);if(y)y.totalRTT+=o,y.totalLoss+=a,d&&(y.totalVideoDelay=(y.totalVideoDelay||0)+d,y.videoDelayCount=(y.videoDelayCount||0)+1),C&&(y.totalAudioDelay=(y.totalAudioDelay||0)+C,y.audioDelayCount=(y.audioDelayCount||0)+1),y.count++;else{let S,k,V,J;d&&(k=d,V=1),C&&(S=C,J=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(c,{totalRTT:o,totalLoss:a,count:1,totalAudioDelay:S,totalVideoDelay:k,audioDelayCount:J,videoDelayCount:V})}}))}handleHeartbeatStats(A){var e;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:a,msg_down_stream_info:c}=A.report;if(a.msg_video_status[0]){let{uint32_video_codec_bitrate:d,uint32_video_enc_fps:C,uint32_video_width:y,uint32_video_height:S}=a.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=d,this._localStreamStat.totalVideoFPS+=C,this._localStreamStat.totalVideoWidth+=y,this._localStreamStat.totalVideoHeight+=S,this._localStreamStat.videoCount++}if(a.msg_audio_status){let{uint32_audio_level:d}=a.msg_audio_status;Math.floor(d/od*100)>0&&(this._localStreamStat.totalAudioLevel+=d/od,this._localStreamStat.audioLevelCount++)}c.forEach(d=>{let{msg_user_info:C,msg_audio_status:y,msg_video_status:S}=d,k=C.str_identifier,V=this._room.remotePublishedUserMap.get(k);if(S.forEach(J=>{let gA=J.uint32_video_stream_type===2,CA=J.uint32_video_stream_type===7,MA="".concat(k,"_").concat(gA?"main":"auxiliary"),$A=this._remoteStreamStatMap.get(MA);if($A&&(gA&&V!=null&&V.remoteVideoTrack.isSubscribed||CA&&V!=null&&V.remoteAuxiliaryTrack)){$A.totalVideoFPS+=J.uint32_video_receive_fps,$A.totalVideoBitrate+=J.uint32_video_codec_bitrate,$A.videoCount++,$A.statsToReport.uint32_video_width===0&&($A.statsToReport.uint32_video_width=J.uint32_video_width),$A.statsToReport.uint32_video_height===0&&($A.statsToReport.uint32_video_height=J.uint32_video_height);let Be=gA?V.remoteVideoTrack:V.remoteAuxiliaryTrack;Be.stat.jitterBufferDelay&&($A.videoJitterBufferDelay=Be.stat.jitterBufferDelay),Be.stat.framesReceived&&($A.statsToReport.uint32_video_consume_render_rate=Math.floor(Be.stat.framesDecoded/Be.stat.framesReceived*xS(10,6)))}}),!S0(y)){let J="".concat(k,"_main"),gA=this._remoteStreamStatMap.get(J);this._remoteStreamStatMap.has(J)&&gA&&V!=null&&V.remoteAudioTrack.isSubscribed&&(gA.totalAudioBitrate+=y.uint32_audio_codec_bitrate,gA.audioCount++,V.remoteAudioTrack.stat.jitterBufferDelay&&(gA.audioJitterBufferDelay=V.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(y.uint32_audio_level/od*100)>0&&(gA.totalAudioLevel+=y.uint32_audio_level/od,gA.audioLevelCount++),y.uint32_audio_block_time&&(gA.statsToReport.uint32_audio_block_time+=y.uint32_audio_block_time))}}),o.uint32_audio_capture_cost&&(this._captureCostSum+=o.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),o.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:e}=A;this.hitTest(e)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(A){let{track:e,error:o}=A,a={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof ai?o.getExtraCode()||o.getCode():dt.UNKNOWN);e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=a,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=a,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&qS)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&jS)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&KS)>=0}hitTest(A){return A===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let A=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,e)=>{let{userId:o}=A,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a){let{totalLoss:k,count:V,audioDelayCount:J,videoDelayCount:gA,totalAudioDelay:CA,totalVideoDelay:MA}=a;A.statsToReport.uint32_avg_down_loss=Math.floor(k/V),J&&CA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(CA/J),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),gA&&MA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(MA/gA))}A.videoCount>0&&(A.statsToReport.uint32_video_avg_fps=Math.floor(A.totalVideoFPS/A.videoCount),A.statsToReport.uint32_video_avg_bitrate=Math.floor(A.totalVideoBitrate/A.videoCount)),A.audioCount>0&&(A.statsToReport.uint32_audio_recv_bitrate=A.statsToReport.uint32_audio_bitrate=Math.floor(A.totalAudioBitrate/A.audioCount)),A.audioLevelCount>0&&(A.statsToReport.uint32_audio_play_db=Math.floor(A.totalAudioLevel/A.audioLevelCount*100));let{callDurationCalculator:c}=this._room;c&&(A.statsToReport.uint32_audio_play_time=c.getDuration(e,YA.AUDIO),A.statsToReport.uint32_video_play_time=c.getDuration(e,YA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,XM));let{badCaseDetector:d}=this._room,{dataFreeze:C,count:y}=d.getDataFreezeDuration(e),{renderFreeze:S}=d.getRenderFreezeDuration(e);A.statsToReport.uint32_video_block_count=y,A.statsToReport.uint32_video_block_time=Math.min(C,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(S,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_audio_block_time=Math.min(A.statsToReport.uint32_audio_block_time,A.statsToReport.uint32_audio_play_time),d.isBlackStream(e)&&A.statsToReport.uint32_video_avg_fps===0?A.statsToReport.uint32_video_black_screen_subjective=1:A.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((A,e)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>XM&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+XM):this._pathMainAudioMap.delete(e)}),this._pathMainVideoMap.forEach((A,e)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>XM&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+XM):this._pathMainVideoMap.delete(e)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>XM&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+XM)}getReportData(){this._basicInfo.uint32_networkType=qf();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new mj({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:sM(this._signalInfo.relayIp),uint32_client_ip:sM(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*xS(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:sM(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return R0(A),A}report(){return KA(this,null,function*(){try{this.prepareReport();let A=this.getReportData();yield this.upload(A),this.initData()}catch(A){this._log.warn(A)}finally{this.isDestroyed&&(this._room=null)}})}upload(A){return KA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),o=_A.enable?AQ(A,2001,e):yield zb(A),a=o instanceof ArrayBuffer,c="".concat(Hf(e,bI.KEY_POINT),"&gzip=").concat(+a),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(c,o));let C=[this.uploadKVStat(ii),this.uploadKVStat(Zh)];d||C.push(eQ({url:c,body:o,priority:"low"})),yield Promise.all(C)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return KA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var c,d;let C=e.getReportData((c=o._room)==null?void 0:c.userSig,(d=o._signalInfo)==null?void 0:d.reportToken);if(C.stats_count.length===0&&C.stats_distribution.length===0)return;C.msg_sdk_basic_info=Qo(mi({},C.msg_sdk_basic_info),{bytes_device_name:o._basicInfo.string_device_name||"",bytes_os_version:o._basicInfo.string_os_version||"",uint32_framework:o._frameWorkType,uint32_network_type:o._basicInfo.uint32_networkType||0}),o._log.debug(C);let y=_A.enable?AQ(C,2003,a):yield zb(C),S=y instanceof ArrayBuffer,k="".concat(Hf(+a,bI.KV_STAT),"&gzip=").concat(+S),V=!1;navigator.sendBeacon&&(V=navigator.sendBeacon(k,y)),V||eQ({url:k,body:y})}()})}};Ci([$h({settings:{timeout:500,retries:3}})],Fz.prototype,"upload");var XM=5e3,CoA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},mj=class{constructor(A){Y(this,"str_identifier"),Y(this,"str_tinyid"),Y(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},hoA=Fz,Oz=class{constructor(){Y(this,"_startTime"),Y(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ko())}stop(){this._endTime===0&&(this._endTime=ko())}getDuration(){return this._endTime===0?ko()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},BoA=class{constructor(A){Y(this,"_room",null),Y(this,"_durationMap"),Y(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(nA.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(nA.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;var c;let{userId:d}=a;if(!this.hitTest(e))return;o.hasAudio&&!a.hasAudio&&this.stopDurationItem("".concat(d,"_main"),YA.AUDIO),o.hasVideo&&!a.hasVideo&&this.stopDurationItem("".concat(d,"_main"),YA.VIDEO),o.hasAuxiliary&&!a.hasAuxiliary&&this.stopDurationItem("".concat(d,"_auxiliary"),YA.VIDEO);let C=(c=this._room)==null?void 0:c.remotePublishedUserMap.get(d);C&&(!o.hasAudio&&a.hasAudio&&C.remoteAudioTrack.isSubscribed&&this.addDuractionItem(d,YA.AUDIO,"main"),!o.hasVideo&&a.hasVideo&&C.remoteVideoTrack.isSubscribed&&this.addDuractionItem(d,YA.VIDEO,"main"),!o.hasAuxiliary&&a.hasAuxiliary&&C.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(d,YA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,e)=>F.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>F.off(e,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:e}=A;if(!this.hitTest(e.room))return;let{userId:o,streamType:a,kind:c}=e;e.isSubscribed?this.addDuractionItem(o,c,a):this.stopDurationItem("".concat(o,"_").concat(a),c)}handleUnsubscribed(A){let{track:e}=A;this.hitTest(e.room)&&this.stopDurationItem("".concat(e.userId,"_").concat(e.streamType),e.kind)}isRecording(A){return A.findIndex(e=>e.endTime===0)>=0}addDuractionItem(A,e,o){let a="".concat(A,"_").concat(o),c=new Oz,d=this._durationMap.get(a);d?this.isRecording(d[e])||d[e].push(c):this._durationMap.set(a,{userId:A,type:o,audio:e===YA.AUDIO?[c]:[],video:e===YA.AUDIO?[]:[c]})}stopDurationItem(A,e){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[e].find(a=>a.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,e){return this._durationMap.has(A)?this._durationMap.get(A)[e].reduce((o,a)=>o+a.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},QoA=class{constructor(){Y(this,"renderFreezeMap",new Map),Y(this,"dataFreezeMap",new Map)}get(A,e){let o=this.renderFreezeMap.get(A),a=this.dataFreezeMap.get(A);return e?e==="data"?a:o:(Bg||er)&&o&&a&&o.duration>a.duration?o:a}set(A,e,o){o==="data"?this.dataFreezeMap.set(A,e):this.renderFreezeMap.set(A,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},poA=class{constructor(A){Y(this,"_room"),Y(this,"_renderFreezeMap",new Map),Y(this,"_isVideoPlayingEventFiredMap",new Map),Y(this,"_dataFreezeMap",new Map),Y(this,"_monitorFreezeData",new QoA),Y(this,"_eventMap",new Map),Y(this,"_videoEncodeFailedCount",0),Y(this,"_audioEncodeFailedCount",0),Y(this,"_encodeFailedThreshold",3),Y(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),Y(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),Y(this,"_videoAbnormalTimestampMap",new Map),Y(this,"_remoteVideoAbnormalTimestampMap",new Map),Y(this,"_audioAbnormalTimestampMap",new Map),Y(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(nA.LEAVE_SUCCESS,A=>{let{room:e}=A;this.hitTest(e)&&this.stop()}).set(nA.PLAY_TRACK_START,this.onPlayTrackStart).set(nA.UNSUBSCRIBE_SUCCESS,A=>{let{room:e,streamType:o,remotePublishedUser:a}=A;if(!this.hitTest(e))return;let{userId:c}=a,d="".concat(c,"_").concat(o);this.stopDataFreeze({key:d,userId:c,type:o})}).set(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;if(!this.hitTest(e))return;let{userId:c}=a;if(o.hasVideo&&!a.hasVideo){let d="main",C="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:C,userId:c,type:d})}if(o.hasAuxiliary&&!a.hasAuxiliary){let d="auxiliary",C="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:C,userId:c,type:d})}}).set(nA.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,reason:a,type:c}=A;if(e.isRemote&&e.room&&this.hitTest(e.room)&&c===YA.VIDEO){if(o==="PLAYING"){let d="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.set(d,!0)}a===YA.MUTE?this.onVideoTrackMuted(e):a===YA.UNMUTE&&this.onVideoTrackUnmuted(e)}}).set(nA.HEARTBEAT_REPORT,this.onHearBeatReport).set(nA.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(nA.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,e)=>F.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>F.off(e,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,a="".concat(e,"_").concat(o),c=this._dataFreezeMap.get(a),d=new Oz;c?c.durationItemList.push(d):this._dataFreezeMap.set(a,{userId:e,type:o,durationItemList:[d],isFreezing(){let C=this.durationItemList[this.durationItemList.length-1];return C&&C.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,a="".concat(e,"_").concat(o);this.stopDataFreeze({key:a,userId:e,type:o})}onHearBeatReport(A){let{room:e,report:o}=A;this.hitTest(e)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(e=>{var o;if(e.msg_video_status.length===0)return;let a=e.msg_user_info.str_identifier,c=(o=this._room.remotePublishedUserMap.get(a))==null?void 0:o.remoteVideoTrack;e.msg_video_status.forEach(d=>{let C=ko();if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>0&&d.uint32_video_receive_fps===0&&c!=null&&c.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-decode"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-decode"));y&&C-y>this.ABNORMAL_TIME_LOWER_LIMIT&&C-y=this.ABNORMAL_TIME_UPPER_LIMIT&&(sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-decode")))}if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>5e5&&d.uint32_video_dec_fps!==void 0&&d.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-hardware"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));if(y&&C-y>this.ABNORMAL_TIME_LOWER_LIMIT/2&&C-y<2*this.ABNORMAL_TIME_UPPER_LIMIT){sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_HARDWARE_DECODE_FAILED)});let S=this._room.remotePublishedUserMap.get(a);if(S){let k=d.uint32_video_stream_type===2?S.remoteVideoTrack:S.remoteAuxiliaryTrack;k&&(k.log.warn("decode failed during call"),k.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(a,"-hardware"),C);else{let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));y&&C-y>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let e=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(c=>c.kind==="video"&&!c.isScreen),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;e.forEach(c=>{let d=ko();if(c.uint32_video_stream_type===2)if(c.uint32_video_capture_fps!==0&&c.uint32_video_codec_bitrate===0&&c.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let C=this._videoAbnormalTimestampMap.get("local-encode");C&&d-C>this.ABNORMAL_TIME_LOWER_LIMIT&&d-C=this.ABNORMAL_TIME_UPPER_LIMIT&&sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let e=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(d=>d.kind==="audio"),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;let c=ko();if(e.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let d=this._audioAbnormalTimestampMap.get("local-encode");d&&c-d>this.ABNORMAL_TIME_LOWER_LIMIT&&c-d=this.ABNORMAL_TIME_UPPER_LIMIT&&sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:e,userId:o,type:a}=A,c=this._dataFreezeMap.get(e);if(!c||!c.isFreezing())return;let d=c.durationItemList[c.durationItemList.length-1];d.stop();let C=d.getDuration();if(C>Tb){let y=this._monitorFreezeData.get(e,"data");this._monitorFreezeData.set(e,{userId:o,type:a,duration:y?y.duration+C:C},"data")}else c.durationItemList.pop()}getTotalDuration(A){return A.reduce((e,o)=>{let a=o.getDuration();return e+Math.min(a,5e3)},0)}onPlayTrackStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room)||e.kind!==YA.VIDEO||!e.isRemotePublished)return;let o="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let e={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let a=o.durationItemList[o.durationItemList.length-1];a.stop(),a.getDuration(){document.hidden||(c=0)};document.addEventListener("visibilitychange",d);let C=(y,S)=>{var k;if(c){let V=e.decodeFPS,J=V>0&&V<=5?600+1e3/V:600,gA=S.presentationTime-c;if(gA>J){gA=Math.min(gA,5e3);let CA="".concat(e.userId,"_").concat(e.streamType),MA=this._monitorFreezeData.get(CA,"render");MA?MA.duration+=gA:this._monitorFreezeData.set(CA,{userId:e.userId,type:e.streamType,duration:gA},"render");let $A=this._renderFreezeMap.get(CA);$A?($A.totalDuration+=gA,$A.count+=1):this._renderFreezeMap.set(CA,{userId:e.userId,type:e.streamType,totalDuration:gA,count:1})}}c=S.presentationTime,(k=o.element)==null||k.requestVideoFrameCallback(C)};(a=o.element)==null||a.requestVideoFrameCallback(C),this.eventListenerMap.set("".concat(e.userId,"_").concat(e.streamType),{onVisibilityChange:d})}onRemoteVideoPlayEnd(A){let{track:e,player:o}=A,a="".concat(e.userId,"_").concat(e.streamType),c=this.eventListenerMap.get(a);c&&document.removeEventListener("visibilitychange",c.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},moA=gc(Kl(),1),foA=class{constructor(A,e,o,a,c){let d=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=a,this.logger=c,Y(this,"animationState"),Y(this,"originalAspect"),Y(this,"totalOffsetX",0),Y(this,"totalOffsetY",0),Y(this,"defaultScaleRatio",.1),Y(this,"isRecovering",!1),Y(this,"boundaryY",280),Y(this,"lastActionTime",0),Y(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=d||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(A,e,o){let a=[{key:570704,error:o??(e?void 0:11)},{key:570705,error:o??(e?void 0:22)}][A-1];a&&(e?ii.addSuccessEvent({key:a.key}):ii.addFailedEvent({key:a.key,error:a.error}))}actionCentering(A){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTimee/2?(c=e-o-a,d=o-c):(c=o,d=0),{min:c,offset:d}}calculateTargetPosition(A,e,o,a,c,d){let C,y,S=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,k=A+o/2,V=e+a/2,{min:J,offset:gA}=this.calculateBoundary(k,c,A,o),{min:CA,offset:MA}=this.calculateBoundary(V,d,e,a);return C=2*J+o,y=2*CA+a,C/y>this.originalAspect?(C=y*this.originalAspect,gA=k-C/2):(y=C/this.originalAspect,MA=V-y/2),o/c>S&&(gA=0,MA=0,C=c,y=d),gA=Math.max(0,Math.min(gA,c-C)),MA=Math.max(0,Math.min(MA,d-y)),{sx:gA,sy:MA,cropWidth:C,cropHeight:y,timestamp:Date.now()}}processFacePositionCrop(A,e,o){if(!this.animationState.current||!this.animationState.target){let C={sx:0,sy:0,cropWidth:e,cropHeight:o,timestamp:Date.now()};return this.animationState.current=C,void(this.animationState.target=C)}let a=this.positionDistance(this.animationState.target,A),c=this.positionDistance(this.animationState.current,A),d=this.animationState.current.cropWidth/e;a>this.animationState.debounceThreshold*d&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&c>this.animationState.movementThreshold*d&&(this.animationState.target=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(A){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=mi({},A),void(this.animationState.target=mi({},A));let e=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold&&(this.animationState.current=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let A=Date.now()-this.animationState.startTime,e=Math.min(A/this.animationState.duration,1),o=a=>a<.5?2*a*a:(4-2*a)*a-1;if(this.animationState.current&&this.animationState.target){let a=(this.animationState.target.sx-this.animationState.current.sx)*o(e);this.animationState.current.sx+=a,this.totalOffsetX+=a;let c=(this.animationState.target.sy-this.animationState.current.sy)*o(e);if(this.animationState.current.sy+=c,this.totalOffsetY+=c,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(e)),bn(this.animationState.current.scaleOffsetX)&&bn(this.animationState.target.scaleOffsetX)&&bn(this.animationState.current.scaleOffsetY)&&bn(this.animationState.target.scaleOffsetY)){let d=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(e);this.animationState.current.scaleOffsetX+=d;let C=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(e);this.animationState.current.scaleOffsetY+=C}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,e){return Math.sqrt(xS(A.sx-e.sx,2)+xS(A.sy-e.sy,2))}recoverOriginal(A,e){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,e,o,a,c,d){let C=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let y=this.calculateTargetPosition(o,a,c,d,A,e);this.processFacePositionCrop(y,A,e),c*d/y.cropWidth/y.cropHeight>C&&this.recoverOriginal(A,e)}movingPortrait(A,e,o,a,c,d){var C,y,S,k,V,J,gA,CA,MA,$A,Be,Ye;let ve={sx:o+c/2+this.totalOffsetX,sy:a+d/2+this.totalOffsetY,cropWidth:A,cropHeight:e,scaleRatio:(y=(C=this.animationState.current)==null?void 0:C.scaleRatio)!=null?y:1,scaleOffsetX:(k=(S=this.animationState.current)==null?void 0:S.scaleOffsetX)!=null?k:0,scaleOffsetY:(J=(V=this.animationState.current)==null?void 0:V.scaleOffsetY)!=null?J:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:a+d/2,cropWidth:A,cropHeight:e,scaleRatio:(CA=(gA=this.animationState.target)==null?void 0:gA.scaleRatio)!=null?CA:1,scaleOffsetX:($A=(MA=this.animationState.target)==null?void 0:MA.scaleOffsetX)!=null?$A:0,scaleOffsetY:(Ye=(Be=this.animationState.target)==null?void 0:Be.scaleOffsetY)!=null?Ye:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(c*d/A/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio{A.log.error(o),A.destroy(new ai({code:dt.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return KA(this,null,function*(){var e,o,a;this.predictReady=new Promise(y=>{this.resolvePreditReady=y});let c=A.Wasm,d=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(e=A.enableFaceCentering)!=null&&e,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new c.AllIn1(d),this.wasm.blurRadius=A.blurRadius||3,this.wasm.mirror=!!A.mirror,this.wasm.rotation=A.rotation||0,this.wasm.vbMode=A.bg==="blur"?1:A.bg instanceof HTMLImageElement?2:A.bg==="color"?3:0,this._onAbort=A.onAbort,A.bg||this.resolvePreditReady(),A.waterMark){let{x:y,y:S,width:k,height:V}=A.waterMark;this.wasm.setWaterMark(y,S,k,V)}if(A.beautyParams){let{beauty:y,brightness:S,ruddy:k}=A.beautyParams;this.wasm.setBeauty(y,S,k,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(d.uniform1i(d.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(d.uniform1i(d.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let C=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=d.getUniformLocation(this.program,"u_textureMatrix"),d.uniformMatrix4fv(this._textureMatrixLocation,!1,C),this._offsetMatrixLocation=d.getUniformLocation(this.program,"u_offsetMatrix"),d.uniformMatrix4fv(this._offsetMatrixLocation,!1,C),this._colorLocation=d.getUniformLocation(this.program,"u_color"),d.uniform1i(d.getUniformLocation(this.program,"lastMask"),4),this._weixin){let y=this.context.createShader(d.FRAGMENT_SHADER,`#version 300 es +`))}removeBandwidthRestriction(e){return e.replace(/b=AS:.*\r\n/,"").replace(/b=TIAS:.*\r\n/,"")}removeVideoOrientation(e){return e.replace(/urn:3gpp:video-orientation/,"")}connect(){return WA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return WA(this,null,function*(){try{yield this.createOffer(),this._log.info("createOffer success, sending offer to remote server"),yield this.doExchangeSDP()}catch(e){throw e}})}createOffer(){return WA(this,null,function*(){try{let e=yield this._peerConnection.createOffer(s8);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:Zz,responseCommand:ls.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof WM||this.localAuxVideoTrack instanceof WM,state:this._room.publishState,constraintConfig:this._mediaSettings},enableLog:!1};return this._log.debug("sending sdp offer: ".concat(e.data.sdp)),this._signalChannel.sendWaitForResponse(e).then(o=>{let{code:a,message:l,data:d}=o.data;return a===0?this.acceptAnswer(d):this.checkPublishResultCode(a,l)})}setSDPDirection(e,o){let a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"all",l=uc(e);return l.media.forEach(d=>{(a==="all"||d.type===a)&&(d.direction=o)}),_y(l)}acceptAnswer(e){return WA(this,null,function*(){var o,a,l,d,h;try{let y;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let k=((o=this._publishingLocalVideoTrack)==null?void 0:o.profile.bitrate)||((a=this.localMainVideoTrack)==null?void 0:a.profile.bitrate),V=((l=this._publishingLocalAudioTrack)==null?void 0:l.profile.bitrate)||((d=this.localMainAudioTrack)==null?void 0:d.profile.bitrate);if(k){let J=this._isPublishingAux?YA.AUXILIARY:YA.BIG;y=yield this.setBandwidth({bandwidth:k,type:YA.VIDEO,sdp:y,videoType:J})}V&&(y=yield this.setBandwidth({bandwidth:V,type:YA.AUDIO,sdp:y}))}if(y=this.removeVideoOrientation(e.sdp),(h=this._publishingLocalVideoTrack)!=null&&h.small){let{smallStreamConfig:k}=this._room;y=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||k.bitrate,type:YA.VIDEO,videoType:YA.SMALL,sdp:y})}let S={type:e.type,sdp:y};yield this.setAnswer(S),this._log.debug("accepted answer: ".concat(y))}catch(y){throw this._log.error("failed to accept remote answer ".concat(y)),y}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(zz,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return WA(this,null,function*(){if(!(GI(gX.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:N1,responseCommand:ls.UNPUBLISH_RESULT,enableLog:!1}),this.closePeerConnection(),this.initialize(),this.isMainStreamPublished&&(yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0})),this._log.warn("reconnect() uplink reconnect successfully"),this.stopReconnection()}catch{let o=Tp(this._reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(o/1e3,"s")),this._reconnectionTimer=setTimeout(()=>{this.clearReconnectionTimer(),this.reconnect()},o)}})}handleConnectionStateChange(e){e.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{uc(e).media.forEach((o,a)=>{if(o.type===YA.AUDIO){let l=o.ssrcs&&o.ssrcs[0];l&&(this.ssrc.audio=Number(l.id))}else{if(this._sdpSemantics===E0&&o.ssrcGroups)return void o.ssrcGroups.forEach((d,h)=>{let y=Number(d.ssrcs.split(" ")[0]);h===0?this.ssrc.video=y:h===1&&(this.ssrc.small=y)});let l=o.ssrcs&&o.ssrcs[0];if(!l)return;switch(a){case 1:this.ssrc.video=Number(l.id);break;case 2:this.ssrc.small=Number(l.id);break;case 3:this.ssrc.auxiliary=Number(l.id)}}})}catch{}}getVideoTrackId(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:YA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(e===YA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(e===YA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&e===YA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&e===YA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,o){if(e!==0)throw e===d0?(this._log.error(cc.NOT_SUPPORTED_H264ENCODE),new gi({code:Ct.NOT_SUPPORTED_H264,message:Xo({key:vo.NOT_SUPPORTED_H264ENCODE})})):new gi({code:Ct.UNKNOWN,message:Xo({key:vo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.PUBLISH_RESULT,code:e,message:o}})})}};hi([jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let h=y=>{this._emitter.off("closed",h),d(new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.CONNECTION_ABORTED,data:y})}))};this._emitter.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this._emitter.off("closed",h)})})})],k1.prototype,"publish"),hi([Sy(521715,!1)],k1.prototype,"unpublish"),hi([qM(sm.prototype.afterConnect),w5(sm.prototype.beforeConnect)],k1.prototype,"connect");var L1=k1,YoA=class{constructor(A,e){this.room=A,Y(this,"_log"),Y(this,"_prevReportTime",0),Y(this,"_prevReport",{}),Y(this,"_prevStats",null),Y(this,"_prevEncoderImplementation",""),Y(this,"_prevAuxEncoderImpl",""),Y(this,"_prevQualityLimitationReason",""),Y(this,"_prevAuxQualityLimitationReason",""),Y(this,"_prevDecoderImplementationMap",new Map),Y(this,"_decodeMap",new Map),Y(this,"_prevQpSum",0),Y(this,"_prevAuxQpSum",0),Y(this,"totalBytesSent",0),Y(this,"totalBytesReceived",0),Y(this,"_spcStats",null),this._log=e}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}getSenderStats(A){return WA(this,null,function*(){var e,o,a,l,d,h,y;let S={audio:{bytesSent:0,packetsSent:0,audioLevel:0,totalAudioEnergy:0},video:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},small:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},auxiliary:{bytesSent:0,packetsSent:0,framesEncoded:0,frameWidth:0,frameHeight:0,framesSent:0,fpsCapture:0},rtt:0},k=A.getPeerConnection(),V=A.getSSRC();if(k)try{if((this._spcStats||(yield k.getStats())).forEach(J=>{var cA,CA,MA,ie,pe,qe,we,Di,Le,Qt,Bi,Si,Jo;let Ho,Qn;if(J.type==="outbound-rtp")if((J.mediaType||J.kind)===YA.VIDEO){if(J.ssrc===V.video?(Ho=YA.VIDEO,Qn=A.localMainVideoTrack):J.ssrc===V.small?Ho=YA.SMALL:J.ssrc===V.auxiliary&&(Qn=A.localAuxVideoTrack,Ho=YA.AUXILIARY),!Ho)return;S[Ho].bytesSent=J.bytesSent,S[Ho].packetsSent=J.packetsSent,S[Ho].framesEncoded=J.framesEncoded,Ke(J.keyFramesEncoded)||(S[Ho].keyFramesEncoded=J.keyFramesEncoded),Ke(J.nackCount)||(S[Ho].nackCount=J.nackCount),Ke(J.pliCount)||(S[Ho].pliCount=J.pliCount),Ke(J.retransmittedPacketsSent)||(S[Ho].retransmittedPacketsSent=J.retransmittedPacketsSent),Ke(J.totalEncodeTime)||(S[Ho].totalEncodeTime=J.totalEncodeTime),Ke(J.totalPacketSendDelay)||(S[Ho].totalPacketSendDelay=J.totalPacketSendDelay);let qo=0;if(!Ke(J.qpSum)&&!Ke(J.framesEncoded)&&J.framesEncoded>0){let Ns=J.qpSum,pg=J.framesEncoded,ya=Ho===YA.VIDEO?this._prevQpSum:this._prevAuxQpSum,Qu=Ho===YA.VIDEO?((CA=(cA=A.localMainVideoTrack)==null?void 0:cA.stat)==null?void 0:CA.framesEncoded)||0:((ie=(MA=A.localAuxVideoTrack)==null?void 0:MA.stat)==null?void 0:ie.framesEncoded)||0;if(pg>Qu&&Ns>ya){let DL=Ns-ya,D_=pg-Qu;qo=Math.round(DL/D_),qo>35&&A.videoCodec==="h264"&&this._log.warn("".concat(Ho===YA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(qo,", resolution: ").concat(J.frameWidth,"x").concat(J.frameHeight,", codec: ").concat(A.videoCodec,", "))}Ho===YA.VIDEO?this._prevQpSum=Ns:Ho===YA.AUXILIARY&&(this._prevAuxQpSum=Ns)}if(!Ke(J.encoderImplementation)&&(Ho===YA.VIDEO&&this._prevEncoderImplementation!==J.encoderImplementation||Ho===YA.AUXILIARY&&this._prevAuxEncoderImpl!==J.encoderImplementation)){let Ns=2,pg=this._prevEncoderImplementation;Ho===YA.AUXILIARY&&(Ns=7,pg=this._prevAuxEncoderImpl),F.emit("262",{userId:A.userId,streamType:Ns,prevImplementation:pg,implementation:J.encoderImplementation,codec:A.videoCodec,isHWCodec:J.powerEfficientEncoder}),this[Ho===YA.VIDEO?"_prevEncoderImplementation":"_prevAuxEncoderImpl"]=J.encoderImplementation,Qn?.log.info("encoderImplementation change to ".concat(J.encoderImplementation,"(").concat(A.videoCodec,") HWEncoder: ").concat(J.powerEfficientEncoder))}J.ssrc===V.video?!Ke(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevQualityLimitationReason!==J.qualityLimitationReason&&(Qn?.log.info("qualityLimitationReason change to ".concat(J.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(pe=A.localMainVideoTrack)==null?void 0:pe.isQosClearFirst}),this._prevQualityLimitationReason=J.qualityLimitationReason):J.ssrc===V.auxiliary&&!Ke(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevAuxQualityLimitationReason!==J.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(J.qualityLimitationReason)),F.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(qe=A.localAuxVideoTrack)==null?void 0:qe.isQosClearFirst}),this._prevAuxQualityLimitationReason=J.qualityLimitationReason)}else S.audio.bytesSent=J.bytesSent,S.audio.packetsSent=J.packetsSent;else if(J.type==="candidate-pair")GM(J)&&(this.totalBytesSent=J.bytesSent,kn(J.currentRoundTripTime)&&(S.rtt=Math.floor(1e3*J.currentRoundTripTime)));else if(J.type==="media-source"){if(J.kind===YA.AUDIO)S.audio.audioLevel=J.audioLevel||0,S.audio.totalAudioEnergy=J.totalAudioEnergy||0,J.echoReturnLoss,Ke((Le=(Di=(we=A.localMainAudioTrack)==null?void 0:we.sourceTrack)==null?void 0:Di.stats)==null?void 0:Le.deliveredFramesDuration)?J.totalSamplesDuration&&(S.audio.totalSamplesDuration=J.totalSamplesDuration):S.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(J.kind===YA.VIDEO)if(J.trackIdentifier===A.getVideoTrackId(YA.VIDEO))if((Si=(Bi=(Qt=A.localMainVideoTrack)==null?void 0:Qt.sourceTrack)==null?void 0:Bi.stats)!=null&&Si.deliveredFrames){let{deliveredFrames:qo}=A.localMainVideoTrack.sourceTrack.stats;S.video.framesCaptured=qo,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&qo>=A.localMainVideoTrack.stat.framesCaptured?S.video.fpsCapture=Math.floor((qo-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):S.video.fpsCapture=J.framesPerSecond}else S.video.fpsCapture=J.framesPerSecond;else J.trackIdentifier===A.getVideoTrackId(YA.AUXILIARY)?S.auxiliary.fpsCapture=J.framesPerSecond:S.small.fpsCapture=J.framesPerSecond}if(!Ke(J.audioLevel)&&(Jo=A.localMainAudioTrack)!=null&&Jo.mediaTrack&&J.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(S.audio.audioLevel=J.audioLevel||0),!Ke(J.frameWidth)){let qo=YA.SMALL;J.trackIdentifier===A.getVideoTrackId(YA.VIDEO)||J.ssrc===V.video?qo=YA.VIDEO:(J.trackIdentifier===A.getVideoTrackId(YA.AUXILIARY)||J.ssrc===V.auxiliary)&&(qo=YA.AUXILIARY),S[qo].frameWidth=J.frameWidth,S[qo].frameHeight=J.frameHeight,S[qo].framesSent=J.framesSent}}),A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack){let J=A.localMainAudioTrack||A.getRoom().capturedLocalMainAudioTrack;if(J){let cA=J.getInternalAudioLevel(),CA=J.getInternalAudioLevelAfter3A();S.audio.audioCaptureEnergyAfter3a=CA,S.audio.micAudioLevel=cA,S.audio.audioLevel===0&&A.localMainAudioTrack&&(S.audio.audioLevel=CA??cA),!A.localMainAudioTrack&&!Ke((o=(e=J.sourceTrack)==null?void 0:e.stats)==null?void 0:o.deliveredFramesDuration)&&(S.audio.totalSamplesDuration=J.sourceTrack.stats.deliveredFramesDuration/1e3)}}if(!A.localMainVideoTrack&&A.getRoom().capturedLocalMainVideoTrack){let J=A.getRoom().capturedLocalMainVideoTrack;if((l=(a=J?.sourceTrack)==null?void 0:a.stats)!=null&&l.deliveredFrames){let{deliveredFrames:cA}=J.sourceTrack.stats;S.video.framesCaptured=cA,J.stat.framesCaptured&&J.stat.framesCaptured>0&&cA>=J.stat.framesCaptured&&(S.video.fpsCapture=Math.floor((cA-J.stat.framesCaptured)/this.statInterval)),J.stat.framesCaptured=cA}}if(!A.localAuxVideoTrack&&A.getRoom().capturedLocalAuxVideoTrack){let J=A.getRoom().capturedLocalAuxVideoTrack;if((h=(d=J?.sourceTrack)==null?void 0:d.stats)!=null&&h.deliveredFrames){let{deliveredFrames:cA}=J.sourceTrack.stats;S.auxiliary.framesCaptured=cA,J.stat.framesCaptured&&J.stat.framesCaptured>0&&cA>=J.stat.framesCaptured&&(S.auxiliary.fpsCapture=Math.floor((cA-J.stat.framesCaptured)/this.statInterval)),J.stat.framesCaptured=cA}}this.totalBytesSent||(this.totalBytesSent+=S.audio.bytesSent+S.video.bytesSent+S.auxiliary.bytesSent),Object.keys(S).forEach(J=>{J===YA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=S[J]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=S[J])):J===YA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=S[J]):J===YA.AUXILIARY&&A.localAuxVideoTrack&&(A.localAuxVideoTrack.stat=S[J])})}catch(J){this._log.warn("failed to getStats on sender connection ".concat(J))}return S.rtt===0&&(S.rtt=((y=this.room.networkQuality)==null?void 0:y.uplinkRTT)||0),S})}getReceiverStats(A){return WA(this,null,function*(){var e,o,a;let l={tinyId:A.tinyId,userId:A.userId,rtt:0,hasAudio:!1,hasVideo:!1,hasAuxiliary:!1,isSmallSubscribed:!1,avSyncDelay:0,audio:{bytesReceived:0,packetsReceived:0,packetsLost:0,p2pDelay:0,totalJitter:0,totalJitterCount:0,audioLevel:0,totalAudioEnergy:0,insertedSamplesForDeceleration:0,removedSamplesForAcceleration:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,freezeCount:0,totalFreezesDuration:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""},auxiliary:{bytesReceived:0,packetsReceived:0,packetsLost:0,framesReceived:0,framesDecoded:0,frameWidth:0,frameHeight:0,fpsDecoded:0,totalJitter:0,totalJitterCount:0,p2pDelay:0,codec:""}},d=A.getPeerConnection();if(d)try{let{ssrc:h}=A,{muteState:y,subscribeState:S}=A;(this._spcStats||(yield d.getStats())).forEach(J=>{var cA,CA;if(J.type==="codec"&&this._decodeMap.set(J.id,J),J.type==="inbound-rtp"){let MA=(J.mediaType||J.kind)===YA.AUDIO;if(MA){if(J.ssrc!==h.audio||!y.hasAudio)return;l.audio.packetsReceived=J.packetsReceived,l.audio.bytesReceived=J.bytesReceived,l.audio.packetsLost=J.packetsLost,J.insertedSamplesForDeceleration&&(l.audio.insertedSamplesForDeceleration=J.insertedSamplesForDeceleration),J.removedSamplesForAcceleration&&(l.audio.removedSamplesForAcceleration=J.removedSamplesForAcceleration),J.totalSamplesDuration&&(l.audio.totalSamplesDuration=J.totalSamplesDuration),J.totalSamplesReceived&&(l.audio.totalSamplesReceived=J.totalSamplesReceived),J.concealedSamples&&(l.audio.concealedSamples=J.concealedSamples),J.silentConcealedSamples&&(l.audio.silentConcealedSamples=J.silentConcealedSamples);let{remoteAudioTrack:ie}=A;ie.stat.packetsReceived=J.packetsReceived,ie.stat.bytesReceived=J.bytesReceived,ie.stat.packetsLost=J.packetsLost,l.audio.p2pDelay=ie.stat.end2EndDelay,l.hasAudio=!0}else{if(or&&J.bytesReceived===0)return;let ie;J.ssrc===h.video&&y.hasVideo&&(l.video.packetsReceived=J.packetsReceived,l.video.bytesReceived=J.bytesReceived,l.video.packetsLost=J.packetsLost,l.video.framesReceived=J.framesReceived,l.video.framesDecoded=J.framesDecoded,l.video.fpsDecoded=J.framesPerSecond,l.hasVideo=!0,A.videoCodec=Cl[(cA=this._decodeMap.get(J.codecId))==null?void 0:cA.mimeType.split("/")[1]]||"h264",l.video.codec=A.videoCodec,ie=A.remoteVideoTrack,y.hasSmall&&S.smallVideo&&(l.isSmallSubscribed=!0),J.decoderImplementation&&(!this._prevDecoderImplementationMap.has(l.userId)||this._prevDecoderImplementationMap.get(l.userId)!==J.decoderImplementation)&&(ie.log.info("decoderImplementation change to ".concat(J.decoderImplementation,"(").concat(A.videoCodec,") HWDecoder: ").concat(J.powerEfficientDecoder)),F.emit("262",{userId:this.room.userId,remoteUserId:l.userId,prevImplementation:this._prevDecoderImplementationMap.get(l.userId),implementation:J.decoderImplementation,codec:A.videoCodec,isHWCodec:J.powerEfficientDecoder}),this._prevDecoderImplementationMap.set(l.userId,J.decoderImplementation)),Ke(J.keyFramesDecoded)||ie.updateKeyFramesDecoded(J.keyFramesDecoded)),J.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.packetsReceived=J.packetsReceived,l.auxiliary.bytesReceived=J.bytesReceived,l.auxiliary.packetsLost=J.packetsLost,l.auxiliary.framesReceived=J.framesReceived,l.auxiliary.framesDecoded=J.framesDecoded,l.auxiliary.fpsDecoded=J.framesPerSecond,ie=A.remoteAuxiliaryTrack,l.auxiliary.p2pDelay=ie.stat.end2EndDelay,l.hasAuxiliary=!0,l.video.codec=((CA=this._decodeMap.get(J.codecId))==null?void 0:CA.mimeType.split("/")[1].toLowerCase())||"h264",Ke(J.keyFramesDecoded)||ie.updateKeyFramesDecoded(J.keyFramesDecoded)),ie&&(ie.stat.packetsReceived=J.packetsReceived,ie.stat.bytesReceived=J.bytesReceived,ie.stat.packetsLost=J.packetsLost,ie.stat.framesReceived=J.framesReceived,ie.stat.framesDecoded=J.framesDecoded,J.jitterBufferDelay&&(ie.stat.jitterBufferDelay=Math.floor(J.jitterBufferDelay/J.jitterBufferEmittedCount*1e3)),l.video.p2pDelay=ie.stat.end2EndDelay)}J.jitterBufferDelay&&(MA?(l.audio.totalJitter=J.jitterBufferDelay,l.audio.totalJitterCount=J.jitterBufferEmittedCount,l.audio.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===h.video&&y.hasVideo?(l.video.totalJitter=J.jitterBufferDelay,l.video.totalJitterCount=J.jitterBufferEmittedCount,l.video.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===h.auxiliary&&y.hasAuxiliary&&(l.auxiliary.totalJitter=J.jitterBufferDelay,l.auxiliary.totalJitterCount=J.jitterBufferEmittedCount))}else J.type==="candidate-pair"&&GM(J)&&(this.totalBytesReceived=J.bytesReceived,kn(J.currentRoundTripTime)&&(l.rtt=Math.floor(1e3*J.currentRoundTripTime)));Ke(J.frameWidth)||((J.trackIdentifier===A.getMainStreamVideoTrackId()||J.ssrc===h.video)&&(l.video.frameWidth=J.frameWidth,l.video.frameHeight=J.frameHeight,A.remoteVideoTrack.stat.frameWidth=J.frameWidth,A.remoteVideoTrack.stat.frameHeight=J.frameHeight),(J.trackIdentifier===A.getAuxStreamVideoTrackId()||J.ssrc===h.auxiliary)&&(l.auxiliary.frameWidth=J.frameWidth,l.auxiliary.frameHeight=J.frameHeight,A.remoteAuxiliaryTrack.stat.frameWidth=J.frameWidth,A.remoteAuxiliaryTrack.stat.frameHeight=J.frameHeight)),!Ke(J.audioLevel)&&A.muteState.audioAvailable&&A.remoteAudioTrack.mediaTrack&&J.trackIdentifier===A.remoteAudioTrack.mediaTrack.id&&(l.audio.audioLevel=J.audioLevel||0,l.audio.totalAudioEnergy=J.totalAudioEnergy||0)}),l.audio.audioLevel===0&&A.muteState.audioAvailable&&(l.audio.audioLevel=A.remoteAudioTrack.getInternalAudioLevel()||0),this.totalBytesReceived||(this.totalBytesReceived+=l.audio.bytesReceived+l.video.bytesReceived+l.auxiliary.bytesReceived),Ke((e=A.remoteVideoTrack.player.stat)==null?void 0:e.fps)||(l.video.fpsRender=A.remoteVideoTrack.player.stat.fps),Ke((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(l.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let k=l.audio.estimatedPlayoutTimestamp,V=l.video.estimatedPlayoutTimestamp;if(k&&V&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let J=V-k;Math.abs(J)<=1e4&&(l.avSyncDelay=J,Math.abs(J)>150&&this._log.warn("av sync delay",J))}}catch(h){this._log.warn("failed to getStats on receiver connection ".concat(h))}return l.rtt===0&&(l.rtt=((a=this.room.networkQuality)==null?void 0:a.uplinkRTT)||0),l})}getStats(A,e){return WA(this,null,function*(){let o,a={},l=[];if(this.room.singlePC){let d=this.room.singlePC.getPeerConnection();if(!d)return{senderStats:a,receiverStats:l};let h=ko(),y=yield d.getStats(),S=ko();S-h>2e3&&this._log.warn("getStats cost ".concat(S-h,"ms"));let k=[],V=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);y.forEach(J=>V.has(J.type)&&k.push(J)),this._spcStats=k}A&&(a=yield this.getSenderStats(A));for(let[d,h]of e){let y=yield this.getReceiverStats(h);y&&l.push(y)}return e.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:a,receiverStats:l,mediaPlayoutStats:o}})}getDifferenceValue(A,e){if(im(A))return e;let o=e-A;return o<0?0:o}prepareReport(A){let{stats:e,report:o,freezeMap:a,uplinkConnection:l}=A;var d,h,y,S,k,V,J,cA,CA;if(!im(e.senderStats)){let Le={uint32_audio_level:e.senderStats.audio.audioLevel*id,uint32_audio_energy:1e6*(e.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent};e.senderStats.audio.micAudioLevel&&(Le.uint32_mic_audio_level=e.senderStats.audio.micAudioLevel*id),Ke(e.senderStats.audio.audioCaptureEnergyAfter3a)||(Le.uint32_audio_capture_energy_after3a=e.senderStats.audio.audioCaptureEnergyAfter3a*id),e.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=e.senderStats.audio.totalSamplesDuration);let Qt=[];if(e.senderStats.video.bytesSent){let Si={uint32_video_stream_type:2,uint32_video_codec_fps:e.senderStats.video.framesSent,uint32_video_capture_fps:e.senderStats.video.fpsCapture,uint32_video_width:e.senderStats.video.frameWidth,uint32_video_height:e.senderStats.video.frameHeight,uint32_video_codec_bitrate:e.senderStats.video.bytesSent,uint32_video_enc_fps:e.senderStats.video.framesEncoded,uint32_key_frame_count:e.senderStats.video.keyFramesEncoded,uint32_nack_count:e.senderStats.video.nackCount,uint32_pli_count:e.senderStats.video.pliCount,uint32_encode_cost:1e3*(e.senderStats.video.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.video.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.video.retransmittedPacketsSent};Qt.push(Si)}if(e.senderStats.small.bytesSent){let Si={uint32_video_stream_type:3,uint32_video_codec_fps:e.senderStats.small.framesSent||0,uint32_video_capture_fps:e.senderStats.small.fpsCapture||0,uint32_video_width:e.senderStats.small.frameWidth||0,uint32_video_height:e.senderStats.small.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.small.bytesSent,uint32_video_enc_fps:e.senderStats.small.framesEncoded||0,uint32_key_frame_count:e.senderStats.small.keyFramesEncoded,uint32_nack_count:e.senderStats.small.nackCount,uint32_pli_count:e.senderStats.small.pliCount,uint32_encode_cost:1e3*(e.senderStats.small.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.small.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.small.retransmittedPacketsSent};Qt.push(Si)}if(e.senderStats.auxiliary.bytesSent){let Si={uint32_video_stream_type:7,uint32_video_codec_fps:e.senderStats.auxiliary.framesSent||0,uint32_video_capture_fps:e.senderStats.auxiliary.fpsCapture||0,uint32_video_width:e.senderStats.auxiliary.frameWidth||0,uint32_video_height:e.senderStats.auxiliary.frameHeight||0,uint32_video_codec_bitrate:e.senderStats.auxiliary.bytesSent,uint32_video_enc_fps:e.senderStats.auxiliary.framesEncoded||0,uint32_key_frame_count:e.senderStats.auxiliary.keyFramesEncoded,uint32_nack_count:e.senderStats.auxiliary.nackCount,uint32_pli_count:e.senderStats.auxiliary.pliCount,uint32_encode_cost:1e3*(e.senderStats.auxiliary.totalEncodeTime||0),uint32_send_packet_cost:1e3*(e.senderStats.auxiliary.totalPacketSendDelay||0),uint32_video_arq_packets:e.senderStats.auxiliary.retransmittedPacketsSent};Qt.push(Si)}let Bi={uint32_bitrate:0,uint32_lost:0,uint32_rtt:e.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:Le,msg_video_status:Qt,msg_network_status:Bi}}let{statInterval:MA}=this;o.msg_down_stream_info=[],e.receiverStats.forEach(Le=>{let Qt={msg_user_info:{str_identifier:Le.userId,uint64_tinyid:Le.tinyId},msg_network_status:{uint32_rtt:Le.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(Le.hasAudio){let Bi={uint32_audio_p2p_delay:Le.audio.p2pDelay,uint32_audio_cache_ms:Le.audio.totalJitter,uint32_audio_cache_ms_count:Le.audio.totalJitterCount,uint32_audio_codec_bitrate:Le.audio.bytesReceived,uint32_audio_total_bitrate:Le.audio.bytesReceived,uint32_audio_level:1e8*Le.audio.audioLevel,uint32_audio_energy:1e6*Le.audio.totalAudioEnergy,uint32_audio_receive:Le.audio.packetsReceived,uint32_audio_origin_lost:Le.audio.packetsLost};Qt.msg_audio_status=Bi}if(Le.hasVideo){let Bi=a.get("".concat(Le.userId,"_").concat(l0)),Si=Bi?Bi.duration:0,Jo={uint32_video_stream_type:Le.isSmallSubscribed?3:2,uint32_video_receive_fps:Le.video.framesReceived,uint32_video_width:Le.video.frameWidth,uint32_video_height:Le.video.frameHeight,uint32_video_codec_bitrate:Le.video.bytesReceived,uint32_video_receive:Le.video.packetsReceived,uint32_video_origin_lost:Le.video.packetsLost,uint32_video_block_time:Si,uint32_video_dec_fps:Le.video.framesDecoded,uint32_video_codec_fps:Le.video.fpsRender,uint32_video_cache_ms:Le.video.totalJitter,uint32_video_cache_ms_count:Le.video.totalJitterCount,uint32_video_p2p_delay:Le.video.p2pDelay,uint32_video_codec:Le.video.codec,int32_video_audio_relative_delay:Le.avSyncDelay+5e3};Qt.msg_video_status.push(Jo)}if(Le.hasAuxiliary){let Bi=a.get("".concat(Le.userId,"_").concat(bb)),Si=Bi?Bi.duration:0,Jo={uint32_video_stream_type:7,uint32_video_receive_fps:Le.auxiliary.framesReceived,uint32_video_width:Le.auxiliary.frameWidth,uint32_video_height:Le.auxiliary.frameHeight,uint32_video_codec_bitrate:Le.auxiliary.bytesReceived,uint32_video_receive:Le.auxiliary.packetsReceived+Le.auxiliary.packetsLost,uint32_video_origin_lost:Le.auxiliary.packetsLost,uint32_video_block_time:Si,uint32_video_dec_fps:Le.auxiliary.framesDecoded,uint32_video_codec_fps:Le.video.fpsRender,uint32_video_cache_ms:Le.auxiliary.totalJitter,uint32_video_cache_ms_count:Le.auxiliary.totalJitterCount,uint32_video_p2p_delay:Le.auxiliary.p2pDelay,uint32_video_codec:Le.video.codec};Qt.msg_video_status.push(Jo)}o.msg_down_stream_info.push(Qt)}),e.mediaPlayoutStats&&!im(e.mediaPlayoutStats)&&(e.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,e.mediaPlayoutStats.totalSamplesDuration*=1e3);let ie=this._prevReport,pe=this._prevStats;if(this._prevReport=JSON.parse(JSON.stringify(o)),this._prevStats=JSON.parse(JSON.stringify(e)),o.msg_up_stream_info.msg_audio_status&&ie.msg_up_stream_info.msg_audio_status){let Le=ie.msg_up_stream_info.msg_audio_status,Qt=o.msg_up_stream_info.msg_audio_status;if(Le.uint32_audio_codec_bitrate===0)Qt.uint32_audio_codec_bitrate=0;else{let Bi=this.getDifferenceValue(Le.uint32_audio_codec_bitrate,Qt.uint32_audio_codec_bitrate);Qt.uint32_audio_codec_bitrate=Math.round(8*Bi/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Qt.uint32_audio_codec_bitrate}(d=ie.msg_device_info)!=null&&d.uint32_audio_capture_cost?(o.msg_device_info.uint32_audio_capture_cost=2*Math.floor(1e3*this.getDifferenceValue(ie.msg_device_info.uint32_audio_capture_cost,o.msg_device_info.uint32_audio_capture_cost)/MA),o.msg_device_info.uint32_audio_capture_cost>0&&((y=l?.localMainAudioTrack)==null||y.updateAfter3aSilenceStartTime((h=e.senderStats.audio.audioCaptureEnergyAfter3a)!=null?h:e.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let qe=ie.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(Le=>{let Qt=qe.find(Qn=>Qn.uint32_video_stream_type===Le.uint32_video_stream_type);if(!Qt||Qt.uint32_video_codec_bitrate===0)return Le.uint32_video_codec_bitrate=0,Le.uint32_video_enc_fps=0,void(Le.uint32_video_codec_fps=0);let Bi=0,Si=0,Jo=0;Qt&&Le.uint32_video_codec_bitrate>=Qt.uint32_video_codec_bitrate&&(Bi=Qt.uint32_video_codec_bitrate,Si=Qt.uint32_video_enc_fps,Jo=Qt.uint32_video_codec_fps);let Ho=this.getDifferenceValue(Bi,Le.uint32_video_codec_bitrate);Le.uint32_video_codec_bitrate=Math.round(8*Ho/MA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Le.uint32_video_codec_bitrate,Le.uint32_video_enc_fps=Math.round(this.getDifferenceValue(Si,Le.uint32_video_enc_fps)/MA),Le.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Jo,Le.uint32_video_codec_fps)/MA),Qt.uint32_video_width===0&&Qt.uint32_video_height===0&&Qt.uint32_video_codec_fps===0&&(Le.uint32_video_codec_fps=Le.uint32_video_enc_fps),Ke(Qt.uint32_key_frame_count)||(Le.uint32_key_frame_count=Math.round(this.getDifferenceValue(Qt.uint32_key_frame_count,Le.uint32_key_frame_count))),Ke(Qt.uint32_nack_count)||(Le.uint32_nack_count=Math.round(this.getDifferenceValue(Qt.uint32_nack_count,Le.uint32_nack_count))),Ke(Qt.uint32_pli_count)||(Le.uint32_pli_count=Math.round(this.getDifferenceValue(Qt.uint32_pli_count,Le.uint32_pli_count))),Ke(Qt.uint32_video_arq_packets)||(Le.uint32_video_arq_packets=Math.round(this.getDifferenceValue(Qt.uint32_video_arq_packets,Le.uint32_video_arq_packets))),Ke(Qt.uint32_encode_cost)||(Le.uint32_encode_cost=Math.round(this.getDifferenceValue(Qt.uint32_encode_cost,Le.uint32_encode_cost)/MA)),Ke(Qt.uint32_send_packet_cost)||(Le.uint32_send_packet_cost=Math.round(this.getDifferenceValue(Qt.uint32_send_packet_cost,Le.uint32_send_packet_cost)/MA))});let we=ie.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(Le=>we.find(Qt=>Qt.msg_user_info.uint64_tinyid===Le.msg_user_info.uint64_tinyid));let Di=o.msg_down_stream_info;if(Di.forEach(Le=>{let Qt=we.find(Bi=>Bi.msg_user_info.uint64_tinyid===Le.msg_user_info.uint64_tinyid);if(im(Le.msg_audio_status)||im(Qt.msg_audio_status))Le.msg_audio_status={};else{let Bi=Le.msg_audio_status,Si=Qt.msg_audio_status,Jo=this.getDifferenceValue(Si.uint32_audio_cache_ms_count,Bi.uint32_audio_cache_ms_count);delete Bi.uint32_audio_cache_ms_count,Bi.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(Si.uint32_audio_cache_ms,Bi.uint32_audio_cache_ms)/Jo)||0;let Ho=this.room.remotePublishedUserMap.get(Le.msg_user_info.str_identifier);Ho&&(Ho.remoteAudioTrack.stat.jitterBufferDelay=Bi.uint32_audio_cache_ms),Bi.uint32_audio_origin_lost=this.getDifferenceValue(Si.uint32_audio_origin_lost,Bi.uint32_audio_origin_lost),Bi.uint32_audio_receive=this.getDifferenceValue(Si.uint32_audio_receive,Bi.uint32_audio_receive),Bi.uint32_audio_receive+=Bi.uint32_audio_origin_lost;let Qn=this.getDifferenceValue(Si.uint32_audio_codec_bitrate,Bi.uint32_audio_codec_bitrate);Bi.uint32_audio_codec_bitrate=Math.round(8*Qn/MA),Bi.uint32_audio_total_bitrate=Math.round(8*Qn/MA)}if(Le.msg_video_status&&Qt.msg_video_status){let Bi=Qt.msg_video_status;Le.msg_video_status=Le.msg_video_status.filter(Si=>Bi.find(Jo=>Jo.uint32_video_stream_type===Si.uint32_video_stream_type)),Le.msg_video_status.forEach(Si=>{let Jo=Bi.find(D_=>D_.uint32_video_stream_type===Si.uint32_video_stream_type),Ho=Jo.uint32_video_receive,Qn=Jo.uint32_video_origin_lost,qo=Jo.uint32_video_codec_bitrate,Ns=Jo.uint32_video_receive_fps,pg=Jo.uint32_video_dec_fps;Si.uint32_video_origin_lost=this.getDifferenceValue(Qn,Si.uint32_video_origin_lost),Si.uint32_video_receive=this.getDifferenceValue(Ho,Si.uint32_video_receive)+Si.uint32_video_origin_lost;let ya=this.getDifferenceValue(qo,Si.uint32_video_codec_bitrate);Si.uint32_video_codec_bitrate=Math.round(8*ya/MA);let Qu=this.getDifferenceValue(Ns,Si.uint32_video_receive_fps);Si.uint32_video_receive_fps=Math.round(Qu/MA),Si.uint32_video_dec_fps=Math.round(this.getDifferenceValue(pg,Si.uint32_video_dec_fps)/MA);let DL=this.getDifferenceValue(Jo.uint32_video_cache_ms_count,Si.uint32_video_cache_ms_count);delete Si.uint32_video_cache_ms_count,Si.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Jo.uint32_video_cache_ms,Si.uint32_video_cache_ms)/DL)||0})}}),!Ke((S=pe?.mediaPlayoutStats)==null?void 0:S.totalSamplesDuration)&&!Ke((k=e.mediaPlayoutStats)==null?void 0:k.totalSamplesDuration)){let Le=2*Math.floor(this.getDifferenceValue((V=pe?.mediaPlayoutStats)==null?void 0:V.synthesizedSamplesDuration,(J=e.mediaPlayoutStats)==null?void 0:J.synthesizedSamplesDuration)/MA),Qt=2*Math.floor(this.getDifferenceValue((cA=pe?.mediaPlayoutStats)==null?void 0:cA.totalSamplesDuration,(CA=e.mediaPlayoutStats)==null?void 0:CA.totalSamplesDuration)/MA);o.msg_device_info.uint32_audio_play_cost=Qt-Le}return pe&&e.receiverStats.forEach(Le=>{if(Le.audio.concealedSamples&&Le.audio.totalSamplesReceived){let Qt=pe.receiverStats.find(Bi=>Bi.userId===Le.userId);if(Qt&&Qt.audio.concealedSamples&&Qt.audio.totalSamplesReceived){let Bi=(Le.audio.silentConcealedSamples||0)-(Qt.audio.silentConcealedSamples||0),Si=Le.audio.concealedSamples-Qt.audio.concealedSamples,Jo=Le.audio.totalSamplesReceived-Qt.audio.totalSamplesReceived,Ho=Math.floor((Si-Bi)/Jo*1e3*MA);if(Ho>1e3*MA/5){let Qn=Di.find(qo=>qo.msg_user_info.str_identifier===Le.userId);Qn&&(Qn.msg_audio_status.uint32_audio_block_time=Ho)}}}}),o.msg_down_stream_info.forEach(Le=>{Le.msg_video_status.forEach(Qt=>{Qt.uint32_video_codec_bitrate===0&&Qt.uint32_video_receive_fps===0&&(Qt.uint32_video_width=0,Qt.uint32_video_height=0)})}),o}getStatsReport(A){return WA(this,arguments,function(e){var o=this;let{uplinkConnection:a,downlinkConnections:l,freezeMap:d}=e;return function*(){let h={msg_device_info:{},msg_up_stream_info:{msg_audio_status:{uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_capture_energy_after3a:0},msg_video_status:[],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}},msg_down_stream_info:[{msg_user_info:{str_identifier:"",uint64_tinyid:0},msg_audio_status:{uint32_audio_cache_ms:0,uint32_audio_format:11,uint32_audio_sample_rate:0,uint32_audio_codec_bitrate:0,uint32_audio_total_bitrate:0,uint32_audio_level:0,uint32_audio_energy:0,uint32_audio_receive:0,uint32_audio_origin_lost:0,uint32_audio_final_lost:0},msg_video_status:[{uint32_video_cache_ms:0,uint32_video_stream_type:0,uint32_video_receive_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_codec_bitrate:0,uint32_video_receive:0,uint32_video_origin_lost:0,uint32_video_block_time:0,uint32_video_dec_fps:0,uint32_video_codec_fps:0}],msg_network_status:{uint32_bitrate:0,uint32_rtt:0,uint32_lost:0}}]},y=yield o.getStats(a,l);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(h))),o.prepareReport({stats:y,report:h,freezeMap:d,uplinkConnection:a}),o._prevReportTime=Date.now(),h}()})}getMediaPlayoutStats(A){let e;if(wa(A)){for(let o of A)if(o.type==="media-playout"){let{synthesizedSamplesDuration:a,totalSamplesDuration:l}=o;e={synthesizedSamplesDuration:a,totalSamplesDuration:l};break}return e}}reset(){this._prevReportTime=0,this._prevReport={},this._prevEncoderImplementation="",this._prevQualityLimitationReason="",this._prevDecoderImplementationMap=new Map,[this.room.localMainVideoTrack,this.room.capturedLocalMainVideoTrack,this.room.localAuxVideoTrack,this.room.capturedLocalAuxVideoTrack].forEach(A=>{A!=null&&A.stat&&(A.stat.framesCaptured=0)})}},VoA=gc(jl());function JoA(A){return new Promise(e=>WA(null,null,function*(){let o=setTimeout(()=>{e({totalCost:1e4,local:0,dns:0,tcp:0,tls:0,request:0,response:0})},1e4),a=Date.now(),l="https://".concat(A,"/?t=").concat(a);try{yield fetch(l)}catch{}clearTimeout(o);let d=function(h){let y={totalCost:0,local:0,redirect:0,httpCache:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let S=performance.getEntriesByType("resource").reverse();for(let k of S)if(k.name===h){let V=Math.round(k.duration),J=Math.max(Math.round(k.domainLookupStart-k.startTime),0),cA=k.redirectStart>0?Math.max(Math.round(k.redirectEnd-k.redirectStart),0):0,CA=k.fetchStart>0?Math.max(Math.round(k.domainLookupStart-k.fetchStart),0):0,MA=Math.round(k.domainLookupEnd-k.domainLookupStart),ie=Math.round(k.requestStart-k.secureConnectionStart),pe=Math.round(k.secureConnectionStart-k.connectStart),qe=Math.round(k.responseStart-k.requestStart),we=Math.round(k.responseEnd-(k.responseStart||k.startTime));y=po(fi({},y),{totalCost:V,local:J,redirect:cA,httpCache:CA,dns:MA,tcp:pe,tls:ie,request:qe,response:we});break}}catch{}return y}(l);d.totalCost===0&&(d.totalCost=Date.now()-a),e(d)}))}var U1=class b_ extends VoA.default{constructor(e){let{signalChannel:o,room:a}=e;super(),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_log"),Y(this,"uplinkRTT",0),Y(this,"uplinkLoss",0),Y(this,"downlinkRTT",0),Y(this,"downlinkLoss",0),Y(this,"pingResults",{}),Y(this,"_downlinkPrevStatMap",new Map),Y(this,"_downlinkLossAndRTTMap",new Map),Y(this,"_interval",-1),Y(this,"_uplinkNetworkQuality",0),Y(this,"_downlinkNetworkQuality",0),Y(this,"_uplinkQualityHistory",[]),Y(this,"_downlinkQualityHistory",[]),this._room=a,this._signalChannel=o,this._log=pA.createLogger({parent:a.getLogger(),id:"q",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this.initialize()}get uplinkNetworkQuality(){return this._uplinkNetworkQuality}set uplinkNetworkQuality(e){e!==this._uplinkNetworkQuality&&this._log.info("uplink ".concat(this.uplinkNetworkQuality," -> ").concat(e,", rtt: ").concat(this.uplinkRTT,", loss: ").concat(this.uplinkLoss," ws-rtt: ").concat(this._signalChannel.rtt)),this._uplinkNetworkQuality=e,this._uplinkQualityHistory.push(e),this._uplinkQualityHistory.length>b_.HISTORY_SIZE&&this._uplinkQualityHistory.shift()}get downlinkNetworkQuality(){return this._downlinkNetworkQuality}set downlinkNetworkQuality(e){if(e!==this._downlinkNetworkQuality){let{rtt:o,loss:a}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this._log.info("downlink ".concat(this.downlinkNetworkQuality," -> ").concat(e,", rtt: ").concat(o,", loss: ").concat(a," ws-rtt: ").concat(this._signalChannel.rtt))}this._downlinkNetworkQuality=e,this._downlinkQualityHistory.push(e),this._downlinkQualityHistory.length>b_.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(ls.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(_j,this.handleSignalConnectionStateChange.bind(this)),this.start()}handleUplinkNetworkQuality(e){var o,a;if(e.data.code!==0)return;let l=e.data.data;if(l.delay&&this.updateDelay(l.delay),this._room.signalChannel&&l.wsRtt&&(this._room.signalChannel.rtt=l.wsRtt),!this._room.uplinkConnection)return this.uplinkNetworkQuality=0,this.uplinkLoss=0,void(this.uplinkRTT=0);let d=(a=(o=this._room)==null?void 0:o.uplinkConnection)==null?void 0:a.getPeerConnection();if(d&&this.isPeerConnectionDisconnected(d))return this.uplinkNetworkQuality=6,this.uplinkLoss=0,void(this.uplinkRTT=0);let h=l.expectAudPkg+l.expectVidPkg,y=l.recvAudPkg+l.recvVidPkg,S=h-y;h===0&&y===0||(this.uplinkLoss=S<=0?0:Math.round(S/h*100),this.uplinkRTT=l.rtt,this.uplinkNetworkQuality=this.getNetworkQuality(this.uplinkLoss,this.uplinkRTT))}handleDownlinkNetworkQuality(){return WA(this,null,function*(){if(this._room.remotePublishedUserMap.size===0)return void(this.downlinkNetworkQuality=0);let e=[...this._room.remotePublishedUserMap.values()],o=new Set,a=e.filter(y=>{let S=y.getPeerConnection();return!(!S||o.has(S))&&(o.add(S),!0)}),l=a.filter(y=>{var S;return((S=y.getPeerConnection())==null?void 0:S.connectionState)===ho.CONNECTED});if(a.filter(y=>this.isPeerConnectionDisconnected(y.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let y=0;y{this.isPeerConnectionDisconnected(y)&&(this._downlinkPrevStatMap.delete(y),this._downlinkLossAndRTTMap.delete(y))}),this._downlinkLossAndRTTMap.size===0)return this.downlinkRTT=0,this.downlinkLoss=0,void(this.downlinkNetworkQuality=0);let{rtt:d,loss:h}=this.getAverageLossAndRTT([...this._downlinkLossAndRTTMap.values()]);this.downlinkRTT=d,this.downlinkLoss=h,this.downlinkNetworkQuality=this.getNetworkQuality(h,d)})}getStat(e){return WA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!By())return o;let a=e.getReceivers();try{for(let l=0;l{d.type==="candidate-pair"&&kn(d.currentRoundTripTime)&&(o.rtt=Math.round(1e3*d.currentRoundTripTime)),d.type==="inbound-rtp"&&(d.mediaType===YA.AUDIO||d.mediaType===YA.VIDEO)&&(o.totalPacketsLost+=d.packetsLost,o.totalPacketsReceived+=d.packetsReceived)});return o.rtt===0&&(o.rtt=this.uplinkRTT),o}catch{return o}})}getAverageLossAndRTT(e){let o={rtt:0,loss:0};return Array.isArray(e)&&e.length>0&&(e.forEach(a=>{o.rtt+=a.rtt,o.loss+=a.loss}),Object.keys(o).forEach(a=>{o[a]=Math.round(o[a]/e.length)})),o}getNetworkQuality(e,o){return e>50||o>500?5:e>30||o>350?4:e>20||o>200?3:e>10||o>100?2:e>=0||o>=0?1:0}handleSignalConnectionStateChange(e){e.state==="DISCONNECTED"?(this.uplinkRTT=0,this.uplinkLoss=0,this.uplinkNetworkQuality=6):e.state==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=1)}handleUplinkConnectionStateChange(e){let{state:o}=e;o==="DISCONNECTED"?(this.uplinkLoss=0,this.uplinkRTT=0,this.uplinkNetworkQuality=6):o==="CONNECTED"&&this.uplinkNetworkQuality===6&&(this.uplinkNetworkQuality=5)}isPeerConnectionDisconnected(e){return!(!e||e.connectionState!==ho.DISCONNECTED&&e.connectionState!==ho.FAILED&&e.connectionState!==ho.CLOSED)}setUplinkConnection(e){this._room.uplinkConnection=e,this._room.uplinkConnection?this._room.uplinkConnection.on("connection-state-changed",this.handleUplinkConnectionStateChange.bind(this)):(this.uplinkNetworkQuality=0,this.uplinkRTT=0,this.uplinkLoss=0)}start(){this._interval===-1?(this._log.debug("start network quality calculating"),this._interval=Gr.run("ric",()=>{var e;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];F.emit(nA.NETWORK_QUALITY,{room:this._room,uplink:{rtt:this.uplinkRTT,loss:this.uplinkLoss},downlinks:o});let a=(e=this._room.scheduleResult.config)==null?void 0:e.pingDomainInfo,l={uplinkNetworkQuality:this.uplinkNetworkQuality,downlinkNetworkQuality:this.downlinkNetworkQuality,uplinkRTT:this.uplinkRTT,uplinkLoss:this.uplinkLoss,downlinkRTT:this.downlinkRTT,downlinkLoss:this.downlinkLoss};a&&(l=po(fi({},l),{pingResults:this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold?this.pingResults:{}})),this.emit(b_.EVENT_NETWORK_QUALITY,l);let d=Date.now();if(a&&(this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold)&&d-b_.lastPingTime>1e3*a.interval){b_.lastPingTime=Date.now();let h=a.domain.map(y=>JoA(y).then(S=>({domain:y,cost:S.totalCost})));Promise.all(h).then(y=>{this.pingResults.isPoorNetwork=y.some(S=>S.cost>700),this.pingResults.timestamp=d,this.pingResults.data=y,y.forEach(S=>{si.addSuccessEvent({key:521718,cost:S.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(y)))}).catch(y=>{this._log.warn("Error during pinging domains: ".concat(y))})}},{delay:2e3})):this._log.info("network quality calculating is already started")}hadRecentBadUplink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._uplinkQualityHistory.some(o=>o>e)}hadRecentBadDownlink(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2;return this._downlinkQualityHistory.some(o=>o>e)}stop(){this._log.debug("stopped"),this._interval!==-1&&(Gr.clearTask(this._interval),this._interval=-1),this._downlinkLossAndRTTMap.clear(),this._downlinkPrevStatMap.clear()}updateDelay(e){let{tinyIdToUserIdMap:o}=this._room;e.forEach(a=>{let{srcTinyId:l,videoDelay:d,audioDelay:h}=a,y=o.get(l);if(y){let S=this._room.remotePublishedUserMap.get(y);S?.setDelay({videoDelay:d,audioDelay:h})}})}};Y(U1,"HISTORY_SIZE",10),Y(U1,"EVENT_NETWORK_QUALITY","0"),Y(U1,"lastPingTime",0);var n8=U1,r8=class{constructor(A){Y(this,"_frameWorkType"),Y(this,"_component"),Y(this,"_language"),Y(this,"connectionType"),Y(this,"_room"),Y(this,"_signalInfo",{tinyId:void 0,clientIp:"",signalIp:"",relayIp:"",relayInnerIp:"",relayPort:0,endReportExtend:void 0,reportToken:void 0}),Y(this,"_keyPrefix"),Y(this,"_log"),Y(this,"_intervalId"),Y(this,"_firstPublishedUserList"),Y(this,"_networkQuality"),Y(this,"_basicInfo"),Y(this,"_pathJoinRoom"),Y(this,"_pathLeaveRoom"),Y(this,"_pathMainVideoMap"),Y(this,"_pathMainAudioMap"),Y(this,"_pathAuxiliaryMap"),Y(this,"_remoteStreamStatMap"),Y(this,"_localStreamStat"),Y(this,"_eventMap",new Map),Y(this,"_captureCostSum",0),Y(this,"_captureCostCount",0),Y(this,"isDestroyed",!1),this._frameWorkType=A.frameWorkType||30,this._component=A.component||0,this.connectionType=A.connectionType||1,this._language=A.language||0,this._room=A.room,this._keyPrefix="key_point",this._log=pA.createLogger({parent:this._room.getLogger(),id:"kpm",userId:this._room.userId,sdkAppId:this._room.sdkAppId}),Object.getOwnPropertyNames(this.__proto__).forEach(e=>{e.startsWith("handle")&&Ra(this[e])&&(this[e]=function(o){let{fn:a,context:l}=o;return function(){try{for(var d=arguments.length,h=new Array(d),y=0;ypA.error("".concat(a.name,"() error observed ").concat(k))):S}catch(S){pA.error("".concat(a.name,"() error observed ").concat(S))}}}({fn:this[e],context:this}))}),this.initData(),this.installEvents()}initData(){this._firstPublishedUserList=[],this._networkQuality={totalUplinkRTT:0,totalUplinkLoss:0,count:0,totalDownlinkRTTAndLossMap:new Map},this._basicInfo={string_sdk_version:qd,uint32_os_type:15,string_device_name:"",string_http_user_agent:navigator.userAgent,string_os_version:"",uint32_avg_rtt:0,uint32_avg_up_loss:0,uint32_scene:this._room.scene==="live"?1:0,uint32_joining_duration:0,uint32_networkType:0,uint32_framework:this._frameWorkType,uint32_component:this._component,uint32_connection_type:this.connectionType,uint32_caller_coding_language:this._language,string_domain:location.hostname},this._pathJoinRoom={uint64_start_time:0,uint64_send_request_acc_ip_cmd_start_time:0,uint64_send_request_acc_ip_cmd_end_time:0,uint64_send_request_enter_room_cmd_start_time:0,uint64_send_request_enter_room_cmd_end_time:0,uint64_send_first_video_frame_time:0,uint64_recv_userlist_time:0,uint64_end_time:0,int32_send_request_acc_ip_cmd_ret:0,int32_send_request_enter_room_cmd_ret:0,int32_end_ret:0},this._pathLeaveRoom={uint64_start_time:0,uint64_send_request_exit_room_cmd_start_time:0,uint64_send_request_exit_room_cmd_end_time:0,uint64_end_time:0,int32_send_request_exit_room_cmd_ret:0,int32_end_ret:0},this._localStreamStat={totalVideoBitrate:0,totalVideoFPS:0,totalVideoHeight:0,totalVideoWidth:0,totalAudioLevel:0,videoCount:0,audioLevelCount:0,publishStartTime:0,statsToReport:{uint32_audio_capture_db:0,uint32_video_big_capture_fps:0,uint32_video_big_bitrate:0,uint32_video_big_resolution:0,uint32_audio_capture_thread_health_zero_cnt:0,uint32_after3a_silence_duration:0}},this._pathMainVideoMap=new Map,this._pathMainAudioMap=new Map,this._pathAuxiliaryMap=new Map,this._remoteStreamStatMap=new Map,SM().then(()=>{this._basicInfo.string_os_version=Hp(),this._basicInfo.string_device_name=cQ()||this._basicInfo.string_os_version})}addEvent(A,e){return this._eventMap.set(A,e),F.on(A,e),this}installEvents(){this.handleUnload=this.handleUnload.bind(this),window.addEventListener("pagehide",this.handleUnload),this._room.once("banned",()=>this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})),this.addEvent(nA.JOIN_START,this.handleJoinStart).addEvent(nA.JOIN_SCHEDULE_SUCCESS,this.handleJoinScheduleSuccess).addEvent(nA.JOIN_SIGNAL_CONNECTION_START,this.handleSignalConnectionStart).addEvent(nA.JOIN_SIGNAL_CONNECTION_END,this.handleSignalConnectionEnd).addEvent(nA.JOIN_SEND_CMD,this.handleJoinSendCMD).addEvent(nA.JOIN_RECEIVED_CMD_RES,this.handleJoinReceivedCMDResponce).addEvent(nA.JOIN_SUCCESS,this.handleJoinSuccess).addEvent(nA.JOIN_FAILED,this.handleJoinFailed).addEvent(nA.LEAVE_START,this.handleLeaveStart).addEvent(nA.LEAVE_SUCCESS,this.handleLeaveSuccess).addEvent(nA.LEAVE_SEND_CMD,this.handleLeaveSendCMD).addEvent(nA.LOCAL_TRACK_CAPTURE_START,this.handleTrackCaptureStart).addEvent(nA.LOCAL_TRACK_CAPTURE_SUCCESS,this.handleTrackCaptureSuccess).addEvent(nA.LOCAL_TRACK_CAPTURE_FAILED,this.handleTrackCaptureFailed).addEvent(nA.PUBLISH_START,this.handlePublishStart).addEvent(nA.SEND_FIRST_VIDEO_FRAME,this.handleSendFirstVideoFrame).addEvent(nA.SUBSCRIBE_START,this.handleSubscribeStart).addEvent(nA.SUBSCRIBE_SUCCESS,this.handleSubscribed).addEvent(nA.PLAY_TRACK_START,this.handlePlayStart).addEvent(nA.VIDEO_LOADED_DATA,this.handleVideoLoadedData).addEvent(nA.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,type:a}=A;!e.isRemote||!this.hitTest(e.room)||o==="PLAYING"&&(a===YA.AUDIO?this.handleAudioPlaying(e):this.handleVideoPlaying(e))}).addEvent(nA.SWITCH_ROOM_START,this.handleSwitchRoomStart).addEvent(nA.SWITCH_ROOM_SUCCESS,this.handleSwitchRoomSuccess).addEvent(nA.SWITCH_ROOM_FAILED,this.handleSwitchRoomFailed).addEvent(nA.NETWORK_QUALITY,this.handleNetworkQuality).addEvent(nA.HEARTBEAT_REPORT,this.handleHeartbeatStats).addEvent(nA.RECEIVED_PUBLISHED_USER_LIST,this.handleReceivedPublishUserList).addEvent(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;if(!this.hitTest(e))return;let l=o.hasAudio||o.hasVideo||o.hasSmall,d=o.hasAuxiliary,h=a.hasAudio||a.hasVideo||a.hasSmall,y=a.hasAuxiliary;!l&&h&&this.handleRemoteStreamAdded(a.userId,"main"),!d&&y&&this.handleRemoteStreamAdded(a.userId,"auxiliary")}).addEvent(nA.SINGLE_CONNECTION_STAT,A=>{let{room:e,stat:o}=A;this.hitTest(e)&&(this._pathJoinRoom.int32_ice_cost=o.ice,this._pathJoinRoom.int32_dtls_cost=o.dtls,this._pathJoinRoom.int32_peer_connection_cost=o.peerConnection)})}uninstallEvents(){window.removeEventListener("pagehide",this.handleUnload),this._eventMap.forEach((A,e)=>F.off(e,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),Gr.clearTask(this._intervalId),this._pathJoinRoom.uint64_start_time===0&&(this._room=null),this.isDestroyed=!0}handleUnload(){this._room.isJoined&&this.handleLeaveSuccess({room:this._room,roomId:this._room.roomId})}handleJoinStart(A){this.hitTest(A.room)&&(this._pathJoinRoom.uint64_start_time===0&&(this._pathJoinRoom.uint64_start_time=Date.now()),A.params&&(Ke(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),Ke(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),Ke(A.params.language)||(this._language=A.params.language,this._basicInfo.uint32_caller_coding_language=this._language)))}handleJoinScheduleSuccess(A){let{room:e,detailCost:o}=A;if(this.hitTest(e)&&o){let{totalCost:a,local:l,dns:d,tcp:h,tls:y,request:S,response:k}=o;this._pathJoinRoom.int32_schedule_cost=a,this._pathJoinRoom.int32_schedule_local=l,this._pathJoinRoom.int32_schedule_dns=d,this._pathJoinRoom.int32_schedule_tcp=h,this._pathJoinRoom.int32_schedule_tls=y,this._pathJoinRoom.int32_schedule_request=S,this._pathJoinRoom.int32_schedule_response=k}}handleSignalConnectionStart(A){let{room:e}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_start_time=Date.now())}handleSignalConnectionEnd(A){let{room:e,error:o}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_acc_ip_cmd_end_time=Date.now(),o&&(this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret=o instanceof gi?Number(o.getExtraCode()||o.getCode()):Ct.UNKNOWN,this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret))}handleJoinSendCMD(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=Date.now())}handleJoinReceivedCMDResponce(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time===0&&(this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=Date.now(),this._pathJoinRoom.int32_send_request_enter_room_cmd_ret=A.code,A.code!==0&&(this._pathJoinRoom.int32_end_ret=this._pathJoinRoom.int32_send_request_enter_room_cmd_ret))}handleJoinSuccess(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_end_time===0&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret=0,this._signalInfo=A.room.getSignalInfo())}handleJoinFailed(A){let{room:e,error:o}=A;this.hitTest(e)&&(this._pathJoinRoom.uint64_end_time=Date.now(),this._pathJoinRoom.int32_end_ret===0&&(this._pathJoinRoom.int32_end_ret=o.code||this._pathJoinRoom.int32_send_request_enter_room_cmd_ret||this._pathJoinRoom.int32_send_request_acc_ip_cmd_ret),setTimeout(()=>{this.report()}))}handleReceivedPublishUserList(A){this.hitTest(A.room)&&this._pathJoinRoom.uint64_recv_userlist_time===0&&(this._pathJoinRoom.uint64_recv_userlist_time=Date.now(),this._firstPublishedUserList=A.publishedUserList||[])}handleSendFirstVideoFrame(A){let{room:e}=A;this.hitTest(e)&&this._pathJoinRoom.uint64_send_first_video_frame_time===0&&this._pathJoinRoom.uint64_start_time!==0&&(this._pathJoinRoom.uint64_send_first_video_frame_time=Date.now())}handleLeaveStart(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_start_time=Date.now())}handleLeaveSuccess(A){var e;if(this.hitTest(A.room)&&this._pathLeaveRoom.uint64_end_time===0){if(this._pathLeaveRoom.uint64_end_time=Date.now(),this._pathJoinRoom.uint64_end_time!==0){this._basicInfo.uint32_joining_duration=this._pathLeaveRoom.uint64_end_time-this._pathJoinRoom.uint64_end_time;let o=(e=this._room.audioManager.localAudioTrack)==null?void 0:e.after3aSilenceStartTime;o&&(this._localStreamStat.statsToReport.uint32_after3a_silence_duration=ko()-o)}else this._log.warn("pathJoinRoom endTime is 0");this.report()}}handleLeaveSendCMD(A){this.hitTest(A.room)&&(this._pathLeaveRoom.uint64_send_request_exit_room_cmd_start_time=Date.now(),this._pathLeaveRoom.uint64_send_request_exit_room_cmd_end_time=Date.now())}handleSwitchRoomStart(A){if(this.hitTest(A.room)){let e=Date.now();this.report().then(()=>{this._pathJoinRoom.uint64_start_time=e,this._pathJoinRoom.uint64_send_request_enter_room_cmd_start_time=e})}}handleSwitchRoomSuccess(A){let{room:e}=A;if(this.hitTest(e)&&this._pathJoinRoom.uint64_end_time===0){let o=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=o,this._pathJoinRoom.uint64_end_time=o,this._pathJoinRoom.int32_end_ret}}handleSwitchRoomFailed(A){let{room:e,error:o}=A;if(this.hitTest(e)){let a=Date.now();this._pathJoinRoom.uint64_send_request_enter_room_cmd_end_time=a,this._pathJoinRoom.uint64_end_time=a,o&&(this._pathJoinRoom.int32_end_ret=o instanceof gi?Number(o.getExtraCode()||o.getCode()):Ct.UNKNOWN)}}handleRemoteStreamAdded(A,e){var o;let a="".concat(A,"_").concat(e);if(!this._remoteStreamStatMap.has(a)){let l={userId:A,totalVideoFPS:0,totalVideoBitrate:0,totalAudioLevel:0,totalAudioBitrate:0,totalLoss:0,audioCount:0,audioLevelCount:0,videoCount:0,networkQualityCount:0,streamAddedTime:Date.now(),subscribeStartTime:0,subscribedTime:0,playStreamTime:0,statsToReport:po(fi({},HoA),{msg_user_info:new Lj({userId:A,tinyId:(o=this._room.remotePublishedUserMap.get(A))==null?void 0:o.tinyId,role:20})})};l.statsToReport.uint32_stream_type=e==="main"?2:7,this._remoteStreamStatMap.set(a,l)}}handleSubscribeStart(A){let{room:e,remotePublishedUser:o,streamType:a,subscribeState:l}=A;if(!this.hitTest(e))return;let{userId:d,tinyId:h,role:y}=o,S=new Lj({userId:d,tinyId:h,role:y==="anchor"?20:21}),k=Date.now(),V="".concat(d,"_").concat(a),J=this._remoteStreamStatMap.get(V);J&&J.subscribeStartTime===0&&(J.subscribeStartTime=k),a==="main"?(o.muteState.hasVideo&&(l.video||l.smallVideo)&&!this._pathMainVideoMap.has(V)&&this._pathMainVideoMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_render_first_frame_time:0,uint64_combine_first_frame_time:0},userId:d,sendSubscribeCMDTime:k}),o.muteState.hasAudio&&l.audio&&!this._pathMainAudioMap.has(V)&&this._pathMainAudioMap.set(V,{statsToReport:{msg_user_info:S,uint64_start_enter_time:this._pathJoinRoom.uint64_start_time,uint64_play_first_frame_time:0},userId:d,sendSubscribeCMDTime:k})):o.muteState.hasAuxiliary&&l.auxiliary&&!this._pathAuxiliaryMap.has(V)&&this._pathAuxiliaryMap.set(V,{sendSubscribeCMDTime:k})}handleSubscribed(A){let{room:e,remotePublishedUser:o,streamType:a}=A;if(this.hitTest(e)){let l="".concat(o.userId,"_").concat(a),d=this._remoteStreamStatMap.get(l);d&&d.subscribedTime===0&&(d.subscribedTime=Date.now())}}handlePlayStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),a=this._remoteStreamStatMap.get(o);a?.playStreamTime===0&&(a.playStreamTime=Date.now())}handleVideoLoadedData(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room))return;let o="".concat(e.userId,"_").concat(e.streamType),a=this._pathMainVideoMap.get(o);a&&a.statsToReport.uint64_combine_first_frame_time===0&&(a.statsToReport.uint64_combine_first_frame_time=Date.now())}handleVideoPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=Date.now(),a=this._pathMainVideoMap.get(e),l=this._remoteStreamStatMap.get(e);if(l){let{statsToReport:d}=l;if(d.uint32_video_render_first||A.streamType!=="main"?this.hasAuxFlag(A.userId):this.hasVideoFlag(A.userId)){let h=o-this._pathJoinRoom.uint64_start_time;d.uint32_video_render_first=h,si.addNumber({key:516820,value:h})}}a?.statsToReport.uint64_render_first_frame_time===0&&(a.statsToReport.uint64_render_first_frame_time=o)}handleAudioPlaying(A){let e="".concat(A.userId,"_").concat(A.streamType),o=this._pathMainAudioMap.get(e);o&&o.statsToReport.uint64_play_first_frame_time===0&&(o.statsToReport.uint64_play_first_frame_time=Date.now())}handleNetworkQuality(A){this.hitTest(A.room)&&(this._networkQuality.totalUplinkLoss+=A.uplink.loss,this._networkQuality.totalUplinkRTT+=A.uplink.rtt,this._networkQuality.count++,A.downlinks.forEach(e=>{let{rtt:o,loss:a,userId:l,videoDelay:d,audioDelay:h}=e,y=this._networkQuality.totalDownlinkRTTAndLossMap.get(l);if(y)y.totalRTT+=o,y.totalLoss+=a,d&&(y.totalVideoDelay=(y.totalVideoDelay||0)+d,y.videoDelayCount=(y.videoDelayCount||0)+1),h&&(y.totalAudioDelay=(y.totalAudioDelay||0)+h,y.audioDelayCount=(y.audioDelayCount||0)+1),y.count++;else{let S,k,V,J;d&&(k=d,V=1),h&&(S=h,J=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(l,{totalRTT:o,totalLoss:a,count:1,totalAudioDelay:S,totalVideoDelay:k,audioDelayCount:J,videoDelayCount:V})}}))}handleHeartbeatStats(A){var e;if(this.hitTest(A.room)){let{msg_device_info:o,msg_up_stream_info:a,msg_down_stream_info:l}=A.report;if(a.msg_video_status[0]){let{uint32_video_codec_bitrate:d,uint32_video_enc_fps:h,uint32_video_width:y,uint32_video_height:S}=a.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=d,this._localStreamStat.totalVideoFPS+=h,this._localStreamStat.totalVideoWidth+=y,this._localStreamStat.totalVideoHeight+=S,this._localStreamStat.videoCount++}if(a.msg_audio_status){let{uint32_audio_level:d}=a.msg_audio_status;Math.floor(d/id*100)>0&&(this._localStreamStat.totalAudioLevel+=d/id,this._localStreamStat.audioLevelCount++)}l.forEach(d=>{let{msg_user_info:h,msg_audio_status:y,msg_video_status:S}=d,k=h.str_identifier,V=this._room.remotePublishedUserMap.get(k);if(S.forEach(J=>{let cA=J.uint32_video_stream_type===2,CA=J.uint32_video_stream_type===7,MA="".concat(k,"_").concat(cA?"main":"auxiliary"),ie=this._remoteStreamStatMap.get(MA);if(ie&&(cA&&V!=null&&V.remoteVideoTrack.isSubscribed||CA&&V!=null&&V.remoteAuxiliaryTrack)){ie.totalVideoFPS+=J.uint32_video_receive_fps,ie.totalVideoBitrate+=J.uint32_video_codec_bitrate,ie.videoCount++,ie.statsToReport.uint32_video_width===0&&(ie.statsToReport.uint32_video_width=J.uint32_video_width),ie.statsToReport.uint32_video_height===0&&(ie.statsToReport.uint32_video_height=J.uint32_video_height);let pe=cA?V.remoteVideoTrack:V.remoteAuxiliaryTrack;pe.stat.jitterBufferDelay&&(ie.videoJitterBufferDelay=pe.stat.jitterBufferDelay),pe.stat.framesReceived&&(ie.statsToReport.uint32_video_consume_render_rate=Math.floor(pe.stat.framesDecoded/pe.stat.framesReceived*JS(10,6)))}}),!R0(y)){let J="".concat(k,"_main"),cA=this._remoteStreamStatMap.get(J);this._remoteStreamStatMap.has(J)&&cA&&V!=null&&V.remoteAudioTrack.isSubscribed&&(cA.totalAudioBitrate+=y.uint32_audio_codec_bitrate,cA.audioCount++,V.remoteAudioTrack.stat.jitterBufferDelay&&(cA.audioJitterBufferDelay=V.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(y.uint32_audio_level/id*100)>0&&(cA.totalAudioLevel+=y.uint32_audio_level/id,cA.audioLevelCount++),y.uint32_audio_block_time&&(cA.statsToReport.uint32_audio_block_time+=y.uint32_audio_block_time))}}),o.uint32_audio_capture_cost&&(this._captureCostSum+=o.uint32_audio_capture_cost,this._captureCostCount+=1,this._captureCostCount>=100&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0)),o.uint32_audio_capture_cost===0&&((e=this._room.audioManager.localAudioTrack)==null?void 0:e.muted)===!1&&(this._localStreamStat.statsToReport.uint32_audio_capture_thread_health_zero_cnt+=1)}}handlePublishStart(A){let{room:e}=A;this.hitTest(e)&&this._localStreamStat.publishStartTime===0&&(this._localStreamStat.publishStartTime=Date.now())}handleTrackCaptureStart(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_start_time&&(this._pathJoinRoom.uint64_init_audio_start_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_start_time&&(this._pathJoinRoom.uint64_init_camera_start_time=Date.now())}handleTrackCaptureSuccess(A){let{track:e}=A;e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=0,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=0,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}handleTrackCaptureFailed(A){let{track:e,error:o}=A,a={NotFoundError:1,NotAllowedError:2,NotReadableError:3,OverConstrainedError:4,AbortError:5,InvalidStateError:6,SecurityError:7,TypeError:8}[o.name]||(o instanceof gi?o.getExtraCode()||o.getCode():Ct.UNKNOWN);e.mediaType===1&&!this._pathJoinRoom.uint64_init_audio_end_time&&(this._pathJoinRoom.int32_init_audio_ret=a,this._pathJoinRoom.uint64_init_audio_end_time=Date.now()),e.mediaType===4&&!this._pathJoinRoom.uint64_init_camera_end_time&&(this._pathJoinRoom.int32_init_camera_ret=a,this._pathJoinRoom.uint64_init_camera_end_time=Date.now())}hasVideoFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&WS)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&ZS)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&zS)>=0}hitTest(A){return A===this._room}prepareReport(){if(this._captureCostCount>0&&!this._basicInfo.uint32_audio_capture_cost&&(this._basicInfo.uint32_audio_capture_cost=Math.floor(this._captureCostSum/this._captureCostCount),this._captureCostSum=0,this._captureCostCount=0),this._networkQuality.count>0&&(this._basicInfo.uint32_avg_rtt=Math.floor(this._networkQuality.totalUplinkRTT/this._networkQuality.count),this._basicInfo.uint32_avg_up_loss=Math.floor(this._networkQuality.totalUplinkLoss/this._networkQuality.count)),this._localStreamStat.videoCount>0){this._localStreamStat.statsToReport.uint32_video_big_capture_fps=Math.floor(this._localStreamStat.totalVideoFPS/this._localStreamStat.videoCount),this._localStreamStat.statsToReport.uint32_video_big_bitrate=Math.floor(this._localStreamStat.totalVideoBitrate/this._localStreamStat.videoCount);let A=Math.floor(this._localStreamStat.totalVideoWidth/this._localStreamStat.videoCount),e=Math.floor(this._localStreamStat.totalVideoHeight/this._localStreamStat.videoCount);this._localStreamStat.statsToReport.uint32_video_big_resolution=A<<16|e}this._localStreamStat.audioLevelCount>0&&(this._localStreamStat.statsToReport.uint32_audio_capture_db=Math.floor(this._localStreamStat.totalAudioLevel/this._localStreamStat.audioLevelCount*100)),this._remoteStreamStatMap.forEach((A,e)=>{let{userId:o}=A,a=this._networkQuality.totalDownlinkRTTAndLossMap.get(o);if(a){let{totalLoss:k,count:V,audioDelayCount:J,videoDelayCount:cA,totalAudioDelay:CA,totalVideoDelay:MA}=a;A.statsToReport.uint32_avg_down_loss=Math.floor(k/V),J&&CA&&(A.statsToReport.uint32_audio_network_p2p_delay=Math.floor(CA/J),A.audioJitterBufferDelay&&(A.statsToReport.uint32_p2p_delay=Math.floor(A.statsToReport.uint32_audio_network_p2p_delay+A.audioJitterBufferDelay))),cA&&MA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(MA/cA))}A.videoCount>0&&(A.statsToReport.uint32_video_avg_fps=Math.floor(A.totalVideoFPS/A.videoCount),A.statsToReport.uint32_video_avg_bitrate=Math.floor(A.totalVideoBitrate/A.videoCount)),A.audioCount>0&&(A.statsToReport.uint32_audio_recv_bitrate=A.statsToReport.uint32_audio_bitrate=Math.floor(A.totalAudioBitrate/A.audioCount)),A.audioLevelCount>0&&(A.statsToReport.uint32_audio_play_db=Math.floor(A.totalAudioLevel/A.audioLevelCount*100));let{callDurationCalculator:l}=this._room;l&&(A.statsToReport.uint32_audio_play_time=l.getDuration(e,YA.AUDIO),A.statsToReport.uint32_video_play_time=l.getDuration(e,YA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,ev));let{badCaseDetector:d}=this._room,{dataFreeze:h,count:y}=d.getDataFreezeDuration(e),{renderFreeze:S}=d.getRenderFreezeDuration(e);A.statsToReport.uint32_video_block_count=y,A.statsToReport.uint32_video_block_time=Math.min(h,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_video_external_block_time=Math.min(S,A.statsToReport.uint32_video_play_time),A.statsToReport.uint32_audio_block_time=Math.min(A.statsToReport.uint32_audio_block_time,A.statsToReport.uint32_audio_play_time),d.isBlackStream(e)&&A.statsToReport.uint32_video_avg_fps===0?A.statsToReport.uint32_video_black_screen_subjective=1:A.statsToReport.uint32_video_black_screen_subjective=0}),this._pathMainAudioMap.forEach((A,e)=>{this.hasAudioFlag(A.userId)?A.statsToReport.uint64_play_first_frame_time-A.statsToReport.uint64_start_enter_time>ev&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+ev):this._pathMainAudioMap.delete(e)}),this._pathMainVideoMap.forEach((A,e)=>{this.hasVideoFlag(A.userId)?A.statsToReport.uint64_render_first_frame_time-A.statsToReport.uint64_start_enter_time>ev&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+ev):this._pathMainVideoMap.delete(e)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>ev&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+ev)}getReportData(){this._basicInfo.uint32_networkType=Wf();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new Lj({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:aM(this._signalInfo.relayIp),uint32_client_ip:aM(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*JS(2,31)),msg_path_enter_room:this._pathJoinRoom,msg_path_exit_room:this._pathLeaveRoom,msg_path_recv_video:[...this._pathMainVideoMap.values()].map(e=>e.statsToReport),msg_quality_statistics:[...this._remoteStreamStatMap.values()].map(e=>e.statsToReport),str_room_name:String(this._room.roomId||0),msg_path_recv_audio:[...this._pathMainAudioMap.values()].map(e=>e.statsToReport),uint32_info_client_ip:aM(this._signalInfo.clientIp,!1),error_code:[],msg_local_statistics:this._localStreamStat.statsToReport,bytes_report_buf_from_0x1:this._signalInfo.endReportExtend,str_user_sig:this._room.userSig,bytes_report_token:this._signalInfo.reportToken};return T0(A),A}report(){return WA(this,null,function*(){try{this.prepareReport();let A=this.getReportData();yield this.upload(A),this.initData()}catch(A){this._log.warn(A)}finally{this.isDestroyed&&(this._room=null)}})}upload(A){return WA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),o=TA.enable?iQ(A,2001,e):yield tk(A),a=o instanceof ArrayBuffer,l="".concat(jf(e,kI.KEY_POINT),"&gzip=").concat(+a),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(l,o));let h=[this.uploadKVStat(si),this.uploadKVStat(AB)];d||h.push(oQ({url:l,body:o,priority:"low"})),yield Promise.all(h)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return WA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._room.sdkAppId;return function*(){var l,d;let h=e.getReportData((l=o._room)==null?void 0:l.userSig,(d=o._signalInfo)==null?void 0:d.reportToken);if(h.stats_count.length===0&&h.stats_distribution.length===0)return;h.msg_sdk_basic_info=po(fi({},h.msg_sdk_basic_info),{bytes_device_name:o._basicInfo.string_device_name||"",bytes_os_version:o._basicInfo.string_os_version||"",uint32_framework:o._frameWorkType,uint32_network_type:o._basicInfo.uint32_networkType||0}),o._log.debug(h);let y=TA.enable?iQ(h,2003,a):yield tk(h),S=y instanceof ArrayBuffer,k="".concat(jf(+a,kI.KV_STAT),"&gzip=").concat(+S),V=!1;navigator.sendBeacon&&(V=navigator.sendBeacon(k,y)),V||oQ({url:k,body:y})}()})}};hi([tB({settings:{timeout:500,retries:3}})],r8.prototype,"upload");var ev=5e3,HoA={msg_user_info:null,uint32_video_avg_fps:0,uint32_video_width:0,uint32_video_height:0,uint32_video_avg_bitrate:0,uint32_video_block_time:0,uint32_video_play_time:0,uint32_audio_block_time:0,uint32_audio_play_time:0,uint32_audio_play_db:0,uint32_avg_down_loss:0,uint32_stream_type:0,uint32_video_block_count:0,uint32_audio_block_count:0,uint32_audio_bitrate:0,uint32_video_black_screen_subjective:0,uint32_audio_recv_bitrate:0,uint32_video_external_block_time:0,uint32_video_consume_render_rate:0},Lj=class{constructor(A){Y(this,"str_identifier"),Y(this,"str_tinyid"),Y(this,"uint32_role"),this.str_identifier=String(A.userId),this.str_tinyid=String(A.tinyId||0),this.uint32_role=A.role}},qoA=r8,a8=class{constructor(){Y(this,"_startTime"),Y(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=ko())}stop(){this._endTime===0&&(this._endTime=ko())}getDuration(){return this._endTime===0?ko()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},KoA=class{constructor(A){Y(this,"_room",null),Y(this,"_durationMap"),Y(this,"_eventMap",new Map),this._room=A.room,this._durationMap=new Map,this.installEvents()}installEvents(){this._eventMap.set(nA.REMOTE_TRACK_SUBSCRIBED,this.handleSubscribed).set(nA.REMOTE_TRACK_UNSUBSCRIBED,this.handleUnsubscribed).set(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;var l;let{userId:d}=a;if(!this.hitTest(e))return;o.hasAudio&&!a.hasAudio&&this.stopDurationItem("".concat(d,"_main"),YA.AUDIO),o.hasVideo&&!a.hasVideo&&this.stopDurationItem("".concat(d,"_main"),YA.VIDEO),o.hasAuxiliary&&!a.hasAuxiliary&&this.stopDurationItem("".concat(d,"_auxiliary"),YA.VIDEO);let h=(l=this._room)==null?void 0:l.remotePublishedUserMap.get(d);h&&(!o.hasAudio&&a.hasAudio&&h.remoteAudioTrack.isSubscribed&&this.addDuractionItem(d,YA.AUDIO,"main"),!o.hasVideo&&a.hasVideo&&h.remoteVideoTrack.isSubscribed&&this.addDuractionItem(d,YA.VIDEO,"main"),!o.hasAuxiliary&&a.hasAuxiliary&&h.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(d,YA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,e)=>F.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>F.off(e,A,this)),this._eventMap.clear()}handleSubscribed(A){let{track:e}=A;if(!this.hitTest(e.room))return;let{userId:o,streamType:a,kind:l}=e;e.isSubscribed?this.addDuractionItem(o,l,a):this.stopDurationItem("".concat(o,"_").concat(a),l)}handleUnsubscribed(A){let{track:e}=A;this.hitTest(e.room)&&this.stopDurationItem("".concat(e.userId,"_").concat(e.streamType),e.kind)}isRecording(A){return A.findIndex(e=>e.endTime===0)>=0}addDuractionItem(A,e,o){let a="".concat(A,"_").concat(o),l=new a8,d=this._durationMap.get(a);d?this.isRecording(d[e])||d[e].push(l):this._durationMap.set(a,{userId:A,type:o,audio:e===YA.AUDIO?[l]:[],video:e===YA.AUDIO?[]:[l]})}stopDurationItem(A,e){if(this._durationMap.has(A)){let o=this._durationMap.get(A)[e].find(a=>a.endTime===0);o&&o.stop()}}hitTest(A){return this._room===A}getDuration(A,e){return this._durationMap.has(A)?this._durationMap.get(A)[e].reduce((o,a)=>o+a.getDuration(),0):0}getDurationMap(){return this._durationMap}reset(){this._durationMap.clear()}destroy(){this._room=null,this.uninstallEvents()}},joA=class{constructor(){Y(this,"renderFreezeMap",new Map),Y(this,"dataFreezeMap",new Map)}get(A,e){let o=this.renderFreezeMap.get(A),a=this.dataFreezeMap.get(A);return e?e==="data"?a:o:(Bg||or)&&o&&a&&o.duration>a.duration?o:a}set(A,e,o){o==="data"?this.dataFreezeMap.set(A,e):this.renderFreezeMap.set(A,e)}clear(){this.renderFreezeMap.clear(),this.dataFreezeMap.clear()}},WoA=class{constructor(A){Y(this,"_room"),Y(this,"_renderFreezeMap",new Map),Y(this,"_isVideoPlayingEventFiredMap",new Map),Y(this,"_dataFreezeMap",new Map),Y(this,"_monitorFreezeData",new joA),Y(this,"_eventMap",new Map),Y(this,"_videoEncodeFailedCount",0),Y(this,"_audioEncodeFailedCount",0),Y(this,"_encodeFailedThreshold",3),Y(this,"ABNORMAL_TIME_LOWER_LIMIT",3e3),Y(this,"ABNORMAL_TIME_UPPER_LIMIT",5e3),Y(this,"_videoAbnormalTimestampMap",new Map),Y(this,"_remoteVideoAbnormalTimestampMap",new Map),Y(this,"_audioAbnormalTimestampMap",new Map),Y(this,"eventListenerMap",new Map),this._room=A.room,this.installEvents()}getRenderFreezeMap(){return this._renderFreezeMap}getDataFreezeMap(){return this._dataFreezeMap}installEvents(){this._eventMap.set(nA.LEAVE_SUCCESS,A=>{let{room:e}=A;this.hitTest(e)&&this.stop()}).set(nA.PLAY_TRACK_START,this.onPlayTrackStart).set(nA.UNSUBSCRIBE_SUCCESS,A=>{let{room:e,streamType:o,remotePublishedUser:a}=A;if(!this.hitTest(e))return;let{userId:l}=a,d="".concat(l,"_").concat(o);this.stopDataFreeze({key:d,userId:l,type:o})}).set(nA.REMOTE_PUBLISH_STATE_CHANGED,A=>{let{room:e,prevMuteState:o,muteState:a}=A;if(!this.hitTest(e))return;let{userId:l}=a;if(o.hasVideo&&!a.hasVideo){let d="main",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}if(o.hasAuxiliary&&!a.hasAuxiliary){let d="auxiliary",h="".concat(a.userId,"_").concat(d);this.stopDataFreeze({key:h,userId:l,type:d})}}).set(nA.PLAYER_STATE_CHANGED,A=>{let{track:e,state:o,reason:a,type:l}=A;if(e.isRemote&&e.room&&this.hitTest(e.room)&&l===YA.VIDEO){if(o==="PLAYING"){let d="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.set(d,!0)}a===YA.MUTE?this.onVideoTrackMuted(e):a===YA.UNMUTE&&this.onVideoTrackUnmuted(e)}}).set(nA.HEARTBEAT_REPORT,this.onHearBeatReport).set(nA.REMOTE_VIDEO_PLAY_START,this.onRemoteVideoPlayStart).set(nA.REMOTE_VIDEO_PLAY_FINISH,this.onRemoteVideoPlayEnd),this._eventMap.forEach((A,e)=>F.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>F.off(e,A,this)),this._eventMap.clear()}stop(){this._renderFreezeMap.clear(),this._dataFreezeMap.clear(),this._isVideoPlayingEventFiredMap.clear()}onVideoTrackMuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,a="".concat(e,"_").concat(o),l=this._dataFreezeMap.get(a),d=new a8;l?l.durationItemList.push(d):this._dataFreezeMap.set(a,{userId:e,type:o,durationItemList:[d],isFreezing(){let h=this.durationItemList[this.durationItemList.length-1];return h&&h.endTime===0}})}onVideoTrackUnmuted(A){if(!A.isSubscribed)return;let{userId:e,streamType:o}=A,a="".concat(e,"_").concat(o);this.stopDataFreeze({key:a,userId:e,type:o})}onHearBeatReport(A){let{room:e,report:o}=A;this.hitTest(e)&&(this.localMediaTrackDetector(o),this.remoteMediaTrackDetector(o))}remoteMediaTrackDetector(A){A.msg_down_stream_info.length>0&&A.msg_down_stream_info.forEach(e=>{var o;if(e.msg_video_status.length===0)return;let a=e.msg_user_info.str_identifier,l=(o=this._room.remotePublishedUserMap.get(a))==null?void 0:o.remoteVideoTrack;e.msg_video_status.forEach(d=>{let h=ko();if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>0&&d.uint32_video_receive_fps===0&&l!=null&&l.muted)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-decode"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-decode"));y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT&&h-y=this.ABNORMAL_TIME_UPPER_LIMIT&&(sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_DECODE_RESUME_DURING_CALL)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-decode")))}if(d.uint32_video_codec_bitrate!==void 0&&d.uint32_video_codec_bitrate>5e5&&d.uint32_video_dec_fps!==void 0&&d.uint32_video_dec_fps<=5)if(this._remoteVideoAbnormalTimestampMap.has("".concat(a,"-hardware"))){let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));if(y&&h-y>this.ABNORMAL_TIME_LOWER_LIMIT/2&&h-y<2*this.ABNORMAL_TIME_UPPER_LIMIT){sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_HARDWARE_DECODE_FAILED)});let S=this._room.remotePublishedUserMap.get(a);if(S){let k=d.uint32_video_stream_type===2?S.remoteVideoTrack:S.remoteAuxiliaryTrack;k&&(k.log.warn("decode failed during call"),k.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(a,"-hardware"),h);else{let y=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));y&&h-y>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_HARDWARE_DECODE_RESUME)}),this._remoteVideoAbnormalTimestampMap.delete("".concat(a,"-hardware")))}})})}localMediaTrackDetector(A){if(A.msg_up_stream_info.msg_video_status){let e=A.msg_up_stream_info.msg_video_status,o=Array.from(this._room.localTracks).find(l=>l.kind==="video"&&!l.isScreen),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;e.forEach(l=>{let d=ko();if(l.uint32_video_stream_type===2)if(l.uint32_video_capture_fps!==0&&l.uint32_video_codec_bitrate===0&&l.uint32_video_enc_fps===0&&o!=null&&o.isPublished)if(this._videoAbnormalTimestampMap.has("local-encode")){let h=this._videoAbnormalTimestampMap.get("local-encode");h&&d-h>this.ABNORMAL_TIME_LOWER_LIMIT&&d-h=this.ABNORMAL_TIME_UPPER_LIMIT&&sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.VIDEO_ENCODE_RESUME_DURING_CALL)}),this._videoAbnormalTimestampMap.delete("local-encode")}})}if(A.msg_up_stream_info.msg_audio_status){let e=A.msg_up_stream_info.msg_audio_status,o=Array.from(this._room.localTracks).find(d=>d.kind==="audio"),a=o?.stat.bytesSent||0;if(o?.isMediaTrackActive===!1||a<=0||o!=null&&o.isUseCustomSource)return;let l=ko();if(e.uint32_audio_codec_bitrate===0&&o!=null&&o.isPublished)if(this._audioAbnormalTimestampMap.has("local-encode")){let d=this._audioAbnormalTimestampMap.get("local-encode");d&&l-d>this.ABNORMAL_TIME_LOWER_LIMIT&&l-d=this.ABNORMAL_TIME_UPPER_LIMIT&&sn.uploadEvent({userId:this._room.userId,log:"stat-".concat(Ja.AUDIO_ENCODE_RESUME_DURING_CALL)}),this._audioAbnormalTimestampMap.delete("local-encode")}}}stopDataFreeze(A){let{key:e,userId:o,type:a}=A,l=this._dataFreezeMap.get(e);if(!l||!l.isFreezing())return;let d=l.durationItemList[l.durationItemList.length-1];d.stop();let h=d.getDuration();if(h>Ub){let y=this._monitorFreezeData.get(e,"data");this._monitorFreezeData.set(e,{userId:o,type:a,duration:y?y.duration+h:h},"data")}else l.durationItemList.pop()}getTotalDuration(A){return A.reduce((e,o)=>{let a=o.getDuration();return e+Math.min(a,5e3)},0)}onPlayTrackStart(A){let{track:e}=A;if(!e.isRemote||!this.hitTest(e.room)||e.kind!==YA.VIDEO||!e.isRemotePublished)return;let o="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.has(o)||this._isVideoPlayingEventFiredMap.set(o,!1)}getDataFreezeDuration(A){let e={dataFreeze:0,count:0},o=this._dataFreezeMap.get(A);if(o){if(o.isFreezing()){let a=o.durationItemList[o.durationItemList.length-1];a.stop(),a.getDuration(){document.hidden||(l=0)};document.addEventListener("visibilitychange",d);let h=(y,S)=>{var k;if(l){let V=e.decodeFPS,J=V>0&&V<=5?600+1e3/V:600,cA=S.presentationTime-l;if(cA>J){cA=Math.min(cA,5e3);let CA="".concat(e.userId,"_").concat(e.streamType),MA=this._monitorFreezeData.get(CA,"render");MA?MA.duration+=cA:this._monitorFreezeData.set(CA,{userId:e.userId,type:e.streamType,duration:cA},"render");let ie=this._renderFreezeMap.get(CA);ie?(ie.totalDuration+=cA,ie.count+=1):this._renderFreezeMap.set(CA,{userId:e.userId,type:e.streamType,totalDuration:cA,count:1})}}l=S.presentationTime,(k=o.element)==null||k.requestVideoFrameCallback(h)};(a=o.element)==null||a.requestVideoFrameCallback(h),this.eventListenerMap.set("".concat(e.userId,"_").concat(e.streamType),{onVisibilityChange:d})}onRemoteVideoPlayEnd(A){let{track:e,player:o}=A,a="".concat(e.userId,"_").concat(e.streamType),l=this.eventListenerMap.get(a);l&&document.removeEventListener("visibilitychange",l.onVisibilityChange)}resetMonitor(){this._monitorFreezeData.clear()}hitTest(A){return A===this._room}destroy(){this.uninstallEvents()}},zoA=gc(jl(),1),ZoA=class{constructor(A,e,o,a,l){let d=arguments.length>5&&arguments[5]!==void 0?arguments[5]:1.3333333333333333;this.vbMode=A,this.faceDetectorHash=o,this.visionTaskRegistry=a,this.logger=l,Y(this,"animationState"),Y(this,"originalAspect"),Y(this,"totalOffsetX",0),Y(this,"totalOffsetY",0),Y(this,"defaultScaleRatio",.1),Y(this,"isRecovering",!1),Y(this,"boundaryY",280),Y(this,"lastActionTime",0),Y(this,"restTime",400),this.animationState={current:null,target:null,animating:!1,debounceTimer:null,startTime:0,duration:3e3,debounceTime:150,movementThreshold:30,debounceThreshold:15},this.addEvent(this.vbMode,!!this.faceDetectorHash),this.originalAspect=d||4/3,this.visionTaskRegistry.setVideo(this.faceDetectorHash,e)}addEvent(A,e,o){let a=[{key:570704,error:o??(e?void 0:11)},{key:570705,error:o??(e?void 0:22)}][A-1];a&&(e?si.addSuccessEvent({key:a.key}):si.addFailedEvent({key:a.key,error:a.error}))}actionCentering(A){let e=Date.now();if(this.animation(),!this.faceDetectorHash||e-this.lastActionTimee/2?(l=e-o-a,d=o-l):(l=o,d=0),{min:l,offset:d}}calculateTargetPosition(A,e,o,a,l,d){let h,y,S=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,k=A+o/2,V=e+a/2,{min:J,offset:cA}=this.calculateBoundary(k,l,A,o),{min:CA,offset:MA}=this.calculateBoundary(V,d,e,a);return h=2*J+o,y=2*CA+a,h/y>this.originalAspect?(h=y*this.originalAspect,cA=k-h/2):(y=h/this.originalAspect,MA=V-y/2),o/l>S&&(cA=0,MA=0,h=l,y=d),cA=Math.max(0,Math.min(cA,l-h)),MA=Math.max(0,Math.min(MA,d-y)),{sx:cA,sy:MA,cropWidth:h,cropHeight:y,timestamp:Date.now()}}processFacePositionCrop(A,e,o){if(!this.animationState.current||!this.animationState.target){let h={sx:0,sy:0,cropWidth:e,cropHeight:o,timestamp:Date.now()};return this.animationState.current=h,void(this.animationState.target=h)}let a=this.positionDistance(this.animationState.target,A),l=this.positionDistance(this.animationState.current,A),d=this.animationState.current.cropWidth/e;a>this.animationState.debounceThreshold*d&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&l>this.animationState.movementThreshold*d&&(this.animationState.target=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}processFacePositionPortrait(A){if(!this.animationState.current||!this.animationState.target)return this.animationState.current=fi({},A),void(this.animationState.target=fi({},A));let e=this.positionDistance(this.animationState.current,A),o=this.positionDistance(this.animationState.target,A);e>this.animationState.debounceThreshold&&(clearTimeout(this.animationState.debounceTimer),this.animationState.animating=!1),!this.animationState.animating&&o>this.animationState.movementThreshold&&(this.animationState.current=A,this.animationState.debounceTimer=setTimeout(()=>{this.animationState.startTime=Date.now(),this.animationState.animating=!0},this.animationState.debounceTime))}animation(){if(!this.animationState.animating)return;let A=Date.now()-this.animationState.startTime,e=Math.min(A/this.animationState.duration,1),o=a=>a<.5?2*a*a:(4-2*a)*a-1;if(this.animationState.current&&this.animationState.target){let a=(this.animationState.target.sx-this.animationState.current.sx)*o(e);this.animationState.current.sx+=a,this.totalOffsetX+=a;let l=(this.animationState.target.sy-this.animationState.current.sy)*o(e);if(this.animationState.current.sy+=l,this.totalOffsetY+=l,this.animationState.current.cropWidth+=(this.animationState.target.cropWidth-this.animationState.current.cropWidth)*o(e),this.animationState.current.cropHeight+=(this.animationState.target.cropHeight-this.animationState.current.cropHeight)*o(e),this.animationState.current.scaleRatio&&this.animationState.target.scaleRatio&&(this.animationState.current.scaleRatio+=(this.animationState.target.scaleRatio-this.animationState.current.scaleRatio)*o(e)),kn(this.animationState.current.scaleOffsetX)&&kn(this.animationState.target.scaleOffsetX)&&kn(this.animationState.current.scaleOffsetY)&&kn(this.animationState.target.scaleOffsetY)){let d=(this.animationState.target.scaleOffsetX-this.animationState.current.scaleOffsetX)*o(e);this.animationState.current.scaleOffsetX+=d;let h=(this.animationState.target.scaleOffsetY-this.animationState.current.scaleOffsetY)*o(e);this.animationState.current.scaleOffsetY+=h}}e>=1&&(this.animationState.animating=!1,this.animationState.current=this.animationState.target,this.isRecovering=!1)}positionDistance(A,e){return Math.sqrt(JS(A.sx-e.sx,2)+JS(A.sy-e.sy,2))}recoverOriginal(A,e){this.animationState.target={sx:0,sy:0,cropWidth:A,cropHeight:e,timestamp:Date.now()},this.animationState.animating=!0,this.animationState.startTime=Date.now(),this.isRecovering=!0}dualStageCropping(A,e,o,a,l,d){let h=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.3;if(this.isRecovering)return;let y=this.calculateTargetPosition(o,a,l,d,A,e);this.processFacePositionCrop(y,A,e),l*d/y.cropWidth/y.cropHeight>h&&this.recoverOriginal(A,e)}movingPortrait(A,e,o,a,l,d){var h,y,S,k,V,J,cA,CA,MA,ie,pe,qe;let we={sx:o+l/2+this.totalOffsetX,sy:a+d/2+this.totalOffsetY,cropWidth:A,cropHeight:e,scaleRatio:(y=(h=this.animationState.current)==null?void 0:h.scaleRatio)!=null?y:1,scaleOffsetX:(k=(S=this.animationState.current)==null?void 0:S.scaleOffsetX)!=null?k:0,scaleOffsetY:(J=(V=this.animationState.current)==null?void 0:V.scaleOffsetY)!=null?J:0,timestamp:Date.now()};this.animationState.target={sx:A/2,sy:a+d/2,cropWidth:A,cropHeight:e,scaleRatio:(CA=(cA=this.animationState.target)==null?void 0:cA.scaleRatio)!=null?CA:1,scaleOffsetX:(ie=(MA=this.animationState.target)==null?void 0:MA.scaleOffsetX)!=null?ie:0,scaleOffsetY:(qe=(pe=this.animationState.target)==null?void 0:pe.scaleOffsetY)!=null?qe:0,timestamp:Date.now()},this.animationState.animating||(this.animationState.target.scaleRatio=Math.sqrt(l*d/A/e/this.defaultScaleRatio),this.animationState.target.scaleOffsetX=-this.animationState.target.scaleRatio/2+.5,this.animationState.target.scaleOffsetY=1-this.animationState.target.scaleRatio,(this.animationState.target.sy-this.animationState.target.scaleOffsetY*this.animationState.target.cropHeight)/this.animationState.target.scaleRatio{A.log.error(o),A.destroy(new gi({code:Ct.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return WA(this,null,function*(){var e,o,a;this.predictReady=new Promise(y=>{this.resolvePreditReady=y});let l=A.Wasm,d=this.context.ctx;if(A.color&&(this._color=A.color),A.mat4&&(this._mat4=A.mat4),A.postProcessing&&(this._postProcessing=A.postProcessing),this._enableFaceCentering=(e=A.enableFaceCentering)!=null&&e,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null&&o,this.wasm=new l.AllIn1(d),this.wasm.blurRadius=A.blurRadius||3,this.wasm.mirror=!!A.mirror,this.wasm.rotation=A.rotation||0,this.wasm.vbMode=A.bg==="blur"?1:A.bg instanceof HTMLImageElement?2:A.bg==="color"?3:0,this._onAbort=A.onAbort,A.bg||this.resolvePreditReady(),A.waterMark){let{x:y,y:S,width:k,height:V}=A.waterMark;this.wasm.setWaterMark(y,S,k,V)}if(A.beautyParams){let{beauty:y,brightness:S,ruddy:k}=A.beautyParams;this.wasm.setBeauty(y,S,k,A?.width,A?.height)}this.program=this.wasm.init(),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this.program,"mask"),1),A.bg instanceof HTMLImageElement&&(d.uniform1i(d.getUniformLocation(this.program,"bg"),2),this._bgTexture=this.createTexture(A.bg)),A.waterMark&&(d.uniform1i(d.getUniformLocation(this.program,"waterMark"),3),this._waterMarkTexture=this.createTexture(A.waterMark.image));let h=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);if(this._textureMatrixLocation=d.getUniformLocation(this.program,"u_textureMatrix"),d.uniformMatrix4fv(this._textureMatrixLocation,!1,h),this._offsetMatrixLocation=d.getUniformLocation(this.program,"u_offsetMatrix"),d.uniformMatrix4fv(this._offsetMatrixLocation,!1,h),this._colorLocation=d.getUniformLocation(this.program,"u_color"),d.uniform1i(d.getUniformLocation(this.program,"lastMask"),4),this._weixin){let y=this.context.createShader(d.FRAGMENT_SHADER,`#version 300 es precision highp float; uniform sampler2D u_texture; uniform sampler2D mask; @@ -336,7 +336,7 @@ out vec2 v_texCoord; void main() { gl_Position = vec4(a_position.x, a_position.y, 0, 1); v_texCoord = a_texCoord; -}`);this._prePrograme=this.context.createProgram(S,y),d.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||this.wasm.vbMode!==2&&this.wasm.vbMode!==3?this._postProcessing=void 0:q0()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(a=this._postProcessing)==null||a.init(d,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(A)})}initVisionTasks(A){return KA(this,null,function*(){if(A.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new foA(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch{this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(A){let e=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let o=this.getMaskTexture(A);if(!o)return;let a=o;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,a=this._postProcessing.postProcessing(o)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a||null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&e.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=A,this.totalFrames++,this.centerFace(),$B(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),e.viewport(0,0,e.canvas.width,e.canvas.height),e.drawArrays(e.TRIANGLE_STRIP,0,4),A.close()}getMaskTexture(A){return A.confidenceMasks?A.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let A=this.context.ctx;this.useTexture(),A.texImage2D(A.TEXTURE_2D,0,A.RGBA,A.RGBA,A.UNSIGNED_BYTE,this.image)}render(A){let e=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:a,videoHeight:c}=o;if($B(this.wasm.rotation)&&!this._visionTaskRegistry&&([a,c]=[c,a]),a===0||c===0||!this.available)return!1;o.width=a,o.height=c;let d=!1;if(this.totalFrames)this.useTexture(),d=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),d=this._textureValid,this._textureValid=!0}if(this.width===a&&this.height===c&&d?e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,o):(this.resize(a,c),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)),this._weixin){if(e.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let C=this.getMaskTexture(this._segmentationMask);e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,C||null),e.bindFramebuffer(e.FRAMEBUFFER,this._lastMaskFbo||null)}e.drawArrays(e.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,a,c):e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,a,c,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let C=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(C)}}catch(C){this._onAbort&&this._onAbort(C)}return this.totalFrames||(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),e.drawArrays(e.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let A=this.context.ctx;this._centerFace.aspectRatio=A.canvas.width/A.canvas.height,this._centerFace.actionCentering(this.image);let{current:e,offset:o}=this._centerFace;if(e&&(this.wasm.vbMode===1&&this.drawImage(e.sx,e.sy,e.cropWidth,e.cropHeight),o&&this.wasm.vbMode===2)){if(!this._mat4)return;let a=this._mat4.create(),{scaleRatio:c=1,scaleOffsetX:d=0,scaleOffsetY:C=0}=e;this._mat4.fromTranslation(a,[-o.offsetX/A.canvas.width+d,C,0]),this._mat4.scale(a,a,[c,c,1]),A.uniformMatrix4fv(this._offsetMatrixLocation,!1,a)}}drawImage(A,e,o,a){let c=this.context.ctx;if(!this._mat4)return;let{width:d,height:C}=c.canvas,y=this._mat4.create();this._mat4.fromTranslation(y,[A/d,1-(e+a)/C,0]),this._mat4.scale(y,y,[o/d,a/C,1]),c.uniformMatrix4fv(this._textureMatrixLocation,!1,y)}close(){var A;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(A=this.wasm)==null||A.close()}},DoA=class extends AC{constructor(A){super(A,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:A.log,fragmentShaderSource:` +}`);this._prePrograme=this.context.createProgram(S,y),d.useProgram(this._prePrograme),this.setAttributes(this.positionBuffer,this.texCoordBuffer),d.uniform1i(d.getUniformLocation(this._prePrograme,"mask"),1)}!this._enableEffectOptimization||this.wasm.vbMode!==2&&this.wasm.vbMode!==3?this._postProcessing=void 0:W0()?(this._postProcessing=void 0,this.log.warn("Virtual background post-processing isn't allowed on mobile.")):(a=this._postProcessing)==null||a.init(d,this.positionBuffer,this.texCoordBuffer,4/3),yield this.initVisionTasks(A)})}initVisionTasks(A){return WA(this,null,function*(){if(A.bg){if(this._visionTaskRegistry=yield window.VisionTaskRegistry.getInstance(),!window.VisionTaskRegistry||!this._visionTaskRegistry||!this._visionTaskRegistry.visionWasm)throw new Error("Virtual background assets not found. Please redeploy the assets of the npm package.");if(this._selfieSegmentationHash=yield this._visionTaskRegistry.register(window.VisionTaskType.ImageSegmenter,{canvas:this.context._canvas}),this._visionTaskRegistry.setVideo(this._selfieSegmentationHash,this.image),this._enableFaceCentering)try{this._visionTaskRegistry.models.has(window.VisionTaskType.FaceDetector)||(yield this._visionTaskRegistry.preloadModels([window.VisionTaskType.FaceDetector]));let e=yield this._visionTaskRegistry.register(window.VisionTaskType.FaceDetector);if(!e)return;this._centerFace=new ZoA(this.wasm.vbMode,this.image,e,this._visionTaskRegistry,this.context.log)}catch{this.log.error("Face detector model not found. Please redeploy the assets of the npm package.")}}})}onPredict(A){let e=this.context.ctx;this._weixin&&(this._lastMaskTexture||(this._lastMaskTexture=this.createTexture(this.image),this._lastMaskFbo=this.createFramebuffer(this._lastMaskTexture)));let o=this.getMaskTexture(A);if(!o)return;let a=o;this._postProcessing&&(this._postProcessing.ratio=this.image.videoWidth/this.image.videoHeight,a=this._postProcessing.postProcessing(o)),this.useProgram(),this.setAttributes(this.positionBuffer,this.texCoordBuffer),this.useTexture(),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,a||null),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),this.wasm.vbMode===3&&e.uniform3fv(this._colorLocation,this._color),this.useBufferFrame(),this._segmentationMask=A,this.totalFrames++,this.centerFace(),tQ(this.wasm.rotation)&&this.resize(this.image.height,this.image.width),e.viewport(0,0,e.canvas.width,e.canvas.height),e.drawArrays(e.TRIANGLE_STRIP,0,4),A.close()}getMaskTexture(A){return A.confidenceMasks?A.confidenceMasks[0].getAsWebGLTexture():void 0}onFirstFrame(){this.waitingFirstFrame=!1;let A=this.context.ctx;this.useTexture(),A.texImage2D(A.TEXTURE_2D,0,A.RGBA,A.RGBA,A.UNSIGNED_BYTE,this.image)}render(A){let e=this.context.ctx,{image:o}=this;this.tryVideoFrameCallback();let{videoWidth:a,videoHeight:l}=o;if(tQ(this.wasm.rotation)&&!this._visionTaskRegistry&&([a,l]=[l,a]),a===0||l===0||!this.available)return!1;o.width=a,o.height=l;let d=!1;if(this.totalFrames)this.useTexture(),d=this._selfieTextureValid,this._selfieTextureValid=!0;else{if(!this.program)return!1;this.useTexture(),d=this._textureValid,this._textureValid=!0}if(this.width===a&&this.height===l&&d?e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,o):(this.resize(a,l),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o)),this._weixin){if(e.useProgram(this._prePrograme),this.useTexture(),this._segmentationMask){let h=this.getMaskTexture(this._segmentationMask);e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,h||null),e.bindFramebuffer(e.FRAMEBUFFER,this._lastMaskFbo||null)}e.drawArrays(e.TRIANGLE_STRIP,0,4),this.useTexture(),this._segmentationMask?e.copyTexSubImage2D(e.TEXTURE_2D,0,0,0,0,0,a,l):e.copyTexImage2D(e.TEXTURE_2D,0,e.RGBA,0,0,a,l,0)}try{if(this._selfieSegmentationHash&&this._visionTaskRegistry){let h=this._visionTaskRegistry.getResult(this._selfieSegmentationHash);this.totalFrames===1&&this.context._canvas&&this.resolvePreditReady(),this.onPredict(h)}}catch(h){this._onAbort&&this._onAbort(h)}return this.totalFrames||(e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this._bgTexture||null),e.activeTexture(e.TEXTURE3),e.bindTexture(e.TEXTURE_2D,this._waterMarkTexture||null),e.drawArrays(e.TRIANGLE_STRIP,0,4)),this._visionTaskRegistry&&this._visionTaskRegistry.resetHashResults(),!1}centerFace(){if(!this._centerFace||!this._enableFaceCentering)return;let A=this.context.ctx;this._centerFace.aspectRatio=A.canvas.width/A.canvas.height,this._centerFace.actionCentering(this.image);let{current:e,offset:o}=this._centerFace;if(e&&(this.wasm.vbMode===1&&this.drawImage(e.sx,e.sy,e.cropWidth,e.cropHeight),o&&this.wasm.vbMode===2)){if(!this._mat4)return;let a=this._mat4.create(),{scaleRatio:l=1,scaleOffsetX:d=0,scaleOffsetY:h=0}=e;this._mat4.fromTranslation(a,[-o.offsetX/A.canvas.width+d,h,0]),this._mat4.scale(a,a,[l,l,1]),A.uniformMatrix4fv(this._offsetMatrixLocation,!1,a)}}drawImage(A,e,o,a){let l=this.context.ctx;if(!this._mat4)return;let{width:d,height:h}=l.canvas,y=this._mat4.create();this._mat4.fromTranslation(y,[A/d,1-(e+a)/h,0]),this._mat4.scale(y,y,[o/d,a/h,1]),l.uniformMatrix4fv(this._textureMatrixLocation,!1,y)}close(){var A;super.close();let e=this.context.ctx;this._bgTexture&&e.deleteTexture(this._bgTexture),this._waterMarkTexture&&e.deleteTexture(this._waterMarkTexture),this._lastMaskTexture&&e.deleteTexture(this._lastMaskTexture),this._lastMaskFbo&&e.deleteFramebuffer(this._lastMaskFbo),this._prePrograme&&e.deleteProgram(this._prePrograme),this._postProcessing&&this._postProcessing.close(),(A=this.wasm)==null||A.close()}},$oA=class extends AC{constructor(A){super(A,{name:"yuv-source",useDefaultProgram:!1,create2d:!1,useFbo:!1,createTexture:!1,logger:A.log,fragmentShaderSource:` precision highp float; uniform sampler2D ySampler; uniform sampler2D uSampler; @@ -361,29 +361,29 @@ void main() { void main() { gl_Position = vertexPos; textureCoord = texturePos; - }`}),Y(this,"yTextureRef"),Y(this,"uTextureRef"),Y(this,"vTextureRef"),Y(this,"Y"),Y(this,"U"),Y(this,"V"),this.useProgram();let e=this.context.ctx;e.pixelStorei(e.PACK_ALIGNMENT,1),e.pixelStorei(e.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=A._canvas}_initTexture(A,e){let o=this.context.ctx,a=o.createTexture();return o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,A),e),a}render(A){let e=this.context.ctx,o=this.width,a=this.height;return this.useProgram(),e.viewport(0,0,o,a),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.yTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.LUMINANCE,e.UNSIGNED_BYTE,this.Y),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.uTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,a/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.U),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.vTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,a/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,e){super.resize(A,e);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A,e,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},Pz=(A,e)=>{switch(A){case"webCodecs":return e==="videoFrame"?514705:514706;case"wasm":return e==="webgl"?514707:e==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},SoA=0,MoA=class{constructor(A){Y(this,"id",SoA++),Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"decoder"),Y(this,"videoContext"),Y(this,"gop",0),Y(this,"gop_helper",0),Y(this,"waitFirstKeyFrame",!0),Y(this,"startTimestamp",0),Y(this,"startTime",0),Y(this,"startPerformanceTime",0),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"decodeFrameCount",0),Y(this,"downgradeLevel",0),Y(this,"lastDowngradeTime",0),Y(this,"lastFrameDiff",0),Y(this,"lastDecodeFrameTimestamp",0),Y(this,"config"),Y(this,"gop_before_configure",[]),Y(this,"videoElement"),Y(this,"type","wasm"),Y(this,"goodType"),Y(this,"renderer","2d"),Y(this,"wasmOption"),Y(this,"createDecoder"),Y(this,"_decodeSink"),Y(this,"isReported",!1),Y(this,"track"),Y(this,"stateChangeOB"),Y(this,"failedReason");let{track:e,createDecoder:o}=A;if(this.stateChangeOB=EQ(),this.track=e,this.createDecoder=o,this.wasmOption={yuvMode:A.renderer==="webgl",wasmPath:A.wasmPath,workerMode:A.workerMode,canvas:A.canvas},this.config=A.config,this.videoElement=A.videoElement,this.renderer=A.renderer,this.trackDoneOB=ca(e.availableState,Zs.OFF),this.stopOB=EQ(),A.type==="auto"){switch(A.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=A.type;this.changeRenderer(this.renderer),ma(this.stateChangeOB,S5((a,c)=>(a!==c&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:a,state:c}),c),"INITIALIZED"),EE(this.stopOB),Bl()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ma(this.pipe(this.track),EE(this.stopOB),AL());ma(e,Bl(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),ii.addFailedEvent({key:Pz(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),ii.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(A);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":this.renderer==="webgl"&&this.changeRenderer("videoFrame")}this.start(A+1)}},()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),ii.addSuccessEvent({key:Pz(this.type,this.renderer)}),ii.addSuccessEvent({key:514704})})),ma(e,l_(1),Bl(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.start()}close(A){this.stopOB.next(A)}changeRenderer(A){this.renderer=A,this.renderer==="videoFrame"&&!RM()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;if(this.failedReason)return;this.inputFrameCount++;let c=new Uint8Array(A.data);if((d=c)[0]!==0||d[1]!==0||d[2]!==0||d[3]!==1||c.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(c.subarray(0,5))),A;var d;let C=!1;switch(31&c[4]){case 5:case 7:C=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),C&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:A.data,timestamp:A.timestamp,type:A.type}),A;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(S=>this.decode(S,!0)),this.gop_before_configure=[]);let{timestamp:y}=A;if(C?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!C)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(c.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=y,this.startTime=Date.now(),this.startPerformanceTime=ko()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(y," ").concat((a=A.getMetadata)==null?void 0:a.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=y,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==A&&this.track.log.debug("downgrade level ".concat(A," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(e,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel))}pipe(A){return e=>KA(this,null,function*(){this._decodeSink=e;let o,a=A.mediaTrack;e.defer(()=>{var C;a&&(A.player.setCanvas(),A.setInputMediaStreamTrack(a)),o?.close(),(C=this.videoContext)==null||C.destroy(),delete this._decodeSink});let{renderer:c,type:d}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(d){case"wasm":o=this.createDecoder(d,this.wasmOption);break;case"webCodecs":o=this.createDecoder(d);break;default:throw new Error("not supported yet")}let C=0;if(o.on("videoFrame",y=>{this.decodedFrameCount++,C++,(C<=10||C%500==0)&&A.log.debug("frame ".concat(C," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(y.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(y.timestamp)),e.next(y)}),o.on("error",y=>{A.log.error(y),e.error(d==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),d==="wasm"&&c==="webgl"){this.videoContext=new VC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(VC.UNAVAILABLE,S=>{A.log.error(S),e.error(7)});let y=new DoA(this.videoContext);o.on("videoCodecInfo",S=>y.resize(S.width,S.height)),o.on("videoFrame",S=>{({y:y.Y,u:y.U,v:y.V}=S),this.downgradeLevel===1?this.decodedFrameCount%2==0&&y.render(this.decodedFrameCount):y.render(this.decodedFrameCount)}),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}else if(c==="videoFrame"){A.player.setCanvas();let y=new MediaStreamTrackGenerator({kind:"video"}),S=y.writable.getWriter();A.setInputMediaStreamTrack(y),o.on("videoFrame",k=>S.write(k))}else{this.videoContext=new CQ({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let y=this.videoContext.createVideoImageSource();o.on("videoFrame",k=>{try{y.image=k,y.update()}catch(V){delete this.goodType,A.log.error(V),e.error(11)}});let S=new qK(this.videoContext,{name:"remotePlayer",logger:A.log});y.connect(S),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(C){A.log.error(C),e.error(d==="webCodecs"?2:6)}})}},xz=Promise.resolve(),Yz=class extends moA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"videoContext"),Y(this,"_glVideoContext"),Y(this,"_2dVideoContext"),Y(this,"destination"),Y(this,"smallVideoContext"),Y(this,"smallDestination"),Y(this,"smallTrackSource"),Y(this,"smallImageSource"),Y(this,"_isMirror",!1),Y(this,"_rotation",0),Y(this,"cameraTrack"),Y(this,"cameraNode"),Y(this,"transformNode"),Y(this,"mixNode"),Y(this,"screenTrack"),Y(this,"screenNode"),Y(this,"selfModel",!1),Y(this,"blurRadius",3),Y(this,"arTrack"),Y(this,"_enableFaceCentering",!1),Y(this,"_enableEffectOptimization",!1),Y(this,"onAbort"),Y(this,"_color"),Y(this,"Wasm"),Y(this,"waterMarkNode"),Y(this,"_waterMarkOption"),Y(this,"watermarkImageList",[]),Y(this,"_beautyParams"),Y(this,"isUsingArTrack",!1),Y(this,"mixTrack"),Y(this,"_isMixScreen",!1),Y(this,"_virtualBackground"),Y(this,"_virtualBackgroundAbortCallback"),Y(this,"virtualBackgroundInstance"),Y(this,"_bgAssetPath"),Y(this,"log"),Y(this,"_mat4"),Y(this,"_postProcessing"),Y(this,"_checkId",0),Y(this,"_use2d",!1),Y(this,"_autoSwitchRenderMode",!0),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"updated",xz),Y(this,"_updateFlag",!1),this.log=QA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new CQ({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var A;return((A=this.room)==null?void 0:A.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(A){if(this._autoSwitchRenderMode=A==="auto",this._autoSwitchRenderMode)return;let e=A==="2d";this._use2d!==e&&(this._use2d=e,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:e,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return $B(this._rotation)?{width:o,height:e}:{width:e,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new CQ({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new VC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(m2<=22),this._glVideoContext.on(VC.UNAVAILABLE,A=>{var e;this.emit("error",A),this.log.warn("video context unavailable",A),(e=this._virtualBackgroundAbortCallback)==null||e.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,e,o){this.onAbort=A,this._mat4=e,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=Gr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,e;(A=this._2dVideoContext)==null||A.destroy(),(e=this._glVideoContext)==null||e.destroy(),this.smallVideoContext.destroy(),Gr.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Fp||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?ii.addFailedEvent({key:e,error:A}):ii.addSuccessEvent({key:e})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let e=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!e||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new VC({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var A;return(A=this.smallDestination)==null?void 0:A.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var A;return(A=this.cameraTrack)==null?void 0:A.mediaTrack}setSmallVideo(A,e){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new XtA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(VC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,e)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.resize(e.width,e.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:a}=this.cameraTrack.settings;this.smallTrackSource.resize(o,a),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var e,o;try{let a=this.cameraTrack,{small:c,player:d}=a;Fp&&d.setCanvas(A);let C=A&&((e=this.destination)==null?void 0:e.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),C=this.arTrack),this.log.info("set main output ".concat(C?C.label:"no output track")),this.setSmallVideo(c,A),F.emit(nA.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:C,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),a.setOutputMediaStreamTrack(C)}catch(a){this.log.error("set main output failed",a)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return KA(this,null,function*(){var e;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:a}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(AC.RENDER,c=>{var d;(d=this.cameraTrack)==null||d.emit("render",c)})),Zd===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof I_?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof I_?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(o.width,o.height);else if(A&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new ZtA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(AC.RENDER,y=>{var S;(S=this.cameraTrack)==null||S.emit("render",y)}));let{width:c,height:d}=this.cameraResolution,C=yield this.getWatermarkImage(c,d);this._waterMarkOption={x:0,y:0,width:C.width,height:C.height,image:C},this.cameraNode=new yoA(this.videoContext,{input:this.initialTrack,width:c,height:d,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=a.frameRate,this._use2d){let c=this.cameraNode;if(c.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Sy(this.videoContext,this.log,this._isMirror,this._rotation),c=c.connect(this.transformNode),c.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new F5(this.videoContext,this.log),c.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:C}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,C),d&&C&&this.waterMarkNode.resize(d,C)}(e=this.waterMarkNode)==null||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),c=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}c.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var A;this.destination&&((A=this.destination.ctx2d)==null||A.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(A){var e,o,a,c,d;if(A instanceof qM)return this.log.info("change screen input",(e=A.mediaTrack)==null?void 0:e.label),this.setScreenTrack(A);if(A instanceof dQ)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof cL){this.log.info("change remote input",(a=A.mediaTrack)==null?void 0:a.label);let C=A.mediaTrack;return A.setOutputMediaStreamTrack(C)}if(A instanceof jK)return this.log.info("change mix input",(c=A.outMediaTrack)==null?void 0:c.label),this.setMixTrack(A);this.log.warn("change unknown input",(d=A.mediaTrack)==null?void 0:d.label)}removeInput(A){var e;A instanceof qM?((e=this.screenNode)==null||e.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof dQ?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):A instanceof cL?A.source&&A.source.context.destroy():A instanceof jK&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return KA(this,null,function*(){return this.screenTrack=A,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(A.mediaTrack):yield this.update()),A.setOutputMediaStreamTrack(A.mediaTrack)})}getWatermarkImage(A,e){return KA(this,null,function*(){let o=document.createElement("canvas");e&&A&&(o.height=e,o.width=A);let a=o.getContext("2d");if(!a)throw new ai({code:dt.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((c,d)=>c.zIndex-d.zIndex),this.watermarkImageList.forEach(c=>{let{image:d,x:C,y,width:S,height:k,fillVideo:V}=c,J=V&&A||S,gA=V&&e||k,CA=V?0:C,MA=V?0:y;a.drawImage(d,CA,MA,J,gA)}),rM(o.toDataURL())})}pushWaterMarkImageList(A){let{type:e}=A;this.watermarkImageList.some(o=>o.imageUrl===A.imageUrl&&o.height===A.height&&o.width===A.width&&o.x===A.x&&o.y===A.y&&o.type===A.type&&o.zIndex===A.zIndex&&o.fillVideo===A.fillVideo)||((e==="mute"||e==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==e)),this.watermarkImageList.push(A))}setBeautyParams(A){return KA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return KA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return KA(this,null,function*(){let e;try{e=yield rM(A?.imageElement||A.imageUrl)}catch{throw new ai({code:dt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:a=0,width:c=e.width,height:d=e.height,type:C="watermark",zIndex:y=2,fillVideo:S=!1}=A;this.watermarkImageList.some(k=>k.type===C)?(this.watermarkImageList=this.watermarkImageList.filter(k=>k.type!==C),this.pushWaterMarkImageList({x:o,y:a,width:c,height:d,image:e,zIndex:y,type:C,imageUrl:A.imageUrl,fillVideo:S}),e=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(e.width,e.height),this.waterMarkNode.image=e):this.update()):(this.pushWaterMarkImageList({x:o,y:a,width:c,height:d,image:e,zIndex:y,type:C,imageUrl:A.imageUrl,fillVideo:S}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(k,V)=>k==="imageUrl"?void 0:V))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return KA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(e,o)=>e==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return KA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:o}=this.cameraResolution,a=yield this.getWatermarkImage(e,o);this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.update()})}setVirtualBackground(A){return KA(this,null,function*(){var e,o,a;if(A){if(A.onAbort&&(this._virtualBackgroundAbortCallback=A.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=A.assetPath,A.type==="image"?this._virtualBackground=yield rM(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(e=A.enableFaceCentering)!=null?e:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(a=A.color)!=null?a:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat(A?.type||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new ai({code:dt.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var e;this._isMixScreen=A,this._isMixScreen||((e=this.screenNode)==null||e.close(),delete this.screenNode),this.update()}set mirror(A){var e;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var e;this._rotation!==A&&(this._rotation=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return KA(this,null,function*(){var A;(A=this.cameraTrack)!=null&&A.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var A;this.isUsingArTrack=!1,(A=this.arTrack)==null||A.stop(),this.arTrack=void 0,this.update()}createDecodeContext(A){return new MoA(A)}clear(){var A,e;(A=this.videoContext)==null||A.disconnect(),(e=this.destination)==null||e.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:e,type:o}=A;var a;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var a;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}};Ci([r5(function(A){this.log.error("update failed",A)}),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{A.apply(this,o).then(c,d),setTimeout(d,5e3,new ai({code:dt.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],Yz.prototype,"update");var voA=0,RoA=class extends Zs{constructor(A){super("room"),Y(this,"seq",++voA),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"privateMapKey"),Y(this,"latencyLevel"),Y(this,"tinyId"),Y(this,"scene"),Y(this,"roomId"),Y(this,"useStringRoomId"),Y(this,"role","anchor"),Y(this,"joinParams",null),Y(this,"localPublishFlag",0),Y(this,"localTracks",new Set),Y(this,"enableAutoPlayDialog",!0),Y(this,"autoReceiveAudio",!0),Y(this,"autoReceiveVideo",!0),Y(this,"proxy_ws"),Y(this,"proxy_wt"),Y(this,"proxy_unified"),Y(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Y(this,"keyPointManager"),Y(this,"audioManager"),Y(this,"videoManager"),Y(this,"callDurationCalculator"),Y(this,"badCaseDetector"),Y(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Y(this,"videoDecodeFallbackType"),Y(this,"smallMode","canvas"),Y(this,"prelinkPromise",null),Y(this,"enableChorus",!1),Y(this,"_isUsingCachedSchedule",!1),Y(this,"_log"),Y(this,"_joinedTimestamp",0),Y(this,"_sdkType"),Y(this,"heartbeatReport"),Y(this,"heartbeatCount",0),Y(this,"quality"),Y(this,"enableSEI"),Y(this,"isDestroyed",!1),this._log=QA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,Nr(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),Nr(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),Nr(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new hoA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new BoA({room:this}),this.badCaseDetector=new poA({room:this}),this.audioManager=new oiA(this),this.videoManager=new Yz(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let A of this.localTracks)if(4&A.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let A of this.localTracks)if(2&A.mediaType)return!0;return!1}get hasAuxStream(){for(let A of this.remotePublishedUserMap.values())if(A.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let A of this.localTracks)if(1&A.mediaType)return A;return null}get localMainVideoTrack(){for(let A of this.localTracks)if(4&A.mediaType)return A;return null}get localAuxVideoTrack(){for(let A of this.localTracks)if(2&A.mediaType)return A;return null}get publishState(){let A={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(e=>{if(e.isPublished||e.isPublishing)switch(e.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=e.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,e,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((e=this.localMainVideoTrack)==null||!e.muted),auxVideo:!((o=this.localAuxVideoTrack)==null||!o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(A){return KA(this,null,function*(){return this.publish(A)})}removeTrack(A){return KA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return KA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Yn(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(lE(A)){let{websocketProxy:e,webtransportProxy:o,loggerProxy:a,scheduleProxy:c,unifiedProxy:d}=A;this.proxy_ws=e,this.proxy_wt=o,this.proxy_unified=d,d?($K([d,d]),VS("https://".concat(d))):(a&&VS(a),c&&$K(c))}F.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:em.main,sched_back_domain:em.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return KA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(e=>{A[e.userId]=e.remoteAudioTrack.stat}),A})}getTransportStats(){return KA(this,null,function*(){var A;let e={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return KA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(a=>{let c=e==="auxiliary"?a.remoteAuxiliaryTrack:a.remoteVideoTrack;o[a.userId]=c.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(cc.INVALID_DESTROY),new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,F.emit(nA.ROOM_DESTROY,{room:this})}schedule(A,e){return KA(this,null,function*(){var o,a,c,d;let C=ko();try{let{isCached:y,result:S,detailCost:k}=yield tz({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:qd,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:e,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=y,this._log.info("schedule cache:".concat(+y," ").concat(zd(S,{keysToExclude:["username","credential"]}))),y&&F.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=mi(mi({},this.scheduleResult),S),bn((o=S.config)==null?void 0:o.retryCount)&&c0(S.config.retryCount),Yn((a=S.config)==null?void 0:a.loggerDomain)&&VS(S.config.loggerDomain),this.videoDecodeFallbackType=((c=S.config)==null?void 0:c.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=S.config)==null?void 0:d.smallMode)||this.smallMode,F.emit(nA.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:k}),ii.addSuccessEvent({key:521700,cost:ko()-C})}catch(y){throw ii.addFailedEvent({key:521700,error:y}),y}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,e,o,a,c,d){return KA(this,null,function*(){return Promise.resolve()})}closePrelink(){return KA(this,null,function*(){return Promise.resolve()})}},woA=gc(Kl()),Vz=gc(Qb());function Jz(A){var e;let o=[];for(let a=0;ad.payload===A.rtp[a].payload)[0];o.push({payload:A.rtp[a].payload,codec:A.rtp[a].codec,fmtp:c?c.config:"",rate:A.rtp[a].rate,rtx:((e=A.rtp[a+1])==null?void 0:e.codec)==="rtx"?A.rtp[a+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(d=>d.payload===A.rtp[a].payload).map(d=>{let{type:C,subtype:y}=d;return{id:C,params:y?[y]:[]}})})}return o}var _oA=(A,e,o)=>KA(null,null,function*(){var a;let c=uc(A),d={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};d.ice.ufrag=String(c.media[0].iceUfrag),d.ice.password=c.media[0].icePwd||"",c.fingerprint&&(d.dtls.hash=c.fingerprint.type,d.dtls.fingerprint=c.fingerprint.hash,d.dtls.setup=c.setup||""),c.media[0].fingerprint&&(d.dtls.hash=c.media[0].fingerprint.type,d.dtls.fingerprint=c.media[0].fingerprint.hash),d.dtls.setup=c.media[0].setup||"";let C=c.media[0],y=c.media[1];C.ext&&(d.audio.extensions=C.ext.map(k=>({id:k.value,uri:k.uri}))),y.ext&&(d.video.extensions=y.ext.map(k=>({id:k.value,uri:k.uri})));for(let k of C.rtp){if(k.codec!=="opus")continue;let V=C.fmtp.find(gA=>gA.payload===k.payload);if(!V)continue;let J={codec:k.codec,fmtp:V.config,payload:V.payload,rate:k.rate,channels:k.encoding,rtcpfb:[],rtx:0};(a=C.rtcpFb)==null||a.forEach(gA=>{let{payload:CA,type:MA,subtype:$A}=gA;if(CA===J.payload){let Be={id:MA,params:[]};$A&&Be.params.push($A),J.rtcpfb.push(Be)}}),d.audio.codecs.push(J);break}let S=["h264","vp8","h265"];return e&&S.shift(),d.video.codecs=[...Jz(y)].filter(k=>S.includes(k.codec.toLocaleLowerCase())),d.video.decoders=(yield function(){return KA(this,null,function*(){let k=new RTCPeerConnection;k.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY});let V=yield k.createOffer();if(!V.sdp)return[];let J=Jz(uc(V.sdp).media[0]);return k.close(),J})}()).filter(k=>["h264","vp8","h265"].includes(k.codec.toLocaleLowerCase())),d}),Hz=(A,e)=>{let o=(A||"").trim(),a=(e||"").trim(),c="profile-level-id",d="".concat(c,"=[0-9a-fA-F]{6}");if(new RegExp(d).test(o)){let y=new RegExp(d,"g");return o.replace(y,"".concat(c,"=").concat(a))}if(!o)return"".concat(c,"=").concat(a);let C=o.endsWith(";")?"":";";return"".concat(o).concat(C).concat(c,"=").concat(a)},ToA=A=>{let{serverAbility:e,clientAbility:o,offerSDP:a,enableCustomMessage:c,profileLevelIdConfig:d}=A,C=uc(a),y={extmapAllowMixed:"extmap-allow-mixed",groups:C.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},S={candidates:e.candidates.map(V=>({component:1,foundation:"1",generation:0,ip:V.ip,port:V.port,priority:V.priority,transport:V.foundation,type:V.type})),connection:{version:4,ip:"0.0.0.0"},direction:YA.TRANSCEIVER_DIRECTION_RECVONLY,ext:e.audio.extensions.map(V=>({value:V.id,uri:V.uri})),fingerprint:{type:e.dtls.hash,hash:e.dtls.fingerprint},fmtp:[{payload:e.audio.codecs[0].payload,config:e.audio.codecs[0].fmtp}],icePwd:e.ice.password,iceUfrag:e.ice.ufrag,mid:"0",payloads:String(e.audio.codecs[0].payload),port:C.media[0].port,protocol:C.media[0].protocol,type:YA.AUDIO,setup:e.dtls.setup,rtcpFb:e.audio.codecs[0].rtcpfb.map(V=>({payload:e.audio.codecs[0].payload,type:V.id,subtype:V.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:e.audio.codecs[0].payload,codec:e.audio.codecs[0].codec,rate:e.audio.codecs[0].rate,encoding:e.audio.codecs[0].channels}]};y.media.push(S);let k=[d?.big,d?.small,d?.aux];return[1,2,3].forEach((V,J)=>{y.media.push(qz({mid:V,serverAbility:e,clientAbility:o,parsedOffer:C,profileLevelId:k[J]}))}),c&&y.media.push(C.media.find(V=>V.mid==="dc")),vy(y)},qz=A=>{let{mid:e,serverAbility:o,clientAbility:a,parsedOffer:c,isDownlink:d=!1,profileLevelId:C}=A,y={candidates:o.candidates.map(S=>({component:1,foundation:"1",generation:0,ip:S.ip,port:S.port,priority:S.priority,transport:S.foundation,type:S.type})),connection:{version:4,ip:"0.0.0.0"},direction:YA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(S=>({value:S.id,uri:S.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(e),payloads:"",port:c.media[0].port,protocol:c.media[0].protocol,type:YA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(d){let S=o.video.decoders;(!S||S.length===0)&&(S=o.video.codecs),(!S||S.length===0)&&(S=a.video.decoders),S.forEach(k=>{Q_(y,k)})}else{let S;S=o.useH265?o.video.codecs.findIndex(V=>V.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(V=>V.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let k=o.video.codecs[S]||a.video.codecs[0];Q_(y,k)}if(!d&&C){let S=y.fmtp,k=y.rtp.find(V=>{var J;return((J=V.codec)==null?void 0:J.toLowerCase())==="h264"});if(k){let V=S.find(J=>String(J.payload)===String(k.payload));V&&(V.config=Hz(V.config,C))}}return y},Q_=(A,e)=>{A.payloads="".concat(A.payloads," ").concat(e.payload).trim(),A.fmtp.push({payload:e.payload,config:e.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...e.rtcpfb.map(o=>({payload:e.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:e.payload,codec:e.codec.toUpperCase(),rate:e.rate}),e.rtx&&(A.payloads="".concat(A.payloads," ").concat(e.rtx),A.fmtp.push({payload:e.rtx,config:"apt=".concat(e.payload)}),A.rtp.push({payload:e.rtx,codec:"rtx",rate:e.rate}))},NoA=(A,e,o)=>{let a=Vz.default.parse(A);return a.media.forEach((c,d)=>{var C;if((c.type===YA.AUDIO||c.type===YA.VIDEO)&&(function(y){if(!y.rtcpFb)return;let S=[];y.rtcpFb.forEach((k,V)=>{var J;S.push(k),y.rtcpFb&&((J=y.rtcpFb[V+1])==null?void 0:J.payload)!==k.payload&&k.type!=="rrtr"&&S.push({payload:k.payload,type:"rrtr"})}),y.rtcpFb=S}(c),function(y){y.type===YA.VIDEO&&y.fmtp&&y.fmtp.forEach(S=>{S.config.includes("apt")||(S.config+=";sps-pps-idr-in-keyframe=1")})}(c),function(y){y.type===YA.AUDIO&&y.fmtp&&y.fmtp.forEach(S=>{S.config+=";sprop-stereo=1;stereo=1"})}(c),function(y){let S=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);y.ext&&(y.ext=y.ext.filter(k=>!S.has(k.uri)))}(c),c.type===YA.VIDEO)){if(d<4)c.payloads="",c.fmtp=[],c.rtp=[],c.rtcpFb=[],e.video.codecs.forEach(y=>Q_(c,y));else if(o){c.payloads="",c.fmtp=[],c.rtp=[],c.rtcpFb=[];let y=o.video.decoders;(!y||y.length===0)&&(y=o.video.codecs),(!y||y.length===0)&&(y=e.video.decoders),y.forEach(S=>Q_(c,S))}}(C=c.payloads)!=null&&C.includes("datachannel")&&a.groups&&c.mid&&(a.groups[0].mids=a.groups[0].mids.replace(c.mid,"dc"),c.mid="dc")}),Vz.default.write(a)};function fj(A){var e,o;let a=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(e=a?.[1])==null?void 0:e.toLowerCase())!=null?o:null}function yj(A){let e=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(e))return"unknown";let o=parseInt(e.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function Kz(A,e){if(!e)return"";let o=A.trim().toLowerCase().replace(/_/g,"-");if(!o)return"";if(/^[0-9a-f]{6}$/.test(o))return o;if(o!=="baseline"&&o!=="main"&&o!=="high")return"";for(let a of e.video.codecs){let c=fj(a.fmtp);if(c&&yj(c)===o)return c}return""}var GoA=gc(Kl()),jz=class extends GoA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"mainFpsHealth",1),Y(this,"mainBitrateHealth",1),Y(this,"badMainBitrateHealthCount",0),Y(this,"lastEmitBadHealthTime",0),Y(this,"log"),!Ha&&IE&&F.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:e,streamType:o,isHWCodec:a,codec:c}=A;if(!e&&o!==7&&c==="h264"){if(!a)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(A){Date.now()-this.lastEmitBadHealthTime<3e4||(A.msg_up_stream_info.msg_video_status.forEach(e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let o=e.uint32_video_enc_fps/e.uint32_video_capture_fps;e.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(e.uint32_video_codec_bitrate&&e.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/o.profile.bitrate)}}),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){F.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Y(jz,"EVENT_BAD_HEALTH","bad_health");var boA=jz,p_=(A=>(A.TRACK="track",A.DATA_CHANNEL_MESSAGE="data_channel_msg",A[A.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",A[A.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",A.RECONNECTED="spc-reconnected",A.RECONNECT_FAILED="spc-reconnect-failed",A.ERROR="error",A.SEI_MESSAGE="sei-message",A.DUMP="dump",A))(p_||{}),koA=1,Ry=class extends woA.default{constructor(A){let{signalChannel:e,room:o,enableDataChannel:a}=A;super(),Y(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Y(this,"isDestroyed",!1),Y(this,"currentState","DISCONNECTED"),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_peerConnection",null),Y(this,"_datachannel",null),Y(this,"_enableDataChannel"),Y(this,"_log"),Y(this,"_downlinkMIDMap",new Map),Y(this,"_downlinkMIDUserIDMap",new Map),Y(this,"_reconnectionTimer",-1),Y(this,"reconnectionCount",0),Y(this,"clientAbility"),Y(this,"_serverAbility",null),Y(this,"addDownlinkQueue",new Set),Y(this,"removeDownlinkQueue",new Set),Y(this,"_parsedAnswer",null),Y(this,"_updateSDPPromise",null),Y(this,"_waitForPCConnectedPromise"),Y(this,"clearWaitForConnectedPromise"),Y(this,"clearConnectTimeout"),Y(this,"_isSDPLogged",!1),Y(this,"enableInsertableStreams",!1),Y(this,"insertableStreamsAbortMap",new Map),Y(this,"receiverRemoteTrackMap",new WeakMap),Y(this,"scriptTransformWorker"),Y(this,"_isRelayTried",!1),Y(this,"_rttOverCount",0),Y(this,"originOffer",null),Y(this,"autoSubscribedSsrcGroups",new Map),Y(this,"autoSubscribedUserMap",new Map),Y(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=a,this._signalChannel=e,this._log=QA.createLogger({parent:this._room.getLogger(),id:"spc".concat(koA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Kp?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let A=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h264")),A}addAbortController(A,e){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,e)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,e,o;let a=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(c=>["h264","vp8","h265"].includes(c.codec.toLowerCase()));return a?a.codec.toLowerCase():(e=this._serverAbility)!=null&&e.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,e,o;return(A=this._serverAbility)!=null&&A.useH265&&(e=this._serverAbility)!=null&&e.video.decoders.find(a=>a.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(a=>a.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(A=>A.fmtp.includes("42001f"))}isProfileLevelIdSupported(A){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let e=uc(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return e.media.forEach((a,c)=>{var d;if(a.ssrcs&&!Je(a.ssrcs[0].id)){let C=Number(a.ssrcs[0].id),y=Number((d=a.ssrcs.filter(S=>S.attribute==="cname")[1])==null?void 0:d.id);switch(c){case 0:o.audioSsrc=C;break;case 1:o.bigVideoSsrc=C,o.bigVideoRtxSsrc=y;break;case 2:o.smallVideoSsrc=C,o.smallVideoRtxSsrc=y;break;case 3:o.auxVideoSsrc=C,o.auxVideoRtxSsrc=y}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){e_&&(this.scriptTransformWorker=uz({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=A=>{A.data.type==="sei"?this.emit("sei-message",A.data):A.data.type,A.data.type==="dump"&&this.emit("dump",A.data)},this.scriptTransformWorker.onerror=A=>{this._log.error("scriptTransformWorker error: ",A.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let A=this._peerConnection.getSenders();return A.length===0?null:A[0].transport}getPeerConnectionConfig(A){var e;let o={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:A,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},a=(e=this._peerConnection)==null?void 0:e.getConfiguration().encodedInsertableStreams;return I2(a)&&(o.encodedInsertableStreams=a),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return KA(this,null,function*(){var e;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let a=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(a)),a==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():a==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),ii.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):a==="failed"&&ii.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var a;let c=((a=this._peerConnection)==null?void 0:a.signalingState)||"";this._log[c==="closed"?"debug":"info"]("signaling state: ".concat(c))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=a=>this.emit("track",a),this._enableDataChannel&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=a=>{let c=new UoA(a.data);this.emit("data_channel_msg",{data:c})},this._datachannel.onerror=a=>{this._log.warn("datachannel error",a)}),this._peerConnection.addTransceiver(YA.AUDIO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield _oA(o.sdp,((e=this._room.scheduleResult.config)==null?void 0:e.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:a}=this;a&&(this._log.debug("dtls state: ".concat(a.state)),a.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():a.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),ii.addSuccessEvent({key:521707}),this.clientAbility}catch(a){throw ii.addFailedEvent({key:521707,error:a}),this._log.error("initialize failed ".concat(a,` -offer: `).concat(o?.sdp)),a}})}setIceServers(A){return KA(this,null,function*(){var e;if(this._peerConnection&&A.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(A,(o,a)=>o==="username"||o==="credential"?"hided":a)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(A)),(e=this._peerConnection)!=null&&e.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(o){this._log.warn("setIceServers error ",o)}})}setPriority(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach(e=>{let o=e.getParameters();o.encodings[0]&&(o.encodings[0].priority=A,o.encodings[0].networkPriority=A,e.setParameters(o).catch(a=>{this._log.warn("setPriority error ",a)}))})}catch(e){this._log.warn("setPriority error ",e)}}connect(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return KA(this,null,function*(){var o,a,c;try{if(this.currentState==="CONNECTED")return;((o=this._peerConnection)==null||!o.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let d=ko(),C=this.getProfileLevelIdConfig(),y={type:"answer",sdp:ToA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:C})};this._serverAbility=A,yield this.setAnswer(y),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let S=((a=this._room.scheduleResult.config)==null?void 0:a.priority)||((c=this._room.joinParams)==null?void 0:c.priority)||new URLSearchParams(location.search).get("priority");S&&this.setPriority(S),e||ii.addSuccessEvent({key:521703,cost:ko()-d})}catch(d){let C=d instanceof ai&&d.code===dt.API_CALL_ABORTED;throw C||this._log.error("connect failed: ".concat(d),A),this.reset(),!C&&!this.isReconnecting&&!this.isDestroyed&&(ii.addFailedEvent({key:521703,error:d}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),d}})}reconnect(){return KA(this,null,function*(){if(this._reconnectionTimer===-1){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(hL,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let A=this._signalChannel.getBackupRelayIpPair(),e=yield this.initialize(this._room.getIceServers(A!=null&&A.iceServer?[A.iceServer]:[])),o=mi({ability:e},A),a=yield this._signalChannel.sendWaitForResponse({command:toA,responseCommand:ls.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(a.data.code!==0)throw new ai({code:a.data.code,message:a.data.message});yield this.connect(a.data.data.ability,!0),ii.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),F.emit(nA.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(A){if(!this.isReconnecting||this.isDestroyed)return;if(A!=null&&A.message.includes("timeout")){let e=Rp(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield LC(e,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),ii.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=xf()&&this._log.warn("SDK has tried reconnect for ".concat(xf()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")})}getPeerConnection(){return this._peerConnection}startReconnection(){return KA(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var A;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(A=this.clearConnectTimeout)==null||A.call(this),this._signalChannel.off(hL,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===Co.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(A){var e;let o=((e=this._peerConnection)==null?void 0:e.iceConnectionState)||"closed",a=this.getDTLSTransportState();this._log.info("connectionState: ".concat(A.target.connectionState," ICE: ").concat(o," DTLS: ").concat(a)),A.target.connectionState===Co.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===Co.FAILED||A.target.connectionState===Co.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===Co.CONNECTED||A.target.connectionState===Co.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),F.emit(nA.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return Kh;let A=null;return LI()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,dy()&&this._peerConnection.getReceivers().length!==0&&A?A.state:Kh):Kh}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(p_.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return KA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[e,o]of A)if(_M(o)){let a=A.get(o.localCandidateId),c=A.get(o.remoteCandidateId);a&&(this._log.info("local candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port," ").concat(a.networkType||""," ").concat(a.relayProtocol?"relayProtocol:".concat(a.relayProtocol," url: ").concat(a.url):"")),a.networkType&&f0(a.networkType)),c&&this._log.info("remote candidate: ".concat(c.candidateType," ").concat(c.protocol,":").concat(c.ip||c.address,":").concat(c.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((A,e)=>{if(this.currentState==="CONNECTED")return A();let o=C=>{C.state==="CONNECTED"&&(clearTimeout(d),c(),A())},a=C=>{let{room:y}=C;y===this._room&&(clearTimeout(d),c(),e(new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.CONNECTION_ABORTED,data:"leave room"})})))},c=()=>{F.off(nA.LEAVE_SUCCESS,a,this),this.off(p_.CONNECTION_STATE_CHANGED,o,this)},d=setTimeout(()=>{c();let C=new ai({code:dt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(C)},Nb);this.clearConnectTimeout=()=>{c(),clearTimeout(d),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,e(new ai({code:dt.API_CALL_TIMEOUT,message:"connection timeout"}))},F.on(nA.LEAVE_SUCCESS,a,this),this.on(p_.CONNECTION_STATE_CHANGED,o,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout})),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise((A,e)=>{this.once("spc-reconnected",A),this.once("error",e)}):Promise.resolve()}addDownlink(A){return KA(this,null,function*(){if(this._log.info("addDownlink(".concat(A.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(A),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(A.userId,") done"))}catch(e){this._log.error("addDownlink(".concat(A.userId,") failed ").concat(e)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(A){let{ssrc:e,userId:o,tinyId:a,prevMids:c}=A;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(o," ").concat(JSON.stringify(e))),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let d,C,y,S=this._parsedAnswer.media.filter(J=>{var gA;return(gA=J.ssrcs)==null?void 0:gA.find(CA=>{var MA;return(MA=CA.value)==null?void 0:MA.includes(a)})});if(S.length===3)d=S[0],C=S[1],y=S[2];else{let J,gA=this._peerConnection.getTransceivers().slice(4);if(c?.length===3&&c.every(MA=>{var $A;return(($A=gA.find(Be=>Number(Be.mid)===MA))==null?void 0:$A.direction)==="inactive"})?(J=c,this._log.info("reusing previous mids for ".concat(o,": ").concat(J.join(","))),gA.forEach(MA=>{J.includes(Number(MA.mid))&&(MA.direction=YA.TRANSCEIVER_DIRECTION_RECVONLY)})):J=gA.filter(MA=>MA.direction==="inactive").slice(0,3).map(MA=>(MA.direction=YA.TRANSCEIVER_DIRECTION_RECVONLY,Number(MA.mid))),J.length===3)d=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[0])),C=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[1])),y=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[2]));else if(J.length===0){this._peerConnection.addTransceiver(YA.AUDIO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),d=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let MA=qz({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:uc(this._peerConnection.localDescription.sdp),isDownlink:!0});C=JSON.parse(JSON.stringify(MA)),y=JSON.parse(JSON.stringify(MA)),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),C.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(C),y.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(y)}}d.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY;let k="".concat(a,"-").concat(e.audio);d.ssrcs=[{id:e.audio,attribute:"cname",value:"".concat(k)},{id:e.audio,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-audio")}],C.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY,C.ssrcs=[{id:e.video,attribute:"cname",value:"".concat(k)},{id:e.video,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-bigvideo")},{id:e.videoRtx,attribute:"cname",value:"".concat(k)},{id:e.videoRtx,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-bigvideo")}],C.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.video," ").concat(e.videoRtx)}],y.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY;let V="".concat(k,"-aux");y.ssrcs=[{id:e.auxiliary,attribute:"cname",value:V},{id:e.auxiliary,attribute:"msid",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)},{id:e.auxiliaryRtx,attribute:"cname",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)},{id:e.auxiliaryRtx,attribute:"msid",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)}],y.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.auxiliary," ").concat(e.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(J=>J.mid).join(" ")),this._downlinkMIDMap.set(o,[d.mid,C.mid,y.mid]),this._downlinkMIDUserIDMap.set(d.mid,o),this._downlinkMIDUserIDMap.set(C.mid,o),this._downlinkMIDUserIDMap.set(y.mid,o)}removeDownlink(A){return KA(this,null,function*(){if(!this._downlinkMIDMap.has(A)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(A,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let e=this._downlinkMIDMap.get(A),o=!1;return this._peerConnection.getTransceivers().forEach(a=>{e!=null&&e.includes(Number(a.mid))&&(o=!0,a.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(a=>{e!=null&&e.includes(Number(a.mid))&&(o=!0,a.direction="inactive",a.ssrcs=[],a.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP()),this._downlinkMIDMap.delete(A),e?.forEach(a=>this._downlinkMIDUserIDMap.delete(a)),this._log.info("removeDownlink(".concat(A,") done")),e})}setBandwidth(A){return KA(this,null,function*(){if(!this._peerConnection)return;let{audio:e,bigVideo:o,smallVideo:a,auxVideo:c}=A;try{if(Ok()){let d=this._peerConnection.getSenders().slice(0,4);for(let y=0;y5e3?5e3:e),!0)}setSenderMaxBitrate(A,e){let o=A.getParameters();if((!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]),e==="unlimited")delete o.encodings[0].maxBitrate;else{if(o.encodings[0].maxBitrate===1e3*e)return;o.encodings[0].maxBitrate=1e3*e}return A.setParameters(o)}setBandwidthBySDP(A){let{audio:e,bigVideo:o,smallVideo:a,auxVideo:c}=A;if(!this._peerConnection||!this._peerConnection.localDescription)return;let d=uc(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let C=er?"TIAS":"AS";e&&(d.media[0].bandwidth=[{type:C,limit:er?1e3*e:e}],this._parsedAnswer.media[0].bandwidth=[{type:C,limit:er?1e3*e:e}]),o&&(d.media[1].bandwidth=[{type:C,limit:er?1e3*o:o}],this._parsedAnswer.media[1].bandwidth=[{type:C,limit:er?1e3*o:o}]),a&&(d.media[2].bandwidth=[{type:C,limit:er?1e3*a:a}],this._parsedAnswer.media[2].bandwidth=[{type:C,limit:er?1e3*a:a}]),c&&(d.media[3].bandwidth=[{type:C,limit:er?1e3*c:c}],this._parsedAnswer.media[3].bandwidth=[{type:C,limit:er?1e3*c:c}]);let y={type:"offer",sdp:vy(d)};return this.updateSDP({localDescription:y})}setScaleResolutionDownBy(A,e,o){let a=A.getParameters();(!a.encodings||a.encodings.length===0)&&(a.encodings=[{}]);let c=a.encodings[0].scaleResolutionDownBy;if(Je(c)?e===1:e===c)return;let d="setScaleResolutionDownBy ".concat(o," ").concat(e);return c&&(d+=" prevScale: ".concat(c)),this._log.warn(d),a.encodings[0].scaleResolutionDownBy=e,A.setParameters(a)}setDegradationPreference(A,e,o){if(IE&&id<83||eg&&hk(kI,"12.1")||er&&L0<138)return;let a=A.getParameters(),c="balanced";if(e==="motion"?c="maintain-framerate":e==="detail"&&(c="maintain-resolution"),a.degradationPreference===c)return;let d="setDegradationPreference ".concat(o," ").concat(c);return this._log.info(d),a.degradationPreference=c,A.setParameters(a).catch(C=>this._log.warn("".concat(d," failed: ").concat(C)))}updateSDP(){let{localDescription:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let e=vy(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>KA(this,null,function*(){var c,d;try{!A&&this._peerConnection&&(this._log.info("creating offer"),A=yield this._peerConnection.createOffer()),A&&(yield this.setOffer(A)),yield this.setAnswer({type:"answer",sdp:e}),this._updateSDPPromise=null,o()}catch(C){this._log.error(C),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((c=this._peerConnection.localDescription)==null?void 0:c.sdp),` + }`}),Y(this,"yTextureRef"),Y(this,"uTextureRef"),Y(this,"vTextureRef"),Y(this,"Y"),Y(this,"U"),Y(this,"V"),this.useProgram();let e=this.context.ctx;e.pixelStorei(e.PACK_ALIGNMENT,1),e.pixelStorei(e.UNPACK_ALIGNMENT,1),this.setTexBuffer([0,1,1,1,0,0,1,0]),this.yTextureRef=this._initTexture("ySampler",0),this.uTextureRef=this._initTexture("uSampler",1),this.vTextureRef=this._initTexture("vSampler",2),this._canvas=A._canvas}_initTexture(A,e){let o=this.context.ctx,a=o.createTexture();return o.bindTexture(o.TEXTURE_2D,a),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MAG_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_MIN_FILTER,o.LINEAR),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.bindTexture(o.TEXTURE_2D,null),o.uniform1i(o.getUniformLocation(this.program,A),e),a}render(A){let e=this.context.ctx,o=this.width,a=this.height;return this.useProgram(),e.viewport(0,0,o,a),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.yTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.LUMINANCE,e.UNSIGNED_BYTE,this.Y),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,this.uTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,a/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.U),e.activeTexture(e.TEXTURE2),e.bindTexture(e.TEXTURE_2D,this.vTextureRef),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o/2,a/2,e.LUMINANCE,e.UNSIGNED_BYTE,this.V),this.draw(),!0}resize(A,e){super.resize(A,e);let o=this.context.ctx;o.activeTexture(o.TEXTURE0),o.bindTexture(o.TEXTURE_2D,this.yTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A,e,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE1),o.bindTexture(o.TEXTURE_2D,this.uTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null),o.activeTexture(o.TEXTURE2),o.bindTexture(o.TEXTURE_2D,this.vTextureRef),o.texImage2D(o.TEXTURE_2D,0,o.LUMINANCE,A/2,e/2,0,o.LUMINANCE,o.UNSIGNED_BYTE,null)}},g8=(A,e)=>{switch(A){case"webCodecs":return e==="videoFrame"?514705:514706;case"wasm":return e==="webgl"?514707:e==="videoFrame"?514708:514709}throw new Error("decoder type not supported")},AsA=0,esA=class{constructor(A){Y(this,"id",AsA++),Y(this,"trackDoneOB"),Y(this,"startOB"),Y(this,"stopOB"),Y(this,"decoder"),Y(this,"videoContext"),Y(this,"gop",0),Y(this,"gop_helper",0),Y(this,"waitFirstKeyFrame",!0),Y(this,"startTimestamp",0),Y(this,"startTime",0),Y(this,"startPerformanceTime",0),Y(this,"inputFrameCount",0),Y(this,"decodedFrameCount",0),Y(this,"decodeFrameCount",0),Y(this,"downgradeLevel",0),Y(this,"lastDowngradeTime",0),Y(this,"lastFrameDiff",0),Y(this,"lastDecodeFrameTimestamp",0),Y(this,"config"),Y(this,"gop_before_configure",[]),Y(this,"videoElement"),Y(this,"type","wasm"),Y(this,"goodType"),Y(this,"renderer","2d"),Y(this,"wasmOption"),Y(this,"createDecoder"),Y(this,"_decodeSink"),Y(this,"isReported",!1),Y(this,"track"),Y(this,"stateChangeOB"),Y(this,"failedReason");let{track:e,createDecoder:o}=A;if(this.stateChangeOB=hQ(),this.track=e,this.createDecoder=o,this.wasmOption={yuvMode:A.renderer==="webgl",wasmPath:A.wasmPath,workerMode:A.workerMode,canvas:A.canvas},this.config=A.config,this.videoElement=A.videoElement,this.renderer=A.renderer,this.trackDoneOB=la(e.availableState,Zs.OFF),this.stopOB=hQ(),A.type==="auto"){switch(A.fallback){case"wasm":this.type="wasm",this.renderer="webgl";break;case"wasm_2d":this.type="wasm",this.renderer="2d";break;case"wasm_video":this.type="wasm",this.renderer="videoFrame";break;default:this.type="webCodecs"}this.wasmOption.yuvMode=this.renderer==="webgl"}else this.type=A.type;this.changeRenderer(this.renderer),ma(this.stateChangeOB,j5((a,l)=>(a!==l&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:a,state:l}),l),"INITIALIZED"),dE(this.stopOB),Bl()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=ma(this.pipe(this.track),dE(this.stopOB),nL());ma(e,Bl(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),si.addFailedEvent({key:g8(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),si.addFailedEvent({key:514704});else{if(this.goodType)return void this.start(A);switch(this.type){case"webCodecs":this.type="wasm",this.changeRenderer("webgl");break;case"wasm":this.renderer==="webgl"&&this.changeRenderer("videoFrame")}this.start(A+1)}},()=>{this.track.log.warn("".concat(this.id," decoderOB completed")),si.addSuccessEvent({key:g8(this.type,this.renderer)}),si.addSuccessEvent({key:514704})})),ma(e,E_(1),Bl(()=>{this.track.player.handlePlaying("canvas"),this.goodType=this.type,this.stateChangeOB.next("STARTED")}))}mock(A){this._decodeSink?this._decodeSink.error(A):this.start()}close(A){this.stopOB.next(A)}changeRenderer(A){this.renderer=A,this.renderer==="videoFrame"&&!TM()&&(this.renderer="2d"),this.wasmOption.yuvMode=this.renderer==="webgl"}decode(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var o,a;if(this.failedReason)return;this.inputFrameCount++;let l=new Uint8Array(A.data);if((d=l)[0]!==0||d[1]!==0||d[2]!==0||d[3]!==1||l.length<5)return this.stateChangeOB.next("FAILED"),this.close("not h26x frame ".concat(l.subarray(0,5))),A;var d;let h=!1;switch(31&l[4]){case 5:case 7:h=!0}if(((o=this.decoder)==null?void 0:o.state)!=="configured")return this.track.log.debug("not configured ".concat(this.inputFrameCount)),h&&(this.gop_before_configure=[]),this.gop_before_configure.push({data:A.data,timestamp:A.timestamp,type:A.type}),A;this.gop_before_configure.length>0&&!e&&(this.gop_before_configure.forEach(S=>this.decode(S,!0)),this.gop_before_configure=[]);let{timestamp:y}=A;if(h?(this.gop=this.gop_helper,this.gop_helper=0):this.gop_helper++,this.decoder){if(this.waitFirstKeyFrame){if(!h)return void this.track.log.debug("wait first key frame ".concat(this.inputFrameCount," ").concat(l.subarray(0,5).join(" ")));this.waitFirstKeyFrame=!1,this.startTimestamp=y,this.startTime=Date.now(),this.startPerformanceTime=ko()}switch(this.downgradeLevel){case 0:case 1:break;case 2:if(this.gop_helper>this.gop>>1)return;break;case 3:if(this.gop_helper>0)return;break;default:return}return(this.decodeFrameCount<10||this.decodeFrameCount%500==0)&&this.track.log.debug("decode ".concat(this.decodeFrameCount," gop: ").concat(this.gop," ").concat(y," ").concat((a=A.getMetadata)==null?void 0:a.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=y,void this.decoder.decode({data:A.data,type:A.type,timestamp:this.lastDecodeFrameTimestamp})}return A}checkDowngradeByFrameDiff(){let A=this.downgradeLevel,e=this.decodeFrameCount-this.decodedFrameCount;e>this.lastFrameDiff?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):e<=this.lastFrameDiff&&this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==A&&this.track.log.debug("downgrade level ".concat(A," to ").concat(this.downgradeLevel," ").concat(this.decodeFrameCount," frameDiff: ").concat(e,", lastFrameDiff: ").concat(this.lastFrameDiff)),this.lastFrameDiff=e,this.lastDowngradeTime=Date.now()}checkDowngradeByTimestampDiff(A){let e=this.downgradeLevel;this.lastDecodeFrameTimestamp-A>9e4?(this.downgradeLevel++,this.downgradeLevel>4&&(this.downgradeLevel=4)):this.downgradeLevel>0&&this.downgradeLevel--,this.downgradeLevel!==e&&this.track.log.debug("downgrade level ".concat(e," to ").concat(this.downgradeLevel))}pipe(A){return e=>WA(this,null,function*(){this._decodeSink=e;let o,a=A.mediaTrack;e.defer(()=>{var h;a&&(A.player.setCanvas(),A.setInputMediaStreamTrack(a)),o?.close(),(h=this.videoContext)==null||h.destroy(),delete this._decodeSink});let{renderer:l,type:d}=this;A.log.info("decoder type: ".concat(this.type," renderer: ").concat(this.renderer));try{switch(d){case"wasm":o=this.createDecoder(d,this.wasmOption);break;case"webCodecs":o=this.createDecoder(d);break;default:throw new Error("not supported yet")}let h=0;if(o.on("videoFrame",y=>{this.decodedFrameCount++,h++,(h<=10||h%500==0)&&A.log.debug("frame ".concat(h," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(y.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(y.timestamp)),e.next(y)}),o.on("error",y=>{A.log.error(y),e.error(d==="webCodecs"?4:8)}),yield o.initialize(this.videoElement),!this._decodeSink)return;if(o.configure(this.config),d==="wasm"&&l==="webgl"){this.videoContext=new qC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(qC.UNAVAILABLE,S=>{A.log.error(S),e.error(7)});let y=new $oA(this.videoContext);o.on("videoCodecInfo",S=>y.resize(S.width,S.height)),o.on("videoFrame",S=>{({y:y.Y,u:y.U,v:y.V}=S),this.downgradeLevel===1?this.decodedFrameCount%2==0&&y.render(this.decodedFrameCount):y.render(this.decodedFrameCount)}),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}else if(l==="videoFrame"){A.player.setCanvas();let y=new MediaStreamTrackGenerator({kind:"video"}),S=y.writable.getWriter();A.setInputMediaStreamTrack(y),o.on("videoFrame",k=>S.write(k))}else{this.videoContext=new QQ({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let y=this.videoContext.createVideoImageSource();o.on("videoFrame",k=>{try{y.image=k,y.update()}catch(V){delete this.goodType,A.log.error(V),e.error(11)}});let S=new rj(this.videoContext,{name:"remotePlayer",logger:A.log});y.connect(S),A.source=y,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(h){A.log.error(h),e.error(d==="webCodecs"?2:6)}})}},c8=Promise.resolve(),l8=class extends zoA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"videoContext"),Y(this,"_glVideoContext"),Y(this,"_2dVideoContext"),Y(this,"destination"),Y(this,"smallVideoContext"),Y(this,"smallDestination"),Y(this,"smallTrackSource"),Y(this,"smallImageSource"),Y(this,"_isMirror",!1),Y(this,"_rotation",0),Y(this,"cameraTrack"),Y(this,"cameraNode"),Y(this,"transformNode"),Y(this,"mixNode"),Y(this,"screenTrack"),Y(this,"screenNode"),Y(this,"selfModel",!1),Y(this,"blurRadius",3),Y(this,"arTrack"),Y(this,"_enableFaceCentering",!1),Y(this,"_enableEffectOptimization",!1),Y(this,"onAbort"),Y(this,"_color"),Y(this,"Wasm"),Y(this,"waterMarkNode"),Y(this,"_waterMarkOption"),Y(this,"watermarkImageList",[]),Y(this,"_beautyParams"),Y(this,"isUsingArTrack",!1),Y(this,"mixTrack"),Y(this,"_isMixScreen",!1),Y(this,"_virtualBackground"),Y(this,"_virtualBackgroundAbortCallback"),Y(this,"virtualBackgroundInstance"),Y(this,"_bgAssetPath"),Y(this,"log"),Y(this,"_mat4"),Y(this,"_postProcessing"),Y(this,"_checkId",0),Y(this,"_use2d",!1),Y(this,"_autoSwitchRenderMode",!0),Y(this,"encodePipeline",[]),Y(this,"decodePipeline",[]),Y(this,"updated",c8),Y(this,"_updateFlag",!1),this.log=pA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new QQ({frameRate:15,logger:this.log,name:"s"}),this.enablePrintDetail()}get smallMode(){var A;return((A=this.room)==null?void 0:A.smallMode)||"canvas"}get _hasVirtualBg(){return!!this._virtualBackground}get _hasWaterMark(){return this.watermarkImageList.length>0}get _isRotate(){return this._rotation!==0}get _isTransform(){return this._isMirror||this._isRotate}get renderMode(){return this._autoSwitchRenderMode?"auto":this._use2d?"2d":"webgl"}set renderMode(A){if(this._autoSwitchRenderMode=A==="auto",this._autoSwitchRenderMode)return;let e=A==="2d";this._use2d!==e&&(this._use2d=e,this.clear(),this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.update())}get cameraResolution(){var A;let{width:e,height:o}=((A=this.cameraTrack)==null?void 0:A.settings)||{};return tQ(this._rotation)?{width:o,height:e}:{width:e,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new QQ({frameRate:15,logger:this.log,name:"m"}),this._2dVideoContext.create({alpha:this._hasWaterMark||this._hasVirtualBg}),this._2dVideoContext}getGlVideoContext(){if(this._glVideoContext){if(this._glVideoContext.available)return this._glVideoContext}else this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(T2<=22),this._glVideoContext.on(qC.UNAVAILABLE,A=>{var e;this.emit("error",A),this.log.warn("video context unavailable",A),(e=this._virtualBackgroundAbortCallback)==null||e.call(this,A),this.update().catch(o=>{this.log.error(o)})})}catch(A){this.emit("error",A)}}initVirtualBackground(A,e,o){this.onAbort=A,this._mat4=e,this._postProcessing=o}enablePrintDetail(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;this._checkId=Gr.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}destroy(){var A,e;(A=this._2dVideoContext)==null||A.destroy(),(e=this._glVideoContext)==null||e.destroy(),this.smallVideoContext.destroy(),Gr.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(xp||this._isMixScreen||this._isTransform||this._hasWaterMark||this._hasVirtualBg||this._beautyParams)&&this.checkOrCreateVideoContext()}sendCreateResult(){let A=arguments.length>1?arguments[1]:void 0,e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"videoCtxGl")==="videoCtxGl"?512700:512701;A?si.addFailedEvent({key:e,error:A}):si.addSuccessEvent({key:e})}checkOrCreateVideoContext(){let A=this._use2d;if(this._autoSwitchRenderMode&&(this._use2d=!this._hasVirtualBg),this.videoContext)if(this.videoContext.available){let e=!this.videoContext.hasAlpha&&this.needAlpha;if(this._autoSwitchRenderMode&&A===this._hasVirtualBg)this.clear();else{if(!e||!this._use2d)return!0;this.clear()}}else{if(this._glVideoContext=new qC({frameRate:15,logger:this.log,name:"m"}),this.initializeGlVideoContext(),this._glVideoContext.available)return this.videoContext=this._glVideoContext,this.videoContext.available;this.log.warn("webgl is still not available"),this.clear(),this._use2d=!0}return this.videoContext=this._use2d?this.get2dVideoContext():this.getGlVideoContext(),this.videoContext.available}get smallTrack(){var A;return(A=this.smallDestination)==null?void 0:A.videoTrack}get hasSmall(){return!!this.smallTrack}get initialTrack(){var A;return(A=this.cameraTrack)==null?void 0:A.mediaTrack}setSmallVideo(A,e){if(this.smallMode!=="api")if(A){if(!this.smallVideoContext.available){if(this.smallVideoContext.create({alpha:!1}),!this.smallVideoContext.available)return;this.smallDestination=new viA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(qC.UNAVAILABLE,o=>{this.log.warn("small video context lost",o)})}if(this.smallVideoContext.frameRate=A.frameRate,this.smallDestination.resolution=A,e)this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource),this.smallImageSource?this.smallImageSource.image=e:(this.smallImageSource=this.smallVideoContext.createVideoImageSource(e),this.smallImageSource.resize(e.width,e.height),this.smallImageSource.connect(this.smallDestination));else if(this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource)this.smallTrackSource.replaceTrack(this.initialTrack);else{this.smallTrackSource=this.smallVideoContext.createVideoTrackSource(this.initialTrack,"smallTrackSource");let{width:o,height:a}=this.cameraTrack.settings;this.smallTrackSource.resize(o,a),this.smallTrackSource.connect(this.smallDestination)}}else this.smallVideoContext.available&&(this.smallVideoContext.destroy(),delete this.smallDestination,delete this.smallTrackSource,delete this.smallImageSource)}_setMainOutput(A){var e,o;try{let a=this.cameraTrack,{small:l,player:d}=a;xp&&d.setCanvas(A);let h=A&&((e=this.destination)==null?void 0:e.videoTrack)||this.initialTrack;return this.isUsingArTrack&&this.arTrack&&(this.emit("output-track-changed"),h=this.arTrack),this.log.info("set main output ".concat(h?h.label:"no output track")),this.setSmallVideo(l,A),F.emit(nA.LOCAL_VIDEO_TRACK_PREPROCESSED,{mediaTrack:h,profile:(o=this.cameraTrack)==null?void 0:o.profile,room:this.room}),a.setOutputMediaStreamTrack(h)}catch(a){this.log.error("set main output failed",a)}}update(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return WA(this,null,function*(){var e;if(!this.cameraTrack||!this.initialTrack)return;if(!this.active)return this.cameraNode&&this.clear(),this._setMainOutput();let{settings:o,profile:a}=this.cameraTrack;if(this._use2d||!this._virtualBackground&&!this._beautyParams)this.destination||(this.destination=this.videoContext.createVideoTrackDestination({name:"mainDestination2d",logger:this.log}),this.destination.on(AC.RENDER,l=>{var d;(d=this.cameraTrack)==null||d.emit("render",l)})),Zd===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof d_?(this.cameraNode.close(),delete this.cameraNode):this.cameraNode.image=this.initialTrack.canvas),this.cameraNode||(this.cameraNode=this.videoContext.createVideoImageSource(this.initialTrack.canvas,{name:"cameraCanvasSource",logger:this.log}))):(this.cameraNode&&(this.cameraNode instanceof d_?this.cameraNode.replaceTrack(this.initialTrack):(this.cameraNode.close(),delete this.cameraNode)),this.cameraNode||(this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraTrackSource"))):this.cameraNode?this.cameraNode.replaceTrack(this.initialTrack):this.cameraNode=this.videoContext.createVideoTrackSource(this.initialTrack,"cameraNodeSource"),this.cameraNode.resize(o.width,o.height);else if(A&&this.cameraNode&&this.destination)this.cameraNode.replaceTrack(this.initialTrack);else{this.cameraNode&&this.cameraNode.close(),this.destination?this.destination.disableCheckMute():(this.destination=new MiA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(AC.RENDER,y=>{var S;(S=this.cameraTrack)==null||S.emit("render",y)}));let{width:l,height:d}=this.cameraResolution,h=yield this.getWatermarkImage(l,d);this._waterMarkOption={x:0,y:0,width:h.width,height:h.height,image:h},this.cameraNode=new XoA(this.videoContext,{input:this.initialTrack,width:l,height:d,mirror:this._isMirror,rotation:this._rotation,bg:this._virtualBackground,selfModel:this.selfModel,waterMark:this._waterMarkOption,beautyParams:this._beautyParams,useTflite:!0,blurRadius:this.blurRadius,assetPath:this._bgAssetPath,Wasm:this.Wasm,enableFaceCentering:this._enableFaceCentering,enableEffectOptimization:this._enableEffectOptimization,onAbort:this.onAbort,mat4:this._mat4,postProcessing:this._postProcessing,color:this._color}),this.cameraNode.connect(this.destination),this.destination.enableCheckMute(),yield this.cameraNode.predictReady}if(this.videoContext.frameRate=a.frameRate,this._use2d){let l=this.cameraNode;if(l.disconnect(),this._isTransform&&(this.transformNode?(this.transformNode.mirror=this._isMirror,this.transformNode.rotation=this._rotation):this.transformNode=new Ry(this.videoContext,this.log,this._isMirror,this._rotation),l=l.connect(this.transformNode),l.disconnect(),this.log.info("start mirror ".concat(this._isMirror," rotate ").concat(this.rotation))),this.mixNode&&this.mixNode.close(),delete this.mixNode,this._isMixScreen||this._hasWaterMark){if(this.mixNode=new rz(this.videoContext,this.log),l.connect(this.mixNode,{zIndex:1}),this._hasWaterMark&&!this.waterMarkNode&&this._waterMarkOption)this.waterMarkNode=this.videoContext.createVideoImageSource(this._waterMarkOption.image,{autoResize:!1,logger:this.log}),this.waterMarkNode.resize(this._waterMarkOption.width,this._waterMarkOption.height),this.waterMarkNode.x=this._waterMarkOption.x,this.waterMarkNode.y=this._waterMarkOption.y;else if(this.waterMarkNode){let{width:d,height:h}=this.cameraResolution;this.waterMarkNode.image=yield this.getWatermarkImage(d,h),d&&h&&this.waterMarkNode.resize(d,h)}(e=this.waterMarkNode)==null||e.connect(this.mixNode,{zIndex:2}),this._isMixScreen&&this.screenTrack&&(this.screenNode||(this.screenNode=this.videoContext.createVideoTrackSource(this.screenTrack.mediaTrack,"screenNodeSource"),this.screenNode.resize(this.screenTrack.settings.width,this.screenTrack.settings.height)),this.screenNode.shouldUpdate=!1,this.screenNode.connect(this.mixNode,{zIndex:0})),l=this.mixNode,this.log.info("start mix","".concat(this.mixNode.width,"x").concat(this.mixNode.height))}l.connect(this.destination)}return this.log.info("update ".concat(this._use2d?"2d":"webgl")),this._setMainOutput(this.videoContext.canvas)})}clearLastFrame(){var A;this.destination&&((A=this.destination.ctx2d)==null||A.clearRect(0,0,this.destination.width,this.destination.height))}changeInput(A){var e,o,a,l,d;if(A instanceof WM)return this.log.info("change screen input",(e=A.mediaTrack)==null?void 0:e.label),this.setScreenTrack(A);if(A instanceof BQ)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof CL){this.log.info("change remote input",(a=A.mediaTrack)==null?void 0:a.label);let h=A.mediaTrack;return A.setOutputMediaStreamTrack(h)}if(A instanceof gj)return this.log.info("change mix input",(l=A.outMediaTrack)==null?void 0:l.label),this.setMixTrack(A);this.log.warn("change unknown input",(d=A.mediaTrack)==null?void 0:d.label)}removeInput(A){var e;A instanceof WM?((e=this.screenNode)==null||e.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof BQ?this._isMixScreen?(delete this.cameraNode,this.cameraTrack._inputTrack=null,this.update()):(this.clear(),delete this.cameraTrack,this.smallImageSource&&(this.smallImageSource.close(),delete this.smallImageSource),this.smallTrackSource&&(this.smallTrackSource.close(),delete this.smallTrackSource)):A instanceof CL?A.source&&A.source.context.destroy():A instanceof gj&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return WA(this,null,function*(){return this.screenTrack=A,this._isMixScreen&&(this.screenNode?this.screenNode.replaceTrack(A.mediaTrack):yield this.update()),A.setOutputMediaStreamTrack(A.mediaTrack)})}getWatermarkImage(A,e){return WA(this,null,function*(){let o=document.createElement("canvas");e&&A&&(o.height=e,o.width=A);let a=o.getContext("2d");if(!a)throw new gi({code:Ct.NOT_SUPPORTED,message:"Make image failed because of canvas context is null"});return this.watermarkImageList.sort((l,d)=>l.zIndex-d.zIndex),this.watermarkImageList.forEach(l=>{let{image:d,x:h,y,width:S,height:k,fillVideo:V}=l,J=V&&A||S,cA=V&&e||k,CA=V?0:h,MA=V?0:y;a.drawImage(d,CA,MA,J,cA)}),cM(o.toDataURL())})}pushWaterMarkImageList(A){let{type:e}=A;this.watermarkImageList.some(o=>o.imageUrl===A.imageUrl&&o.height===A.height&&o.width===A.width&&o.x===A.x&&o.y===A.y&&o.type===A.type&&o.zIndex===A.zIndex&&o.fillVideo===A.fillVideo)||((e==="mute"||e==="watermark")&&(this.watermarkImageList=this.watermarkImageList.filter(o=>o.type!==e)),this.watermarkImageList.push(A))}setBeautyParams(A){return WA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return WA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return WA(this,null,function*(){let e;try{e=yield cM(A?.imageElement||A.imageUrl)}catch{throw new gi({code:Ct.INVALID_PARAMETER,message:"load image failed, url: ".concat(A.imageUrl)})}let{x:o=0,y:a=0,width:l=e.width,height:d=e.height,type:h="watermark",zIndex:y=2,fillVideo:S=!1}=A;this.watermarkImageList.some(k=>k.type===h)?(this.watermarkImageList=this.watermarkImageList.filter(k=>k.type!==h),this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:e,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),e=yield this.getWatermarkImage(this.cameraResolution.width,this.cameraResolution.height),this._waterMarkOption={x:0,y:0,width:e.width,height:e.height,image:e},this.waterMarkNode?(this.waterMarkNode.x=0,this.waterMarkNode.y=0,this.waterMarkNode.resize(e.width,e.height),this.waterMarkNode.image=e):this.update()):(this.pushWaterMarkImageList({x:o,y:a,width:l,height:d,image:e,zIndex:y,type:h,imageUrl:A.imageUrl,fillVideo:S}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(k,V)=>k==="imageUrl"?void 0:V))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return WA(this,null,function*(){this.watermarkImageList=this.watermarkImageList.filter(e=>e.type!==A),this.log.info("delete watermark",A,JSON.stringify(this.watermarkImageList,(e,o)=>e==="imageUrl"?void 0:o)),yield this.freshWatermark()})}freshWatermark(){return WA(this,null,function*(){var A;(A=this.waterMarkNode)==null||A.close(),delete this.waterMarkNode,delete this._waterMarkOption;let{width:e,height:o}=this.cameraResolution,a=yield this.getWatermarkImage(e,o);this._waterMarkOption={x:0,y:0,width:a.width,height:a.height,image:a},this.update()})}setVirtualBackground(A){return WA(this,null,function*(){var e,o,a;if(A){if(A.onAbort&&(this._virtualBackgroundAbortCallback=A.onAbort),this._use2d&&!this._autoSwitchRenderMode)return Promise.reject(new Error("not support virtual background in 2d mode"));this._bgAssetPath=A.assetPath,A.type==="image"?this._virtualBackground=yield cM(A.imageUrl):(this.blurRadius=A.blurLevel||this.blurRadius||3,this._virtualBackground=A.type),this._enableFaceCentering=(e=A.enableFaceCentering)!=null?e:this._enableFaceCentering,this._enableEffectOptimization=(o=A.enableEffectOptimization)!=null?o:this._enableEffectOptimization,this._color=(a=A.color)!=null?a:[0,1,0]}else delete this._virtualBackground,delete this._virtualBackgroundAbortCallback;if(this.log.info("".concat(this._virtualBackground?"start":"stop"," virtual background, ").concat(A?.type||"",", ").concat(this.blurRadius||"")),yield this.update(),this._virtualBackground&&!this._glVideoContext.available)throw new gi({code:Ct.INVALID_OPERATION,message:"webgl context create failed, ".concat(this._glVideoContext.error)})})}get mixScreen(){return this._isMixScreen}set mixScreen(A){var e;this._isMixScreen=A,this._isMixScreen||((e=this.screenNode)==null||e.close(),delete this.screenNode),this.update()}set mirror(A){var e;this._isMirror!==A&&(this._isMirror=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get mirror(){return this._isMirror}set rotation(A){var e;this._rotation!==A&&(this._rotation=A,this._isTransform||((e=this.transformNode)==null||e.close(),delete this.transformNode),this.update())}get rotation(){return this._rotation}enableAr(A){this.arTrack=A,this.isUsingArTrack=!0,this.update()}updateAr(){return WA(this,null,function*(){var A;(A=this.cameraTrack)!=null&&A.mediaTrack&&(yield this.virtualBackgroundInstance.ar.updateInputTrack(this.cameraTrack.mediaTrack.clone()))})}disableAr(){var A;this.isUsingArTrack=!1,(A=this.arTrack)==null||A.stop(),this.arTrack=void 0,this.update()}createDecodeContext(A){return new esA(A)}clear(){var A,e;(A=this.videoContext)==null||A.disconnect(),(e=this.destination)==null||e.removeAllListeners(),delete this.destination,delete this.cameraNode,delete this.transformNode,delete this.screenNode,delete this.waterMarkNode}addEncodeProcessor(A){let{processor:e,type:o}=A;var a;this.encodePipeline.includes(e)||(this.encodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}addDecodeProcessor(A){let{processor:e,type:o}=A;var a;this.decodePipeline.includes(e)||(this.decodePipeline[o]=e,(a=this.room)==null||a.enableInsertableStreams())}removeEncodeProcessor(A){let{type:e}=A;this.encodePipeline[e]=void 0}removeDecodeProcessor(A){let{type:e}=A;this.decodePipeline[e]=void 0}};hi([_5(function(A){this.log.error("update failed",A)}),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{A.apply(this,o).then(l,d),setTimeout(d,5e3,new gi({code:Ct.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],l8.prototype,"update");var tsA=0,isA=class extends Zs{constructor(A){super("room"),Y(this,"seq",++tsA),Y(this,"sdkAppId"),Y(this,"userId"),Y(this,"userSig"),Y(this,"privateMapKey"),Y(this,"latencyLevel"),Y(this,"tinyId"),Y(this,"scene"),Y(this,"roomId"),Y(this,"useStringRoomId"),Y(this,"role","anchor"),Y(this,"joinParams",null),Y(this,"localPublishFlag",0),Y(this,"localTracks",new Set),Y(this,"enableAutoPlayDialog",!0),Y(this,"autoReceiveAudio",!0),Y(this,"autoReceiveVideo",!0),Y(this,"proxy_ws"),Y(this,"proxy_wt"),Y(this,"proxy_unified"),Y(this,"checkSystemResult",{result:!0,detail:{isBrowserSupported:!0,isWebRTCSupported:!0,isWebCodecsSupported:!0,isMediaDevicesSupported:!0,isScreenShareSupported:!0,isSmallStreamSupported:!0,isH264EncodeSupported:!0,isVp8EncodeSupported:!0,isH264DecodeSupported:!0,isVp8DecodeSupported:!0,isH265EncodeSupported:!0,isH265DecodeSupported:!0}}),Y(this,"keyPointManager"),Y(this,"audioManager"),Y(this,"videoManager"),Y(this,"callDurationCalculator"),Y(this,"badCaseDetector"),Y(this,"scheduleResult",{domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null}),Y(this,"videoDecodeFallbackType"),Y(this,"smallMode","canvas"),Y(this,"prelinkPromise",null),Y(this,"enableChorus",!1),Y(this,"_isUsingCachedSchedule",!1),Y(this,"_log"),Y(this,"_joinedTimestamp",0),Y(this,"_sdkType"),Y(this,"heartbeatReport"),Y(this,"heartbeatCount",0),Y(this,"quality"),Y(this,"enableSEI"),Y(this,"isDestroyed",!1),this._log=pA.createLogger({parent:A.logger,id:"r".concat(this.seq)}),this.useStringRoomId=!!A.useStringRoomId,Nr(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),Nr(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),Nr(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new qoA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new KoA({room:this}),this.badCaseDetector=new WoA({room:this}),this.audioManager=new GiA(this),this.videoManager=new l8(this)}get videoCodec(){return"h264"}get scriptTransformWorker(){}get isMainStreamPublished(){for(let A of this.localTracks)if(4&A.mediaType)return!0;return!1}get isAuxStreamPublished(){for(let A of this.localTracks)if(2&A.mediaType)return!0;return!1}get hasAuxStream(){for(let A of this.remotePublishedUserMap.values())if(A.muteState.hasAuxiliary)return!0;return this.isAuxStreamPublished}get localMainAudioTrack(){for(let A of this.localTracks)if(1&A.mediaType)return A;return null}get localMainVideoTrack(){for(let A of this.localTracks)if(4&A.mediaType)return A;return null}get localAuxVideoTrack(){for(let A of this.localTracks)if(2&A.mediaType)return A;return null}get publishState(){let A={audio:!1,bigVideo:!1,smallVideo:!1,auxVideo:!1};return this.localTracks.forEach(e=>{if(e.isPublished||e.isPublishing)switch(e.mediaType){case 1:A.audio=!0;break;case 4:A.bigVideo=!0,A.smallVideo=e.hasSmall;break;case 2:A.auxVideo=!0}}),A}get muteState(){var A,e,o;return{audio:!((A=this.localMainAudioTrack)==null||!A.muted),bigVideo:!((e=this.localMainVideoTrack)==null||!e.muted),auxVideo:!((o=this.localAuxVideoTrack)==null||!o.muted)}}getLogger(){return this._log}get isJoining(){return this.state.toString()==="joining"}get isJoined(){return this.state==="joined"}get isLeft(){return this.state==="left"}addTrack(A){return WA(this,null,function*(){return this.publish(A)})}removeTrack(A){return WA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return WA(this,null,function*(){})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAIVoice(A){throw new Error("Method not implemented.")}setProxyServer(A){if(Vn(A))/^wss?:\/\//i.test(A)?this.proxy_ws=A:/^https?:\/\//i.test(A)&&(this.proxy_wt=A);else if(IE(A)){let{websocketProxy:e,webtransportProxy:o,loggerProxy:a,scheduleProxy:l,unifiedProxy:d}=A;this.proxy_ws=e,this.proxy_wt=o,this.proxy_unified=d,d?(Ej([d,d]),qS("https://".concat(d))):(a&&qS(a),l&&Ej(l))}F.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:om.main,sched_back_domain:om.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return WA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(e=>{A[e.userId]=e.remoteAudioTrack.stat}),A})}getTransportStats(){return WA(this,null,function*(){var A;let e={rtt:((A=this.quality)==null?void 0:A.uplinkRTT)||0,downlinksRTT:{}};if(this.quality)for(let o of this.quality.downlinkInfo)e.downlinksRTT[o.userId]=o.rtt;return e})}getRemoteVideoStats(){return WA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"main";return function*(){let o={};return A.remotePublishedUserMap.forEach(a=>{let l=e==="auxiliary"?a.remoteAuxiliaryTrack:a.remoteVideoTrack;o[a.userId]=l.stat}),o}()})}checkDestroy(){if(this.isDestroyed)throw new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(cc.INVALID_DESTROY),new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.INVALID_DESTROY})});this._log.info("destroy room"),this.audioManager.destroy(),this.videoManager.destroy(),this.keyPointManager.destroy(),this.callDurationCalculator.destroy(),this.badCaseDetector.destroy(),this.isDestroyed=!0,F.emit(nA.ROOM_DESTROY,{room:this})}schedule(A,e){return WA(this,null,function*(){var o,a,l,d;let h=ko();try{let{isCached:y,result:S,detailCost:k}=yield Sz({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:qd,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:e,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=y,this._log.info("schedule cache:".concat(+y," ").concat(zd(S,{keysToExclude:["username","credential"]}))),y&&F.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=fi(fi({},this.scheduleResult),S),kn((o=S.config)==null?void 0:o.retryCount)&&u0(S.config.retryCount),Vn((a=S.config)==null?void 0:a.loggerDomain)&&qS(S.config.loggerDomain),this.videoDecodeFallbackType=((l=S.config)==null?void 0:l.videoDecodeFallback)||this.videoDecodeFallbackType,this.smallMode=((d=S.config)==null?void 0:d.smallMode)||this.smallMode,F.emit(nA.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:k}),si.addSuccessEvent({key:521700,cost:ko()-h})}catch(y){throw si.addFailedEvent({key:521700,error:y}),y}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,e,o,a,l,d){return WA(this,null,function*(){return Promise.resolve()})}closePrelink(){return WA(this,null,function*(){return Promise.resolve()})}},osA=gc(jl()),I8=gc(Sb());function u8(A){var e;let o=[];for(let a=0;ad.payload===A.rtp[a].payload)[0];o.push({payload:A.rtp[a].payload,codec:A.rtp[a].codec,fmtp:l?l.config:"",rate:A.rtp[a].rate,rtx:((e=A.rtp[a+1])==null?void 0:e.codec)==="rtx"?A.rtp[a+1].payload:0,rtcpfb:(A?.rtcpFb||[]).filter(d=>d.payload===A.rtp[a].payload).map(d=>{let{type:h,subtype:y}=d;return{id:h,params:y?[y]:[]}})})}return o}var ssA=(A,e,o)=>WA(null,null,function*(){var a;let l=uc(A),d={ice:{ufrag:"",password:""},dtls:{hash:"",fingerprint:"",setup:""},audio:{codecs:[],extensions:[]},video:{codecs:[],decoders:[],extensions:[]},useDataChannel:o};d.ice.ufrag=String(l.media[0].iceUfrag),d.ice.password=l.media[0].icePwd||"",l.fingerprint&&(d.dtls.hash=l.fingerprint.type,d.dtls.fingerprint=l.fingerprint.hash,d.dtls.setup=l.setup||""),l.media[0].fingerprint&&(d.dtls.hash=l.media[0].fingerprint.type,d.dtls.fingerprint=l.media[0].fingerprint.hash),d.dtls.setup=l.media[0].setup||"";let h=l.media[0],y=l.media[1];h.ext&&(d.audio.extensions=h.ext.map(k=>({id:k.value,uri:k.uri}))),y.ext&&(d.video.extensions=y.ext.map(k=>({id:k.value,uri:k.uri})));for(let k of h.rtp){if(k.codec!=="opus")continue;let V=h.fmtp.find(cA=>cA.payload===k.payload);if(!V)continue;let J={codec:k.codec,fmtp:V.config,payload:V.payload,rate:k.rate,channels:k.encoding,rtcpfb:[],rtx:0};(a=h.rtcpFb)==null||a.forEach(cA=>{let{payload:CA,type:MA,subtype:ie}=cA;if(CA===J.payload){let pe={id:MA,params:[]};ie&&pe.params.push(ie),J.rtcpfb.push(pe)}}),d.audio.codecs.push(J);break}let S=["h264","vp8","h265"];return e&&S.shift(),d.video.codecs=[...u8(y)].filter(k=>S.includes(k.codec.toLocaleLowerCase())),d.video.decoders=(yield function(){return WA(this,null,function*(){let k=new RTCPeerConnection;k.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY});let V=yield k.createOffer();if(!V.sdp)return[];let J=u8(uc(V.sdp).media[0]);return k.close(),J})}()).filter(k=>["h264","vp8","h265"].includes(k.codec.toLocaleLowerCase())),d}),E8=(A,e)=>{let o=(A||"").trim(),a=(e||"").trim(),l="profile-level-id",d="".concat(l,"=[0-9a-fA-F]{6}");if(new RegExp(d).test(o)){let y=new RegExp(d,"g");return o.replace(y,"".concat(l,"=").concat(a))}if(!o)return"".concat(l,"=").concat(a);let h=o.endsWith(";")?"":";";return"".concat(o).concat(h).concat(l,"=").concat(a)},nsA=A=>{let{serverAbility:e,clientAbility:o,offerSDP:a,enableCustomMessage:l,profileLevelIdConfig:d}=A,h=uc(a),y={extmapAllowMixed:"extmap-allow-mixed",groups:h.groups,icelite:"ice-lite",media:[],msidSemantic:{semantic:"",token:"WMS"},name:"-",origin:{address:"127.0.0.1",username:"-",sessionId:String(Date.now()),sessionVersion:1,netType:"IN",ipVer:4},timing:{start:0,stop:0},version:0},S={candidates:e.candidates.map(V=>({component:1,foundation:"1",generation:0,ip:V.ip,port:V.port,priority:V.priority,transport:V.foundation,type:V.type})),connection:{version:4,ip:"0.0.0.0"},direction:YA.TRANSCEIVER_DIRECTION_RECVONLY,ext:e.audio.extensions.map(V=>({value:V.id,uri:V.uri})),fingerprint:{type:e.dtls.hash,hash:e.dtls.fingerprint},fmtp:[{payload:e.audio.codecs[0].payload,config:e.audio.codecs[0].fmtp}],icePwd:e.ice.password,iceUfrag:e.ice.ufrag,mid:"0",payloads:String(e.audio.codecs[0].payload),port:h.media[0].port,protocol:h.media[0].protocol,type:YA.AUDIO,setup:e.dtls.setup,rtcpFb:e.audio.codecs[0].rtcpfb.map(V=>({payload:e.audio.codecs[0].payload,type:V.id,subtype:V.params[0]})),rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[{payload:e.audio.codecs[0].payload,codec:e.audio.codecs[0].codec,rate:e.audio.codecs[0].rate,encoding:e.audio.codecs[0].channels}]};y.media.push(S);let k=[d?.big,d?.small,d?.aux];return[1,2,3].forEach((V,J)=>{y.media.push(d8({mid:V,serverAbility:e,clientAbility:o,parsedOffer:h,profileLevelId:k[J]}))}),l&&y.media.push(h.media.find(V=>V.mid==="dc")),_y(y)},d8=A=>{let{mid:e,serverAbility:o,clientAbility:a,parsedOffer:l,isDownlink:d=!1,profileLevelId:h}=A,y={candidates:o.candidates.map(S=>({component:1,foundation:"1",generation:0,ip:S.ip,port:S.port,priority:S.priority,transport:S.foundation,type:S.type})),connection:{version:4,ip:"0.0.0.0"},direction:YA.TRANSCEIVER_DIRECTION_RECVONLY,ext:o.video.extensions.map(S=>({value:S.id,uri:S.uri})),fingerprint:{type:o.dtls.hash,hash:o.dtls.fingerprint},fmtp:[],icePwd:o.ice.password,iceUfrag:o.ice.ufrag,mid:String(e),payloads:"",port:l.media[0].port,protocol:l.media[0].protocol,type:YA.VIDEO,setup:o.dtls.setup,rtcpFb:[],rtcpMux:"rtcp-mux",rtcpRsize:"rtcp-rsize",rtp:[]};if(d){let S=o.video.decoders;(!S||S.length===0)&&(S=o.video.codecs),(!S||S.length===0)&&(S=a.video.decoders),S.forEach(k=>{f_(y,k)})}else{let S;S=o.useH265?o.video.codecs.findIndex(V=>V.codec.toLowerCase()==="h265"):o.video.codecs.findIndex(V=>V.codec.toLowerCase()===(o.useVp8?"vp8":"h264"));let k=o.video.codecs[S]||a.video.codecs[0];f_(y,k)}if(!d&&h){let S=y.fmtp,k=y.rtp.find(V=>{var J;return((J=V.codec)==null?void 0:J.toLowerCase())==="h264"});if(k){let V=S.find(J=>String(J.payload)===String(k.payload));V&&(V.config=E8(V.config,h))}}return y},f_=(A,e)=>{A.payloads="".concat(A.payloads," ").concat(e.payload).trim(),A.fmtp.push({payload:e.payload,config:e.fmtp}),A.rtcpFb=[...A.rtcpFb||[],...e.rtcpfb.map(o=>({payload:e.payload,type:o.id,subtype:o.params[0]}))],A.rtp.push({payload:e.payload,codec:e.codec.toUpperCase(),rate:e.rate}),e.rtx&&(A.payloads="".concat(A.payloads," ").concat(e.rtx),A.fmtp.push({payload:e.rtx,config:"apt=".concat(e.payload)}),A.rtp.push({payload:e.rtx,codec:"rtx",rate:e.rate}))},rsA=(A,e,o)=>{let a=I8.default.parse(A);return a.media.forEach((l,d)=>{var h;if((l.type===YA.AUDIO||l.type===YA.VIDEO)&&(function(y){if(!y.rtcpFb)return;let S=[];y.rtcpFb.forEach((k,V)=>{var J;S.push(k),y.rtcpFb&&((J=y.rtcpFb[V+1])==null?void 0:J.payload)!==k.payload&&k.type!=="rrtr"&&S.push({payload:k.payload,type:"rrtr"})}),y.rtcpFb=S}(l),function(y){y.type===YA.VIDEO&&y.fmtp&&y.fmtp.forEach(S=>{S.config.includes("apt")||(S.config+=";sps-pps-idr-in-keyframe=1")})}(l),function(y){y.type===YA.AUDIO&&y.fmtp&&y.fmtp.forEach(S=>{S.config+=";sprop-stereo=1;stereo=1"})}(l),function(y){let S=new Set(["urn:ietf:params:rtp-hdrext:sdes:mid","urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id","urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id"]);y.ext&&(y.ext=y.ext.filter(k=>!S.has(k.uri)))}(l),l.type===YA.VIDEO)){if(d<4)l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[],e.video.codecs.forEach(y=>f_(l,y));else if(o){l.payloads="",l.fmtp=[],l.rtp=[],l.rtcpFb=[];let y=o.video.decoders;(!y||y.length===0)&&(y=o.video.codecs),(!y||y.length===0)&&(y=e.video.decoders),y.forEach(S=>f_(l,S))}}(h=l.payloads)!=null&&h.includes("datachannel")&&a.groups&&l.mid&&(a.groups[0].mids=a.groups[0].mids.replace(l.mid,"dc"),l.mid="dc")}),I8.default.write(a)};function Uj(A){var e,o;let a=/profile-level-id=([0-9a-fA-F]{6})/.exec(A);return(o=(e=a?.[1])==null?void 0:e.toLowerCase())!=null?o:null}function Fj(A){let e=A.toLowerCase();if(!/^[0-9a-f]{6}$/.test(e))return"unknown";let o=parseInt(e.slice(0,2),16);return o===66?"baseline":o===77?"main":o===100?"high":"unknown"}function C8(A,e){if(!e)return"";let o=A.trim().toLowerCase().replace(/_/g,"-");if(!o)return"";if(/^[0-9a-f]{6}$/.test(o))return o;if(o!=="baseline"&&o!=="main"&&o!=="high")return"";for(let a of e.video.codecs){let l=Uj(a.fmtp);if(l&&Fj(l)===o)return l}return""}var asA=gc(jl()),h8=class extends asA.EventEmitter{constructor(A){super(),this.room=A,Y(this,"mainFpsHealth",1),Y(this,"mainBitrateHealth",1),Y(this,"badMainBitrateHealthCount",0),Y(this,"lastEmitBadHealthTime",0),Y(this,"log"),!Ha&&uE&&F.on("262",this.onVideoCodecChanged,this),this.log=A.getLogger().createChild({id:"h-d"})}onVideoCodecChanged(A){let{remoteUserId:e,streamType:o,isHWCodec:a,codec:l}=A;if(!e&&o!==7&&l==="h264"){if(!a)return void this.room.off("heartbeat-report",this.onHeartbeatReport,this);this.room.listeners("heartbeat-report").includes(this.onHeartbeatReport)||this.room.on("heartbeat-report",this.onHeartbeatReport,this)}}onHeartbeatReport(A){Date.now()-this.lastEmitBadHealthTime<3e4||(A.msg_up_stream_info.msg_video_status.forEach(e=>{if(e.uint32_video_enc_fps&&e.uint32_video_capture_fps){let o=e.uint32_video_enc_fps/e.uint32_video_capture_fps;e.uint32_video_stream_type===2&&(this.mainFpsHealth=o)}if(e.uint32_video_codec_bitrate&&e.uint32_video_stream_type===2){let{localMainVideoTrack:o}=this.room;o&&(this.mainBitrateHealth=e.uint32_video_codec_bitrate/1e3/o.profile.bitrate)}}),this.log.debug("mainBitrateHealth: ".concat(this.mainBitrateHealth," mainFpsHealth: ").concat(this.mainFpsHealth)),this.mainBitrateHealth>.5&&(this.badMainBitrateHealthCount=0),this.mainFpsHealth>.9&&this.mainBitrateHealth<.5&&(this.badMainBitrateHealthCount++,this.badMainBitrateHealthCount>3&&(this.badMainBitrateHealthCount=0,this.lastEmitBadHealthTime=Date.now(),this.log.warn("bad main bitrate health: ".concat(this.mainBitrateHealth)),this.emit("1",{isAux:!1}))))}destroy(){F.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Y(h8,"EVENT_BAD_HEALTH","bad_health");var gsA=h8,y_=(A=>(A.TRACK="track",A.DATA_CHANNEL_MESSAGE="data_channel_msg",A[A.CONNECTION_STATE_CHANGED="connection-state-changed"]="CONNECTION_STATE_CHANGED",A[A.FIREWALL_RESTRICTION="firewall-restriction"]="FIREWALL_RESTRICTION",A.RECONNECTED="spc-reconnected",A.RECONNECT_FAILED="spc-reconnect-failed",A.ERROR="error",A.SEI_MESSAGE="sei-message",A.DUMP="dump",A))(y_||{}),csA=1,Ty=class extends osA.default{constructor(A){let{signalChannel:e,room:o,enableDataChannel:a}=A;super(),Y(this,"stat",{iceStartTime:0,iceEndTime:0,dtlsStartTime:0,dtlsEndTime:0,peerConnectionStartTime:0,peerConnectionEndTime:0}),Y(this,"isDestroyed",!1),Y(this,"currentState","DISCONNECTED"),Y(this,"_room"),Y(this,"_signalChannel"),Y(this,"_peerConnection",null),Y(this,"_datachannel",null),Y(this,"_enableDataChannel"),Y(this,"_log"),Y(this,"_downlinkMIDMap",new Map),Y(this,"_downlinkMIDUserIDMap",new Map),Y(this,"_reconnectionTimer",-1),Y(this,"reconnectionCount",0),Y(this,"clientAbility"),Y(this,"_serverAbility",null),Y(this,"addDownlinkQueue",new Set),Y(this,"removeDownlinkQueue",new Set),Y(this,"_parsedAnswer",null),Y(this,"_updateSDPPromise",null),Y(this,"_waitForPCConnectedPromise"),Y(this,"clearWaitForConnectedPromise"),Y(this,"clearConnectTimeout"),Y(this,"_isSDPLogged",!1),Y(this,"enableInsertableStreams",!1),Y(this,"insertableStreamsAbortMap",new Map),Y(this,"receiverRemoteTrackMap",new WeakMap),Y(this,"scriptTransformWorker"),Y(this,"_isRelayTried",!1),Y(this,"_rttOverCount",0),Y(this,"originOffer",null),Y(this,"autoSubscribedSsrcGroups",new Map),Y(this,"autoSubscribedUserMap",new Map),Y(this,"_h265DecodeFailed",!1),this._room=o,this._enableDataChannel=a,this._signalChannel=e,this._log=pA.createLogger({parent:this._room.getLogger(),id:"spc".concat(csA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(zp?this.enableInsertableStreams=!0:this.initScriptTransformWorker()),this._room.healthDetector.on("1",this.onBadHealth,this)}get isH264EncodeSupported(){let A=this._room.checkSystemResult.detail.isH264EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h264")),A}addAbortController(A,e){var o;(o=this.insertableStreamsAbortMap.get(A))==null||o.abort("destroy"),this.insertableStreamsAbortMap.set(A,e)}get isVP8EncodeSupported(){let A=this._room.checkSystemResult.detail.isVp8EncodeSupported;return this._serverAbility&&(A=A&&this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="vp8")),A}get isH265EncodeSupported(){let A=this._room.checkSystemResult.detail.isH265EncodeSupported;return this._serverAbility&&(A=A&&!!this._serverAbility.video.codecs.find(e=>e.codec.toLowerCase()==="h265")),A}get videoCodec(){var A,e,o;let a=(A=this._parsedAnswer)==null?void 0:A.media[1].rtp.find(l=>["h264","vp8","h265"].includes(l.codec.toLowerCase()));return a?a.codec.toLowerCase():(e=this._serverAbility)!=null&&e.useH265?"h265":(o=this._serverAbility)!=null&&o.useVp8?"vp8":"h264"}get downlinkVideoCodec(){var A,e,o;return(A=this._serverAbility)!=null&&A.useH265&&(e=this._serverAbility)!=null&&e.video.decoders.find(a=>a.codec.toLowerCase()==="h265")&&!this._h265DecodeFailed?"h265":(o=this._serverAbility)!=null&&o.video.decoders.find(a=>a.codec.toLowerCase()==="h264")?"h264":"vp8"}get isUsingH264(){return this.videoCodec==="h264"}get isUsingH265(){return this.videoCodec==="h265"}get isUsingVP8(){return this.videoCodec==="vp8"}get is42001fSupported(){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(A=>A.fmtp.includes("42001f"))}isProfileLevelIdSupported(A){return!!this.clientAbility&&!!this.clientAbility.video.codecs.find(e=>e.fmtp.includes(A))}get uplinkSSRC(){return this._peerConnection&&this._peerConnection.localDescription?(A=>{let e=uc(A),o={audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0};return e.media.forEach((a,l)=>{var d;if(a.ssrcs&&!Ke(a.ssrcs[0].id)){let h=Number(a.ssrcs[0].id),y=Number((d=a.ssrcs.filter(S=>S.attribute==="cname")[1])==null?void 0:d.id);switch(l){case 0:o.audioSsrc=h;break;case 1:o.bigVideoSsrc=h,o.bigVideoRtxSsrc=y;break;case 2:o.smallVideoSsrc=h,o.smallVideoRtxSsrc=y;break;case 3:o.auxVideoSsrc=h,o.auxVideoRtxSsrc=y}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){o_&&(this.scriptTransformWorker=Lz({videoEncodePipeline:this._room.videoManager.encodePipeline,videoDecodePipeline:this._room.videoManager.decodePipeline,audioEncodePipeline:this._room.audioManager.encodePipeline,audioDecodePipeline:this._room.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=A=>{A.data.type==="sei"?this.emit("sei-message",A.data):A.data.type,A.data.type==="dump"&&this.emit("dump",A.data)},this.scriptTransformWorker.onerror=A=>{this._log.error("scriptTransformWorker error: ",A.message)})}get isReconnecting(){return this.currentState==="RECONNECTING"||this._reconnectionTimer>0||this.reconnectionCount>0}get dtlsTransport(){if(!this._peerConnection)return null;let A=this._peerConnection.getSenders();return A.length===0?null:A[0].transport}getPeerConnectionConfig(A){var e;let o={encodedInsertableStreams:this.enableInsertableStreams,offerExtmapAllowMixed:!0,iceServers:A,iceTransportPolicy:this._room.getIceTransportPolicy(),sdpSemantics:this._room.sdpSemantics,bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},a=(e=this._peerConnection)==null?void 0:e.getConfiguration().encodedInsertableStreams;return f2(a)&&(o.encodedInsertableStreams=a),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return WA(this,null,function*(){var e;let o;try{return this._peerConnection=new RTCPeerConnection(this.getPeerConnectionConfig(A)),this._peerConnection.oniceconnectionstatechange=()=>{if(!this._peerConnection)return;let a=this._peerConnection.iceConnectionState;this._log.debug("ice state: ".concat(a)),a==="checking"&&this.stat.iceStartTime===0?this.stat.iceStartTime=Date.now():a==="connected"&&this.stat.iceEndTime===0?(this.stat.iceEndTime=Date.now(),this._signalChannel.clearBakRelayIps(),si.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):a==="failed"&&si.addFailedEvent({key:521711})},this._peerConnection.onsignalingstatechange=()=>{var a;let l=((a=this._peerConnection)==null?void 0:a.signalingState)||"";this._log[l==="closed"?"debug":"info"]("signaling state: ".concat(l))},this._peerConnection.onconnectionstatechange=this.onConnectionStateChange.bind(this),this._peerConnection.ontrack=a=>this.emit("track",a),this._enableDataChannel&&(this._datachannel=this._peerConnection.createDataChannel("".concat(this._room.userId,"dc")),this._datachannel.binaryType="arraybuffer",this._datachannel.onopen=()=>{this._log.info("datachannel open")},this._datachannel.onclose=()=>{this._log.warn("datachannel close")},this._datachannel.onmessage=a=>{let l=new IsA(a.data);this.emit("data_channel_msg",{data:l})},this._datachannel.onerror=a=>{this._log.warn("datachannel error",a)}),this._peerConnection.addTransceiver(YA.AUDIO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield ssA(o.sdp,((e=this._room.scheduleResult.config)==null?void 0:e.remove264FromSDP)||!1,this._enableDataChannel),this.originOffer=o,this.dtlsTransport&&(this.dtlsTransport.onstatechange=()=>{let{dtlsTransport:a}=this;a&&(this._log.debug("dtls state: ".concat(a.state)),a.state==="connecting"&&this.stat.dtlsStartTime===0?this.stat.dtlsStartTime=Date.now():a.state==="connected"&&this.stat.dtlsEndTime===0&&(this.stat.dtlsEndTime=Date.now()))}),si.addSuccessEvent({key:521707}),this.clientAbility}catch(a){throw si.addFailedEvent({key:521707,error:a}),this._log.error("initialize failed ".concat(a,` +offer: `).concat(o?.sdp)),a}})}setIceServers(A){return WA(this,null,function*(){var e;if(this._peerConnection&&A.length!==0)try{if(this._log.info("setIceServers",JSON.stringify(A,(o,a)=>o==="username"||o==="credential"?"hided":a)),this._peerConnection.setConfiguration(this.getPeerConnectionConfig(A)),(e=this._peerConnection)!=null&&e.localDescription||!this.originOffer)return void this._log.warn("setIceServers already has localDescription or no origin Offer");yield this.setOffer(this.originOffer)}catch(o){this._log.warn("setIceServers error ",o)}})}setPriority(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"high";if(this._peerConnection)try{this._peerConnection.getSenders().forEach(e=>{let o=e.getParameters();o.encodings[0]&&(o.encodings[0].priority=A,o.encodings[0].networkPriority=A,e.setParameters(o).catch(a=>{this._log.warn("setPriority error ",a)}))})}catch(e){this._log.warn("setPriority error ",e)}}connect(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return WA(this,null,function*(){var o,a,l;try{if(this.currentState==="CONNECTED")return;((o=this._peerConnection)==null||!o.localDescription)&&this.originOffer&&(yield this.setOffer(this.originOffer));let d=ko(),h=this.getProfileLevelIdConfig(),y={type:"answer",sdp:nsA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:h})};this._serverAbility=A,yield this.setAnswer(y),yield this.waitForPeerConnectionConnected(),this._room.firewallDetector.resetTimeoutCount();let S=((a=this._room.scheduleResult.config)==null?void 0:a.priority)||((l=this._room.joinParams)==null?void 0:l.priority)||new URLSearchParams(location.search).get("priority");S&&this.setPriority(S),e||si.addSuccessEvent({key:521703,cost:ko()-d})}catch(d){let h=d instanceof gi&&d.code===Ct.API_CALL_ABORTED;throw h||this._log.error("connect failed: ".concat(d),A),this.reset(),!h&&!this.isReconnecting&&!this.isDestroyed&&(si.addFailedEvent({key:521703,error:d}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),d}})}reconnect(){return WA(this,null,function*(){if(this._reconnectionTimer===-1){if(!this._signalChannel.isConnected)return this._log.warn("reconnect() wait signal channel is connected"),void this._signalChannel.once(yL,this.reconnect,this);try{this.reconnectionCount+=1,this._log.warn("reconnect() trying [".concat(this.reconnectionCount,"]")),this.reset();let A=this._signalChannel.getBackupRelayIpPair(),e=yield this.initialize(this._room.getIceServers(A!=null&&A.iceServer?[A.iceServer]:[])),o=fi({ability:e},A),a=yield this._signalChannel.sendWaitForResponse({command:ToA,responseCommand:ls.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(a.data.code!==0)throw new gi({code:a.data.code,message:a.data.message});yield this.connect(a.data.data.ability,!0),si.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),F.emit(nA.SPC_RECONNECTED,{room:this._room}),this.emit("spc-reconnected")}catch(A){if(!this.isReconnecting||this.isDestroyed)return;if(A!=null&&A.message.includes("timeout")){let e=Tp(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield OC(e,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),si.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=Jf()&&this._log.warn("SDK has tried reconnect for ".concat(Jf()," times, but all failed, please check your network")),this.stopReconnection(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.emit("error")}}else this._log.warn("reconnect() is reconnecting, ignore current reconnection")})}getPeerConnection(){return this._peerConnection}startReconnection(){return WA(this,null,function*(){this.isReconnecting||(this._log.warn("start reconnect"),this._updateSDPPromise=null,this.emitConnectionStateChangedEvent("RECONNECTING"),yield this.reconnect())})}stopReconnection(){var A;this.isReconnecting&&(this._log.info("stop reconnect"),this.reconnectionCount=0,this.clearReconnectionTimer(),(A=this.clearConnectTimeout)==null||A.call(this),this._signalChannel.off(yL,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===ho.CLOSED&&this.startReconnection()}clearReconnectionTimer(){this._reconnectionTimer!==-1&&(clearTimeout(this._reconnectionTimer),this._reconnectionTimer=-1)}onConnectionStateChange(A){var e;let o=((e=this._peerConnection)==null?void 0:e.iceConnectionState)||"closed",a=this.getDTLSTransportState();this._log.info("connectionState: ".concat(A.target.connectionState," ICE: ").concat(o," DTLS: ").concat(a)),A.target.connectionState===ho.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===ho.FAILED||A.target.connectionState===ho.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===ho.CONNECTED||A.target.connectionState===ho.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),F.emit(nA.SINGLE_CONNECTION_STAT,{room:this._room,stat:{ice:this.stat.iceEndTime-this.stat.iceStartTime,dtls:this.stat.dtlsEndTime-this.stat.dtlsStartTime,peerConnection:this.stat.peerConnectionEndTime-this.stat.peerConnectionStartTime}}),this.logSelectedCandidate(),this.emitConnectionStateChangedEvent("CONNECTED"))}getDTLSTransportState(){if(!this._peerConnection)return zh;let A=null;return UI()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,By()&&this._peerConnection.getReceivers().length!==0&&A?A.state:zh):zh}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(y_.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return WA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[e,o]of A)if(GM(o)){let a=A.get(o.localCandidateId),l=A.get(o.remoteCandidateId);a&&(this._log.info("local candidate: ".concat(a.candidateType," ").concat(a.protocol,":").concat(a.ip||a.address,":").concat(a.port," ").concat(a.networkType||""," ").concat(a.relayProtocol?"relayProtocol:".concat(a.relayProtocol," url: ").concat(a.url):"")),a.networkType&&S0(a.networkType)),l&&this._log.info("remote candidate: ".concat(l.candidateType," ").concat(l.protocol,":").concat(l.ip||l.address,":").concat(l.port));break}})}waitForPeerConnectionConnected(){return this._waitForPCConnectedPromise||(this._waitForPCConnectedPromise=new Promise((A,e)=>{if(this.currentState==="CONNECTED")return A();let o=h=>{h.state==="CONNECTED"&&(clearTimeout(d),l(),A())},a=h=>{let{room:y}=h;y===this._room&&(clearTimeout(d),l(),e(new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.CONNECTION_ABORTED,data:"leave room"})})))},l=()=>{F.off(nA.LEAVE_SUCCESS,a,this),this.off(y_.CONNECTION_STATE_CHANGED,o,this)},d=setTimeout(()=>{l();let h=new gi({code:Ct.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(h)},Fb);this.clearConnectTimeout=()=>{l(),clearTimeout(d),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,e(new gi({code:Ct.API_CALL_TIMEOUT,message:"connection timeout"}))},F.on(nA.LEAVE_SUCCESS,a,this),this.on(y_.CONNECTION_STATE_CHANGED,o,this)}),this._waitForPCConnectedPromise=this._waitForPCConnectedPromise.finally(()=>{this._waitForPCConnectedPromise=null,delete this.clearConnectTimeout})),this._waitForPCConnectedPromise}waitForReconnected(){return this.isReconnecting?new Promise((A,e)=>{this.once("spc-reconnected",A),this.once("error",e)}):Promise.resolve()}addDownlink(A){return WA(this,null,function*(){if(this._log.info("addDownlink(".concat(A.userId,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise),this.updateLocalAndRemoteSDPConfig(A),this.addDownlinkQueue.size===0)try{yield this.updateSDP(),this._log.info("addDownlink(".concat(A.userId,") done"))}catch(e){this._log.error("addDownlink(".concat(A.userId,") failed ").concat(e)),yield this.startReconnection()}})}updateLocalAndRemoteSDPConfig(A){let{ssrc:e,userId:o,tinyId:a,prevMids:l}=A;if(!this._peerConnection)return;this._log.info("updateLocalAndRemoteSDPConfig ".concat(o," ").concat(JSON.stringify(e))),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let d,h,y,S=this._parsedAnswer.media.filter(J=>{var cA;return(cA=J.ssrcs)==null?void 0:cA.find(CA=>{var MA;return(MA=CA.value)==null?void 0:MA.includes(a)})});if(S.length===3)d=S[0],h=S[1],y=S[2];else{let J,cA=this._peerConnection.getTransceivers().slice(4);if(l?.length===3&&l.every(MA=>{var ie;return((ie=cA.find(pe=>Number(pe.mid)===MA))==null?void 0:ie.direction)==="inactive"})?(J=l,this._log.info("reusing previous mids for ".concat(o,": ").concat(J.join(","))),cA.forEach(MA=>{J.includes(Number(MA.mid))&&(MA.direction=YA.TRANSCEIVER_DIRECTION_RECVONLY)})):J=cA.filter(MA=>MA.direction==="inactive").slice(0,3).map(MA=>(MA.direction=YA.TRANSCEIVER_DIRECTION_RECVONLY,Number(MA.mid))),J.length===3)d=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[0])),h=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[1])),y=this._parsedAnswer.media.find(MA=>Number(MA.mid)===Number(J[2]));else if(J.length===0){this._peerConnection.addTransceiver(YA.AUDIO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(YA.VIDEO,{direction:YA.TRANSCEIVER_DIRECTION_RECVONLY}),d=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let MA=d8({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:uc(this._peerConnection.localDescription.sdp),isDownlink:!0});h=JSON.parse(JSON.stringify(MA)),y=JSON.parse(JSON.stringify(MA)),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),h.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(h),y.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(y)}}d.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY;let k="".concat(a,"-").concat(e.audio);d.ssrcs=[{id:e.audio,attribute:"cname",value:"".concat(k)},{id:e.audio,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-audio")}],h.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY,h.ssrcs=[{id:e.video,attribute:"cname",value:"".concat(k)},{id:e.video,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-bigvideo")},{id:e.videoRtx,attribute:"cname",value:"".concat(k)},{id:e.videoRtx,attribute:"msid",value:"".concat(k,"-").concat(YA.MAIN," ").concat(k,"-bigvideo")}],h.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.video," ").concat(e.videoRtx)}],y.direction=YA.TRANSCEIVER_DIRECTION_SENDONLY;let V="".concat(k,"-aux");y.ssrcs=[{id:e.auxiliary,attribute:"cname",value:V},{id:e.auxiliary,attribute:"msid",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)},{id:e.auxiliaryRtx,attribute:"cname",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)},{id:e.auxiliaryRtx,attribute:"msid",value:"".concat(V," ").concat(k,"-aux").concat(YA.VIDEO)}],y.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.auxiliary," ").concat(e.auxiliaryRtx)}],this._parsedAnswer.groups&&(this._parsedAnswer.groups[0].mids=this._parsedAnswer.media.map(J=>J.mid).join(" ")),this._downlinkMIDMap.set(o,[d.mid,h.mid,y.mid]),this._downlinkMIDUserIDMap.set(d.mid,o),this._downlinkMIDUserIDMap.set(h.mid,o),this._downlinkMIDUserIDMap.set(y.mid,o)}removeDownlink(A){return WA(this,null,function*(){if(!this._downlinkMIDMap.has(A)||!this._peerConnection)return;this._log.info("removeDownlink(".concat(A,") trying")),this.isReconnecting&&(yield this.waitForReconnected()),this._updateSDPPromise&&(yield this._updateSDPPromise);let e=this._downlinkMIDMap.get(A),o=!1;return this._peerConnection.getTransceivers().forEach(a=>{e!=null&&e.includes(Number(a.mid))&&(o=!0,a.direction="inactive")}),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp)),this._parsedAnswer.media.forEach(a=>{e!=null&&e.includes(Number(a.mid))&&(o=!0,a.direction="inactive",a.ssrcs=[],a.ssrcGroups=[])}),this.removeDownlinkQueue.size===0&&o&&(yield this.updateSDP()),this._downlinkMIDMap.delete(A),e?.forEach(a=>this._downlinkMIDUserIDMap.delete(a)),this._log.info("removeDownlink(".concat(A,") done")),e})}setBandwidth(A){return WA(this,null,function*(){if(!this._peerConnection)return;let{audio:e,bigVideo:o,smallVideo:a,auxVideo:l}=A;try{if(Hk()){let d=this._peerConnection.getSenders().slice(0,4);for(let y=0;y5e3?5e3:e),!0)}setSenderMaxBitrate(A,e){let o=A.getParameters();if((!o.encodings||o.encodings.length===0)&&(o.encodings=[{}]),e==="unlimited")delete o.encodings[0].maxBitrate;else{if(o.encodings[0].maxBitrate===1e3*e)return;o.encodings[0].maxBitrate=1e3*e}return A.setParameters(o)}setBandwidthBySDP(A){let{audio:e,bigVideo:o,smallVideo:a,auxVideo:l}=A;if(!this._peerConnection||!this._peerConnection.localDescription)return;let d=uc(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let h=or?"TIAS":"AS";e&&(d.media[0].bandwidth=[{type:h,limit:or?1e3*e:e}],this._parsedAnswer.media[0].bandwidth=[{type:h,limit:or?1e3*e:e}]),o&&(d.media[1].bandwidth=[{type:h,limit:or?1e3*o:o}],this._parsedAnswer.media[1].bandwidth=[{type:h,limit:or?1e3*o:o}]),a&&(d.media[2].bandwidth=[{type:h,limit:or?1e3*a:a}],this._parsedAnswer.media[2].bandwidth=[{type:h,limit:or?1e3*a:a}]),l&&(d.media[3].bandwidth=[{type:h,limit:or?1e3*l:l}],this._parsedAnswer.media[3].bandwidth=[{type:h,limit:or?1e3*l:l}]);let y={type:"offer",sdp:_y(d)};return this.updateSDP({localDescription:y})}setScaleResolutionDownBy(A,e,o){let a=A.getParameters();(!a.encodings||a.encodings.length===0)&&(a.encodings=[{}]);let l=a.encodings[0].scaleResolutionDownBy;if(Ke(l)?e===1:e===l)return;let d="setScaleResolutionDownBy ".concat(o," ").concat(e);return l&&(d+=" prevScale: ".concat(l)),this._log.warn(d),a.encodings[0].scaleResolutionDownBy=e,A.setParameters(a)}setDegradationPreference(A,e,o){if(uE&&td<83||eg&&yk(LI,"12.1")||or&&O0<138)return;let a=A.getParameters(),l="balanced";if(e==="motion"?l="maintain-framerate":e==="detail"&&(l="maintain-resolution"),a.degradationPreference===l)return;let d="setDegradationPreference ".concat(o," ").concat(l);return this._log.info(d),a.degradationPreference=l,A.setParameters(a).catch(h=>this._log.warn("".concat(d," failed: ").concat(h)))}updateSDP(){let{localDescription:A}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!this._parsedAnswer)return Promise.resolve();let e=_y(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>WA(this,null,function*(){var l,d;try{!A&&this._peerConnection&&(this._log.info("creating offer"),A=yield this._peerConnection.createOffer()),A&&(yield this.setOffer(A)),yield this.setAnswer({type:"answer",sdp:e}),this._updateSDPPromise=null,o()}catch(h){this._log.error(h),!this._isSDPLogged&&this._peerConnection&&(this._log.warn("current offer: ".concat(this.filterSDPDirection((l=this._peerConnection.localDescription)==null?void 0:l.sdp),` next offer: `).concat(this.filterSDPDirection(A?.sdp))),this._log.warn("current answer: ".concat(this.filterSDPDirection((d=this._peerConnection.remoteDescription)==null?void 0:d.sdp),` -next answer: `).concat(this.filterSDPDirection(e))),this._log.warn("offer: ".concat(A?.sdp)),this._log.warn("answer: ".concat(e)),this._log.warn("transceivers: ".concat(JSON.stringify(this._peerConnection.getTransceivers().map(y=>{let{mid:S,currentDirection:k,direction:V,stopped:J}=y;return{mid:S,currentDirection:k,direction:V,stopped:J}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,a(C)}})),this._updateSDPPromise}setTransceiverDirection(A,e){return KA(this,null,function*(){if(!er||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(e.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();e.forEach(a=>{o[a].direction!==A&&(o[a].direction=A)});for(let a of e){let c=this._parsedAnswer.media[a].direction;A===zn.INACTIVE&&c===zn.RECVONLY&&(this._parsedAnswer.media[a].direction=A),A===zn.SENDONLY&&c===zn.INACTIVE&&(this._parsedAnswer.media[a].direction=zn.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return uc(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let e=NoA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(e),this._peerConnection.setLocalDescription({type:"offer",sdp:e})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return KA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let e=!1;this._parsedAnswer.media.forEach(o=>{var a;if(o.type===YA.VIDEO){let c=this._serverAbility.video.codecs.find(d=>d.codec.toLowerCase()===A);c&&((a=o.payloads)==null||!a.includes(String(c.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],Q_(o,c),e=!0)}}),e&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var e;try{let o=(e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId,a="";if(A===2?a=Zb(o?.big)?o.big:"":A===3?a=Zb(o?.small)?o.small:"":A===7&&(a=Zb(o?.aux)?o.aux:""),!a)return"";let c=Kz(a,this.clientAbility);return c?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(a,", resolved=").concat(c)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(a)),c}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",e=Kz(A,this.clientAbility);if(e)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(e)),{big:e,small:e,aux:e};let o=this.getScheduleProfileLevelId(2),a=this.getScheduleProfileLevelId(3),c=this.getScheduleProfileLevelId(7);if(!o&&!a&&!c)return;let d={};return o&&(d.big=o),a&&(d.small=a),c&&(d.aux=c),d}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,e){return KA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,a=this._parsedAnswer.media[o];if(!a||a.type!==YA.VIDEO)return;let c=a.rtp||[],d=a.fmtp||[],C=c.find(gA=>{var CA;return((CA=gA.codec)==null?void 0:CA.toLowerCase())==="h264"});if(!C)return;let y=d.find(gA=>String(gA.payload)===String(C.payload));if(!y)return;let S=fj(y.config);if(!S)return;let k=yj(S)==="high";if(e&&k||!e&&!k)return;let V=this._serverAbility.video.codecs.map(gA=>fj(gA.fmtp)).filter(Boolean).find(gA=>{let CA=yj(gA);return e?CA==="high":CA!=="high"});if(!V)return;let J=y.config;y.config=Hz(y.config,V),y.config!==J&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],e=arguments.length>1?arguments[1]:void 0;return KA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,a=[];Je(e)?a=this._parsedAnswer.media.slice(1,4):e===2?a.push(this._parsedAnswer.media[1]):e===3?a.push(this._parsedAnswer.media[2]):e===7&&a.push(this._parsedAnswer.media[3]),a.forEach(c=>{var d;if(c.type===YA.VIDEO){let C;A&&this.is42001fSupported?C=this.clientAbility.video.codecs.find(y=>y.fmtp.includes("42001f")):A||(C=this._serverAbility.video.codecs.find(y=>y.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),C&&((d=c.payloads)==null||!d.includes(String(C.payload)))&&(c.fmtp=[],c.payloads="",c.rtp=[],c.rtcpFb=[],Q_(c,C),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var e;(e=this._datachannel)==null||e.send(A)}reset(){var A;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._datachannel=null,(A=this.clearWaitForConnectedPromise)==null||A.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(A=>Np(A.abort)&&A.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(A){if(!this._peerConnection)return[];let e=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>e[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:e,downlinkRTT:o}=A;var a;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let c=this._signalChannel.rtt,d=Math.max(e,o),{rttRatioThreshold:C,rttThreshold:y}=((a=this._room.scheduleResult.config)==null?void 0:a.useTurnTcpInfo)||{};if(!(C&&y&&c&&d))return;let S=Math.floor(d/c),k=(this._isRelayTried||S>C)&&d>y;k?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(c," upRTT: ").concat(e," downRTT: ").concat(o," ratio: ").concat(S," over-count: ").concat(this._rttOverCount," isOver: ").concat(k," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return KA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",a=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let c=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),ii.addSuccessEvent({key:a,cost:Date.now()-c})}catch(c){this._log.warn("switchRelay ".concat(o," failed"),c),ii.addFailedEvent({key:a,error:c}),e?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((e,o)=>{let a=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(e,o).finally(()=>clearTimeout(a))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:Qj,data:{videoDecCodec:"h264"},responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};Ci([g5("reconnect")],Ry.prototype,"startReconnection"),Ci([py(A=>A.userId)],Ry.prototype,"addDownlink"),Ci([py(A=>A)],Ry.prototype,"removeDownlink"),Ci([$k(!0)],Ry.prototype,"updateSDP"),Ci([fy(521712,!1),o1(10,0)],Ry.prototype,"setOffer"),Ci([fy(521713,!1),o1(10,0)],Ry.prototype,"setAnswer"),Ci([jr((A,e)=>function(){for(var o=arguments.length,a=new Array(o),c=0;cclearTimeout(d)),this._checkPendingPromiseSet.clear()),A.apply(this,a)})],Ry.prototype,"close");var LoA=class{constructor(A){Y(this,"tag"),Y(this,"len"),Y(this,"data");let e=new DataView(A);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},UoA=class{constructor(A){Y(this,"tinyId"),Y(this,"data");let e=new DataView(A),o=0,a=[];for(;o{S.tag===1?this.tinyId=new TextDecoder().decode(S.data):S.tag===2&&c.push(S.data)});let d=c.reduce((S,k)=>S+k.byteLength,0),C=new Uint8Array(d),y=0;c.forEach(S=>{C.set(new Uint8Array(S),y),y+=S.byteLength}),this.data=C.buffer}},Wz=new Set;function tB(){let A=Math.floor(4294967296*Math.random());return Wz.has(A)?tB():(Wz.add(A),A)}var FoA=gc(Kl()),zz=class extends FoA.default{constructor(A){super(),Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_currentState","DISCONNECTED"),Y(this,"_prevTime",-1),Y(this,"_blackSmallVideoDetectionId"),Y(this,"isDestroyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=QA.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var A;return((A=this.singlePC)==null?void 0:A.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(A){this._log.info("close connection"),this.emit("closed",A)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(F.emit(nA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}};function Zz(A){let{when:e,onSkip:o}=A;return jr((a,c)=>function(){for(var d=arguments.length,C=new Array(d),y=0;y{let{mid:S,currentDirection:k,direction:V,stopped:J}=y;return{mid:S,currentDirection:k,direction:V,stopped:J}})))),this._log.warn("parsedAnswer: ".concat(JSON.stringify(this._parsedAnswer))),this._isSDPLogged=!0),this._updateSDPPromise=null,a(h)}})),this._updateSDPPromise}setTransceiverDirection(A,e){return WA(this,null,function*(){if(!or||!this._peerConnection||!this._parsedAnswer)return;this._log.info("setting transceiver ".concat(e.join(",")," direction to ").concat(A));let o=this._peerConnection.getTransceivers();e.forEach(a=>{o[a].direction!==A&&(o[a].direction=A)});for(let a of e){let l=this._parsedAnswer.media[a].direction;A===Xn.INACTIVE&&l===Xn.RECVONLY&&(this._parsedAnswer.media[a].direction=A),A===Xn.SENDONLY&&l===Xn.INACTIVE&&(this._parsedAnswer.media[a].direction=Xn.RECVONLY)}yield this.updateSDP()})}filterSDPDirection(){return uc(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let e=rsA(A.sdp,this.clientAbility,this._serverAbility);return this._log.debug(e),this._peerConnection.setLocalDescription({type:"offer",sdp:e})}setAnswer(A){return this._log.info("setting answer"),this._log.debug(A.sdp),this._peerConnection.setRemoteDescription(A)}switchVideoEncoder(A){return WA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let e=!1;this._parsedAnswer.media.forEach(o=>{var a;if(o.type===YA.VIDEO){let l=this._serverAbility.video.codecs.find(d=>d.codec.toLowerCase()===A);l&&((a=o.payloads)==null||!a.includes(String(l.payload)))&&(o.fmtp=[],o.payloads="",o.rtp=[],o.rtcpFb=[],f_(o,l),e=!0)}}),e&&(this._log.warn("switch video encoder to ".concat(A)),yield this.updateSDP())})}getScheduleProfileLevelId(A){var e;try{let o=(e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId,a="";if(A===2?a=ik(o?.big)?o.big:"":A===3?a=ik(o?.small)?o.small:"":A===7&&(a=ik(o?.aux)?o.aux:""),!a)return"";let l=C8(a,this.clientAbility);return l?this._log.info("use schedule profile level id: streamType=".concat(A,", raw=").concat(a,", resolved=").concat(l)):this._log.warn("schedule profile level id not resolved: streamType=".concat(A,", raw=").concat(a)),l}catch(o){return this._log.warn("getScheduleProfileLevelId error: ".concat(o)),""}}getProfileLevelIdConfig(){try{let A=new URLSearchParams(location.search).get("profileLevelId")||"",e=C8(A,this.clientAbility);if(e)return this._log.info("use url profile level id: raw=".concat(A,", resolved=").concat(e)),{big:e,small:e,aux:e};let o=this.getScheduleProfileLevelId(2),a=this.getScheduleProfileLevelId(3),l=this.getScheduleProfileLevelId(7);if(!o&&!a&&!l)return;let d={};return o&&(d.big=o),a&&(d.small=a),l&&(d.aux=l),d}catch(A){return void this._log.warn("getProfileLevelIdConfig error: ".concat(A))}}setH264ProfileLevelId(A,e){return WA(this,null,function*(){if(!this._peerConnection||!this._serverAbility)return;this._updateSDPPromise&&(yield this._updateSDPPromise),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," for ").concat(A)),this._parsedAnswer||(this._parsedAnswer=uc(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,a=this._parsedAnswer.media[o];if(!a||a.type!==YA.VIDEO)return;let l=a.rtp||[],d=a.fmtp||[],h=l.find(cA=>{var CA;return((CA=cA.codec)==null?void 0:CA.toLowerCase())==="h264"});if(!h)return;let y=d.find(cA=>String(cA.payload)===String(h.payload));if(!y)return;let S=Uj(y.config);if(!S)return;let k=Fj(S)==="high";if(e&&k||!e&&!k)return;let V=this._serverAbility.video.codecs.map(cA=>Uj(cA.fmtp)).filter(Boolean).find(cA=>{let CA=Fj(cA);return e?CA==="high":CA!=="high"});if(!V)return;let J=y.config;y.config=E8(y.config,V),y.config!==J&&(yield this.updateSDP(),this._log.info("set H264 profile-level-id to ".concat(e?"high":"default"," success")))})}useHWEncoder(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0],e=arguments.length>1?arguments[1]:void 0;return WA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,a=[];Ke(e)?a=this._parsedAnswer.media.slice(1,4):e===2?a.push(this._parsedAnswer.media[1]):e===3?a.push(this._parsedAnswer.media[2]):e===7&&a.push(this._parsedAnswer.media[3]),a.forEach(l=>{var d;if(l.type===YA.VIDEO){let h;A&&this.is42001fSupported?h=this.clientAbility.video.codecs.find(y=>y.fmtp.includes("42001f")):A||(h=this._serverAbility.video.codecs.find(y=>y.codec.toLowerCase()===(this._serverAbility.useVp8?"vp8":"h264"))),h&&((d=l.payloads)==null||!d.includes(String(h.payload)))&&(l.fmtp=[],l.payloads="",l.rtp=[],l.rtcpFb=[],f_(l,h),o=!0)}}),o&&(this._log.warn("use ".concat(A?"hw":"sw"," encoder")),yield this.updateSDP())})}sendDataChannelMessage(A){var e;(e=this._datachannel)==null||e.send(A)}reset(){var A;this._peerConnection&&(this._peerConnection.close(),this._peerConnection.removeEventListener("track",this._peerConnection._onaddstreampoly,this),this._peerConnection._onaddstreampoly=null,this._peerConnection=null),this._datachannel=null,(A=this.clearWaitForConnectedPromise)==null||A.call(this),this._parsedAnswer=null,this.originOffer=null}close(){this._log.info("close pc"),this.isDestroyed=!0,this.removeRTCListener(),this.insertableStreamsAbortMap.forEach(A=>kp(A.abort)&&A.abort("destroy")),this.insertableStreamsAbortMap.clear(),this.reset(),this.emitConnectionStateChangedEvent("DISCONNECTED"),this._downlinkMIDMap.clear(),this.stopReconnection(),this.removeAllListeners(),this._room.healthDetector.off("1",this.onBadHealth,this)}getReceiversByUserId(A){if(!this._peerConnection)return[];let e=this._peerConnection.getReceivers();return(this._downlinkMIDMap.get(A)||[]).map(o=>e[o])}get isUsingRelay(){return this._room.getIceTransportPolicy()==="relay"}detectTCPAndUDP(A){let{uplinkRTT:e,downlinkRTT:o}=A;var a;if(this.currentState!=="CONNECTED"||this._isRelayTried&&!this._room.forceRelay||this._room.getIceServers().length===0)return;let l=this._signalChannel.rtt,d=Math.max(e,o),{rttRatioThreshold:h,rttThreshold:y}=((a=this._room.scheduleResult.config)==null?void 0:a.useTurnTcpInfo)||{};if(!(h&&y&&l&&d))return;let S=Math.floor(d/l),k=(this._isRelayTried||S>h)&&d>y;k?++this._rttOverCount<5||(this._log.warn("detectTCPAndUDP ws-rtt: ".concat(l," upRTT: ").concat(e," downRTT: ").concat(o," ratio: ").concat(S," over-count: ").concat(this._rttOverCount," isOver: ").concat(k," isRelayTried: ").concat(this._isRelayTried," force-relay: ").concat(this._room.forceRelay)),this.isUsingRelay||this._isRelayTried?this._room.forceRelay&&this.switchRelay(!1):(this._isRelayTried=!0,this._rttOverCount=0,this.switchRelay(!0))):this._rttOverCount=0}switchRelay(A){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return WA(this,null,function*(){if(this.isUsingRelay===A)return;let o=A?"relay":"udp",a=A?521709:521710;try{this._room.forceRelay=A,this._log.warn("switchRelay ".concat(o));let l=Date.now();yield this.doSwitchRelay(o),this._log.warn("switchRelay ".concat(o," success")),si.addSuccessEvent({key:a,cost:Date.now()-l})}catch(l){this._log.warn("switchRelay ".concat(o," failed"),l),si.addFailedEvent({key:a,error:l}),e?this._room.reJoin():yield this.switchRelay(!A,!0)}})}doSwitchRelay(A){return new Promise((e,o)=>{let a=setTimeout(()=>{this.stopReconnection(),o(new Error("switch ".concat(A," timeout")))},1e4);this.startReconnection().then(e,o).finally(()=>clearTimeout(a))})}removeRTCListener(){this._peerConnection&&(this._peerConnection.oniceconnectionstatechange=null,this._peerConnection.onconnectionstatechange=null,this._peerConnection.onsignalingstatechange=null,this._peerConnection.ontrack=null),this.dtlsTransport&&(this.dtlsTransport.onstatechange=null)}requestRemoteFallbackToH264(){this._log.warn("H265 decode failed, remote need to fallback h264"),this._h265DecodeFailed=!0,this._signalChannel.sendWaitForResponse({command:bj,data:{videoDecCodec:"h264"},responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};hi([N5("reconnect")],Ty.prototype,"startReconnection"),hi([Dy(A=>A.userId)],Ty.prototype,"addDownlink"),hi([Dy(A=>A)],Ty.prototype,"removeDownlink"),hi([sL(!0)],Ty.prototype,"updateSDP"),hi([Sy(521712,!1),E1(10,0)],Ty.prototype,"setOffer"),hi([Sy(521713,!1),E1(10,0)],Ty.prototype,"setAnswer"),hi([jr((A,e)=>function(){for(var o=arguments.length,a=new Array(o),l=0;lclearTimeout(d)),this._checkPendingPromiseSet.clear()),A.apply(this,a)})],Ty.prototype,"close");var lsA=class{constructor(A){Y(this,"tag"),Y(this,"len"),Y(this,"data");let e=new DataView(A);this.tag=e.getUint16(),this.len=e.getUint16(2),this.data=new Uint8Array(A).slice(4,4+this.len).buffer}},IsA=class{constructor(A){Y(this,"tinyId"),Y(this,"data");let e=new DataView(A),o=0,a=[];for(;o{S.tag===1?this.tinyId=new TextDecoder().decode(S.data):S.tag===2&&l.push(S.data)});let d=l.reduce((S,k)=>S+k.byteLength,0),h=new Uint8Array(d),y=0;l.forEach(S=>{h.set(new Uint8Array(S),y),y+=S.byteLength}),this.data=h.buffer}},B8=new Set;function sB(){let A=Math.floor(4294967296*Math.random());return B8.has(A)?sB():(B8.add(A),A)}var usA=gc(jl()),Q8=class extends usA.default{constructor(A){super(),Y(this,"userId"),Y(this,"tinyId"),Y(this,"_sdpSemantics"),Y(this,"_isUplink"),Y(this,"_room"),Y(this,"_log"),Y(this,"_currentState","DISCONNECTED"),Y(this,"_prevTime",-1),Y(this,"_blackSmallVideoDetectionId"),Y(this,"isDestroyed",!1),this.userId=A.userId,this.tinyId=A.tinyId,this._room=A.room,this._sdpSemantics=A.room.sdpSemantics,this._isUplink=A.isUplink,this._log=pA.createLogger({parent:this._room.getLogger(),id:"n",userId:this._room.userId,remoteUserId:this._isUplink?void 0:this.userId,sdkAppId:this._room.sdkAppId,isLocal:this._isUplink})}get _peerConnection(){var A;return((A=this.singlePC)==null?void 0:A.getPeerConnection())||null}get singlePC(){return this._room.singlePC}get _signalChannel(){return this._room.signalChannel}close(A){this._log.info("close connection"),this.emit("closed",A)}destroy(){this.isDestroyed=!0}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(F.emit(nA.PEER_CONNECTION_STATE_CHANGED,{room:this._room,prevState:this._currentState,state:A,remoteUserId:this._isUplink?void 0:this.userId}),this.emit("connection-state-changed",{prevState:this._currentState,state:A}),this._currentState=A,!0)}getPeerConnection(){return this._peerConnection}getRoom(){return this._room}getUserId(){return this.userId}getTinyId(){return this.tinyId}getCurrentState(){return this._currentState}get isH264(){var A,e;return!((e=(A=this._peerConnection)==null?void 0:A.remoteDescription)==null||!e.sdp.includes("H264"))}};function p8(A){let{when:e,onSkip:o}=A;return jr((a,l)=>function(){for(var d=arguments.length,h=new Array(d),y=0;ypostMessage({type:"log",message:"[worker] "+t.join(" ")});function startDetection(e,t,a){if(!tracks.has(e)){const c={reader:a.getReader(),blackCount:0,timeoutId:null,intervalId:null};tracks.set(e,c),c.timeoutId=setTimeout(()=>stopDetection(e,"timeout"),t),c.intervalId=setInterval(async()=>{try{await isFrameBlack(e)?(c.blackCount++,postMessage({type:"blackCount",trackId:e,count:c.blackCount}),3<=c.blackCount&&(postMessage({type:"black",trackId:e}),stopDetection(e,"black"))):c.blackCount=0}catch(t){log("check black video error:",t.message),stopDetection(e,"error")}},1e3)}}function stopDetection(t,e){var a=tracks.get(t);a&&(a.timeoutId&&clearTimeout(a.timeoutId),a.intervalId&&clearInterval(a.intervalId),a.reader&&a.reader.cancel(),tracks.delete(t),postMessage({type:e,trackId:t}))}async function isFrameBlack(t){t=tracks.get(t);if(!t)return!1;var t=t.reader,{done:t,value:e}=await t.read();if(!e||t)return!1;canvas||(canvas=new OffscreenCanvas(e.codedWidth,e.codedHeight),ctx=canvas.getContext("2d",{willReadFrequently:!0})),canvas.width===e.codedWidth&&canvas.height===e.codedHeight||(canvas.width=e.codedWidth,canvas.height=e.codedHeight,ctx=canvas.getContext("2d",{willReadFrequently:!0})),ctx.drawImage(e,0,0,canvas.width,canvas.height);t=getFrameBlackRatio(ctx.getImageData(0,0,canvas.width,canvas.height));return e.close(),1===t}function getFrameBlackRatio(t){var e=t.data;let a=0;for(let t=0;t<100;t++){var c=4*Math.floor(Math.random()*(e.length/4)),[c,r,n,o]=[e[c],e[1+c],e[2+c],e[3+c]];0{var{type:t,trackId:e,timeout:a,readable:c}=t.data;"addTrack"===t&&startDetection(e,a,c),"removeTrack"===t&&stopDetection(e)}; - `],{type:"application/javascript"}),e=URL.createObjectURL(A);this.worker=new Worker(e),URL.revokeObjectURL(e),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var a;let{type:c,trackId:d,message:C,count:y}=o.data;if(c==="black")(a=this.callbacks.get(d))==null||a();else if(c==="log")this._log.warn(C);else if(c==="blackCount"){let S=this.userIdMap.get(d);this._log.warn("".concat(S||d," black count: ").concat(y))}}}return this.worker}start(A){let{track:e,isUplink:o,room:a,userId:c,onBlack:d}=A;if(this._log.debug("start detect black video",e.id),!RM()||!d||!e||typeof Worker>"u")return void this._log.warn("black video detector not supported");let C=y=>{var S,k,V,J;let gA;if(o)gA=(k=(S=y.msg_up_stream_info)==null?void 0:S.msg_video_status)==null?void 0:k.filter(CA=>CA.uint32_video_stream_type===3)[0];else{let CA=(V=y.msg_down_stream_info)==null?void 0:V.filter(MA=>{var $A;return(($A=MA.msg_user_info)==null?void 0:$A.str_identifier)===c})[0];gA=(J=CA?.msg_video_status)==null?void 0:J.filter(MA=>MA.uint32_video_stream_type===3)[0]}if(gA){let CA=(gA.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[e.id]&&this.sleep[e.id]>0)return void(this.sleep[e.id]-=1);CA>0&&CA<10&&(this.sleep[e.id]=30,this._log.info("track bitrate",CA,"start check"),this.checkOnce(e,3e4))}};return a.on("heartbeat-report",C),this.heartbeatListenerCleaner.set(e.id,()=>a.off("heartbeat-report",C)),this.callbacks.set(e.id,d),this.userIdMap.set(e.id,c),e.id}checkOnce(A,e){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let a=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:e,readable:a.readable},[a.readable])}catch(o){this._log.warn("check error:",o),this.stop(A.id)}}stop(A){if(A){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:A}),this.callbacks.delete(A),delete this.sleep[A];let e=this.heartbeatListenerCleaner.get(A);e&&e(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},R1=class extends zz{constructor(A){super(Qo(mi({},A),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"_flag",0),Y(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:A,bigVideoSsrc:e,bigVideoRtxSsrc:o,smallVideoSsrc:a,smallVideoRtxSsrc:c,auxVideoSsrc:d,auxVideoRtxSsrc:C}=this.singlePC.uplinkSSRC;return{audio:A||0,video:e||0,videoRtx:o||0,small:a||0,smallRtx:c||0,auxiliary:d||0,auxiliaryRtx:C||0}}get flag(){return this._flag}set flag(A){this._flag!==A&&(this._flag=A,this.checkPublishState())}checkPublishState(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];try{if(!A&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:e}=this,{publishState:o}=this._room,a=Object.keys(o).filter(c=>{if(o[c]!==e[c]&&o[c])switch(c){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(a.length>0){if(!A)return void(this._checkPublishStateTimeoutId=Gr.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));ii.addCount({key:521e3}),a.forEach(c=>{this._log.warn("".concat(c," publish failed during call ").concat(Yp()," ").concat(rQ())),ii.addEnum({key:521719,value:Xz[c]})}),Gr.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(e){this._log.warn("checkPublishState failed",e)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&jS),bigVideo:!!(this.flag&qS),smallVideo:!!(this.flag&Mb),auxVideo:!!(this.flag&KS)}}initialize(){this.installEvents()}close(A){var e;let o=((e=this._peerConnection)==null?void 0:e.getSenders())||[];for(let a of o)a.replaceTrack(null);super.close(A),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var A,e;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var A;(A=this.singlePC)==null||A.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(A,e){var o,a,c;let d=this._currentState,C=super.emitConnectionStateChangedEvent(A);return C&&d!==A&&(e?e.emit("connection-state-changed",{prevState:d,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:d,state:A}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:d,state:A}),(c=this._publishingLocalVideoTrack)==null||c.emit("connection-state-changed",{prevState:d,state:A}))),C}onVideoEncodeFailed(A){return KA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:e,singlePC:o}=this;if(!o)return;let a={h265:{supported:o.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:o.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(e==="vp9"||e==="av1")return;let c=a[e];this._log.warn(c.log),c!=null&&c.supported&&(yield o.switchVideoEncoder(c.target))})}publish(A){return KA(this,arguments,function(e){var o=this;let{localAudioTrack:a,localVideoTrack:c,isAuxiliary:d}=e;return function*(){var C,y,S,k,V,J,gA;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(a,c),c&&(c.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),eg&&(ny(kI,"26.2",!0)||ny(oQ,"26.2",!0)||tQ&&ny(kI,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield te.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),a&&(o._publishingLocalAudioTrack=a),c){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new ai({code:dt.NOT_SUPPORTED_H264,message:Xo({key:Mo.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),Ha&&pM()===115&&c.profile.width*c.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(HS))),c.setProfile(HS),yield c.applyProfile()),o._publishingLocalVideoTrack=c}let CA;if(o._isPublishingAux=d,c&&!d&&c.small&&(CA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:_z,responseCommand:ls.SPC_PUBLISH_RESULT,data:Qo(mi({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),c&&(yield o.checkHighProfile({streamType:c.streamType,newWidth:c.settings.width,newHeight:c.settings.height})),yield o.publishByTransceiver({localAudioTrack:a,localVideoTrack:c,smallTrack:CA,isAuxiliary:d}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,c){o[d?"localAuxVideoTrack":"localMainVideoTrack"]=c,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[d?3:1],c.contentHint,c.streamType);let{scaleResolutionDownBy:$A}=c;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[d?3:1],$A,c.streamType)}a&&(o[d?"localAuxAudioTrack":"localMainAudioTrack"]=a),yield o.singlePC.setBandwidth({audio:((C=o.localMainAudioTrack)==null?void 0:C.profile.bitrate)||((y=o.localAuxAudioTrack)==null?void 0:y.profile.bitrate),bigVideo:(S=o.localMainVideoTrack)==null?void 0:S.profile.bitrate,smallVideo:(V=(k=o.localMainVideoTrack)==null?void 0:k.small)==null?void 0:V.bitrate,auxVideo:(J=o.localAuxVideoTrack)==null?void 0:J.profile.bitrate}),o.sendMediaSettings();let MA=d?7:2;(o._room.preferHW||(gA=o._room.scheduleResult.config)!=null&&gA.preferHW)&&c&&c.profile.width*c.profile.height>=921600&&o.singlePC.useHWEncoder(!0,MA)}()})}publishByTransceiver(A){let{localAudioTrack:e,localVideoTrack:o,smallTrack:a,isAuxiliary:c}=A;if(!Xd())return;this._log.info("publish by transceiver");let d=o?.outMediaTrack,C=e?.outMediaTrack,y=this._peerConnection.getTransceivers(),S=[],k=[],V=(gA,CA,MA)=>{var $A;let Be=y[CA].sender.replaceTrack(MA);k.push(CA),($A=this.singlePC)!=null&&$A.enableInsertableStreams&&Be.then(()=>this.createEncodedStreams(y[CA].sender,gA)),this.initSenderTransform(y[CA].sender,gA),S.push(Be)};C&&V(e.mediaType,0,C),d&&V(o.mediaType,c?3:1,d),o!=null&&o.small&&S.push(this.publishSmall(this._room.videoManager.smallMode,o));let J=this.singlePC.setTransceiverDirection(zn.SENDONLY,k);return S.push(J),Promise.all(S)}getTrackByMediaType(A){switch(A){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(A,e){var o,a;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let c=A.createEncodedStreams(),d=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,d),((a=this.getTrackByMediaType(e))!=null&&a.enableEncodeFrame?c.readable.pipeThrough(new TransformStream({transform:(C,y)=>{var S,k;let V=this.getTrackByMediaType(e);if(!V||!V.encodeFrame)return y.enqueue(C);V.isAudio?y.enqueue(V.enableEncodeFrame?V.encodeFrame(C):C):y.enqueue((S=this.singlePC)!=null&&S.isUsingH264||(k=this.singlePC)!=null&&k.isUsingH265?V.encodeFrame(C,e===8):C)}}),d):c.readable).pipeTo(c.writable,d).catch(C=>{this._log.debug("encoded stream error",C),C!=="destroy"&&this._log.warn(C)})}initSenderTransform(A,e){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&e_))return;let o=e!==2,a=e===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:e===1,isMain:o,isSmall:a}))}enableSmall(A){return KA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return KA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var c;if(!o.singlePC)return;if(e==="canvas"&&!A_())return void o._log.warn("canvas mode small stream is not supported");let d=o._peerConnection.getTransceivers(),{sender:C}=d[2],y=yield o.doPublishSmall(e,a),S=e==="canvas"?524700:524701;ii.addSuccessEvent({key:S}),y?((c=o.singlePC)!=null&&c.enableInsertableStreams&&o.createEncodedStreams(C,8),o.initSenderTransform(C,8),yield o.singlePC.setTransceiverDirection(zn.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),C.track&&(o._blackSmallVideoDetectionId=$M.start({track:C.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let k=e==="canvas"?524700:524701;ii.addFailedEvent({key:k,error:10002}),$M.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):ii.addFailedEvent({key:S,error:10001})}()})}doPublishSmall(A){return KA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",e);let c=o._peerConnection.getTransceivers(),{sender:d}=c[2];if(e==="canvas"&&o._room.videoManager.smallTrack)return yield d.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(e==="api"&&a!=null&&a.outMediaTrack&&a!=null&&a.small){yield d.replaceTrack(a?.outMediaTrack);let C=d.getParameters(),y=w0(a?.profile,a?.small);return o._log.info("small scaleResolutionDownBy",y),C.encodings[0].scaleResolutionDownBy=y,d.setParameters(C),"api"}return o._log.warn("small track can not be enabled, smallMode: ".concat(o._room.videoManager.smallMode,", smallTrack: ").concat(!!o._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(a==null||!a.outMediaTrack))),null}()})}unpublishSmall(){return KA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(zn.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),$M.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return KA(this,null,function*(){var e,o;if((((e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let a=A.newWidth*A.newHeight>=921600&&!ry();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,a)}catch(c){this._log.warn("setH264ProfileLevelId failed, ignore",c)}})}installTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return KA(this,arguments,function(e){var o=this;let{localAudioTrack:a,localVideoTrack:c}=e;return function*(){var d;yield(d=o.singlePC)==null?void 0:d.waitForPeerConnectionConnected();let C=c&&c===o.localAuxVideoTrack||a&&a===o.localAuxAudioTrack,y=c?.outMediaTrack,S=o._peerConnection.getSenders(),k=[];a&&(C?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield S[0].replaceTrack(null),k.push(0))),y&&(C?(yield S[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=Qo(mi({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),k.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=Qo(mi({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),k.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(zn.INACTIVE,k),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(a,c),c?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return KA(this,null,function*(){let e={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:Cj,data:e,responseCommand:ls.PUBLISH_STATE_CHANGE_RESULT,enableLog:A,retries:3});this.checkPublishResultCode(o.data.code,o.data.message)})}doUnpublish(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:f1,commandDesc:"unpublish",responseCommand:ls.UNPUBLISH_RESULT,enableLog:A}).catch(e=>{if(e.getCode()===dt.API_CALL_TIMEOUT||e.getCode()===dt.API_CALL_ABORTED)return Promise.resolve();throw e})}updateMediaSettings(){var A,e;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:c}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?c=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),Cy){if(o&&o.outMediaTrack){let d=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=d.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=d.sampleRate||0}if(a&&a.outMediaTrack){let d=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:C}=a;this._mediaSettings.videoWidth=(d.width||0)/C||0,this._mediaSettings.videoHeight=(d.height||0)/C||0,this._mediaSettings.videoFps=d.frameRate||0,this._mediaSettings.videoBps=1e3*a.profile.bitrate,a.small&&(this._mediaSettings.smallVideoWidth=a.small.width,this._mediaSettings.smallVideoHeight=a.small.height,this._mediaSettings.smallVideoFps=a.small.frameRate,this._mediaSettings.smallVideoBps=1e3*a.small.bitrate)}if(c&&c.outMediaTrack){let d=c.outMediaTrack.getSettings(),{scaleResolutionDownBy:C}=c;this._mediaSettings.auxVideoWidth=(d.width||0)/C||0,this._mediaSettings.auxVideoHeight=(d.height||0)/C||0,this._mediaSettings.auxVideoFps=d.frameRate||0,this._mediaSettings.auxVideoBps=1e3*c.profile.bitrate}}else o&&o.outMediaTrack&&(this._mediaSettings.audioChannel=o.profile.channelCount,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=o.profile.sampleRate),a&&a.outMediaTrack&&(this._mediaSettings.videoWidth=a.profile.width,this._mediaSettings.videoHeight=a.profile.height,this._mediaSettings.videoFps=a.profile.frameRate,this._mediaSettings.videoBps=1e3*a.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:Qj,data:this._mediaSettings,responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return KA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(e?YA.AUXILIARY:YA.MAIN," stream")),IQ()&&(yield this.addTrackByTransceiver(A,e))})}addTrackByTransceiver(A,e){return KA(this,null,function*(){var o;if(!A.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(A.kind===YA.AUDIO)yield a[0].sender.replaceTrack(A.outMediaTrack);else{let c=e?3:1;yield a[c].sender.replaceTrack(A.outMediaTrack),c===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[c].direction===zn.INACTIVE&&(yield this.singlePC.setTransceiverDirection(zn.SENDONLY,[c]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return KA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(e?YA.AUXILIARY:YA.MAIN," stream")),IQ()&&(yield this.removeTrackByTransceiver(A,e))})}removeTrackByTransceiver(A,e){return KA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===YA.AUDIO)yield o[0].sender.replaceTrack(null);else{let a=e?3:1;yield o[a].sender.replaceTrack(null),a===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(zn.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return KA(this,null,function*(){var e;let o=(e=this._peerConnection)==null?void 0:e.getSenders(),a=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!a||o.find(d=>d.track===a))return!1;let c=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(a.kind," track ").concat(a.id," ").concat(a.label," on ").concat(c?YA.AUXILIARY:YA.MAIN," stream")),a.kind===YA.AUDIO&&o[0]&&(yield o[0].replaceTrack(a)),a.kind===YA.VIDEO&&(!c&&o[1]&&(yield o[1].replaceTrack(a)),c&&o[3]&&(yield o[3].replaceTrack(a))),!0})}setBandwidth(A){return KA(this,arguments,function(e){var o=this;let{bandwidth:a,type:c,videoType:d}=e;return function*(){if(o.singlePC){let C={};c===YA.AUDIO?C.audio=a:d==="big"?C.bigVideo=a:d==="small"?C.smallVideo=a:C.auxVideo=a,yield o.singlePC.setBandwidth(C)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:vz,responseCommand:ls.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:YA.VIDEO;if(this._peerConnection){let e=this._peerConnection.getSenders();if(A===YA.AUXILIARY&&e[3]&&e[3].track)return e[3].track.id;if(A===YA.VIDEO&&e[1]&&e[1].track)return e[1].track.id}if(this.localMainVideoTrack&&A===YA.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&A===YA.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,e){if(A!==0)throw A===I0?(this._log.error(cc.NOT_SUPPORTED_H264ENCODE),new ai({code:dt.NOT_SUPPORTED_H264,message:Xo({key:Mo.NOT_SUPPORTED_H264ENCODE})})):new ai({code:dt.UNKNOWN,message:Xo({key:Mo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.PUBLISH_RESULT,code:A,message:e}})})}onSinglePCReconnected(){return KA(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};Ci([VM(A=>{let{localVideoTrack:e}=A;e==null||delete e.retryEncodeFailed})],R1.prototype,"unpublish"),Ci([Zz({when(){return this.isDestroyed}})],R1.prototype,"doPublishChange"),Ci([Zz({when(){return this.isDestroyed}})],R1.prototype,"doUnpublish");var Xz=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(Xz||{}),$z=R1;function A8(A){return Object.keys(A).filter(e=>A[e])}var w1=class extends zz{constructor(A){super(Qo(mi({},A),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"fromType"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Y(this,"_prevMids"),Y(this,"jitterBufferTimeoutId",-1),Y(this,"_jitterBufferResolve"),Y(this,"_videoCodec"),Y(this,"avPlayerStateSyncManager"),Y(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new s1(this._room,this),this.remoteVideoTrack=new cL(this._room,this),this.remoteAuxiliaryTrack=new P5(this._room,this),this.avPlayerStateSyncManager=new ij({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),this.initialize()}get videoCodec(){var A;return this._videoCodec||((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}set videoCodec(A){this._videoCodec=A}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing,datachannel:this.isDataChannelSubscribed}}get muteState(){return wp(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var e,o,a;A!==this._flag&&(this._flag=A,(e=this.remoteAudioTrack)==null||e.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(a=this.remoteAuxiliaryTrack)==null||a.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(A){return A===YA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(A){clearTimeout(this.jitterBufferTimeoutId),super.close(A),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(A){var e,o;let a=this._currentState,c=super.emitConnectionStateChangedEvent(A);return c&&a!==A&&((e=this.remoteVideoTrack)==null||e.emit("connection-state-changed",{prevState:a,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:a,state:A})),c}onTrack(A){var e,o;let a=A.streams[0],{track:c,receiver:d}=A;if(!a.id.includes(this.tinyId))return;let C=a.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(C," ").concat(c.kind));let y=YA.AUDIO;c.kind===YA.VIDEO&&(y=C===YA.MAIN?YA.VIDEO:YA.AUXILIARY);let S=this.remoteAudioTrack;y===YA.VIDEO?S=this.remoteVideoTrack:y===YA.AUXILIARY&&(S=this.remoteAuxiliaryTrack),(e=this.singlePC)==null||e.receiverRemoteTrackMap.set(d,S),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(d,C,c.kind===YA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d),S.setInputMediaStreamTrack(c)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let e=A.createEncodedStreams(),o=new AbortController,a={abortController:o,enqueue:c=>{var d,C,y;let S=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(A);return S&&(S.kind!=="video"||(C=this.singlePC)!=null&&C.isUsingH264||(y=this.singlePC)!=null&&y.isUsingH265)?S.decodeFrame(c):c}};e.readable.pipeThrough(new TransformStream({transform:(c,d)=>{let C=a.enqueue(c);C&&d.enqueue(C)}})).pipeTo(e.writable,o).catch(c=>{c!=="destroy"&&this._log.warn(c)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,e,o){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:o,userId:this.userId,streamType:e}))}subscribe(A,e){return KA(this,null,function*(){var o,a;try{let c=!0;if(this._log.info("subscribe ".concat(e," ").concat(A8(A))),this.hasSSRC){let y="subscribe_change";Object.values(A).find(S=>S===!0)||(y="unsubscribe"),yield this.sendSubscription(y,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let y=this.singlePC.autoSubscribedUserMap.get(this.userId);if(y){this.singlePC.autoSubscribedUserMap.delete(this.userId);let S=(a=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:a[y.groupIndex];S&&(this.ssrc={audio:S.audioSsrc,video:S.bigVideoSsrc,videoRtx:S.bigVideoRtxSsrc,auxiliary:S.auxVideoSsrc,auxiliaryRtx:S.auxVideoRtxSsrc},c=!1)}}yield this.doSubscribe(A,c),this.checkTrackEnded(A)}let{user:d,mediaTrack:C}=this.remoteVideoTrack;A.smallVideo&&C?(ii.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=$M.start({track:C,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,d),ii.addFailedEvent({key:524702}),$M.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):($M.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(c){throw this._room.isJoined&&this.isStreamUnpublished(e)?(this._log.warn("".concat(c.message," ").concat(JSON.stringify(this.muteState))),new ai({code:dt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):c}})}checkTrackEnded(A){var e,o,a;if((A.audio&&((e=this.remoteAudioTrack.mediaTrack)==null?void 0:e.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((a=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:a.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),IE&&id<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return KA(this,arguments,function(e){var o=this;let{remoteTracks:a,streamType:c}=e;return function*(){var d;if(c==="main"&&!o.isMainStreamSubscribed||c==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(c," stream already unsubscribed"));let C=mi({},o.subscribeState);a.forEach(S=>{switch(S.mediaType){case 1:C.audio=!1;break;case 4:C.video=!1;break;case 8:C.smallVideo=!1;break;case 2:C.auxiliary=!1}});let y="subscribe_change";Object.values(C).find(S=>S===!0)||(y="unsubscribe"),o._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(c," [").concat(A8(C),"]")),y==="unsubscribe"&&((d=o.singlePC)==null||d.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(y,C),c==="main"&&($M.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),y==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return KA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=Qo(mi({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return KA(this,null,function*(){let A=Qo(mi({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},a=hj,c=ls.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:e.datachannel,srcTinyId:this.tinyId},a=Bj,c=ls.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:a,data:o,responseCommand:c,timeout:1e4,retries:3}).then(d=>{let{data:C}=d;if(C.code!==0){let y=new ai({code:C.code,message:Xo({key:Mo.ERROR_MESSAGE,data:{type:A,message:C.message}})});throw this._log.error(y),y}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(A){let{audioDelay:e,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return KA(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return KA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var a,c;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let d={audioSsrc:tB(),bigVideoSsrc:tB(),bigVideoRtxSsrc:tB(),auxVideoSsrc:tB(),auxVideoRtxSsrc:tB()},{audioSsrc:C,bigVideoSsrc:y,bigVideoRtxSsrc:S,auxVideoSsrc:k,auxVideoRtxSsrc:V}=d;A.ssrc={audio:C,video:y,videoRtx:S,auxiliary:k,auxiliaryRtx:V},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let J=yield A._signalChannel.sendWaitForResponseWithRetry({command:Tz,responseCommand:ls.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:(a=e.datachannel)!=null&&a,ssrc:d},retries:3,retryTimeout:0});if(J.data.code!==0&&J.data.code!==-10036)throw new ai({code:J.data.code,message:J.data.message});A.isDataChannelSubscribed=(c=e.datachannel)!=null&&c}catch(J){throw yield A.removeDownlink(),J}return}A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids})}finally{if((e.audio||e.video||e.smallVideo||e.auxiliary||!e.datachannel)&&uQ){let{main:d,aux:C}=A._room.jitterBufferDelay||{},{jitterDelay:y=d,jitterDelayAux:S=C}=A._room.scheduleResult.config||{};(bn(y)||bn(S))&&A.setJitterBufferDelay({mainDelay:y,auxDelay:S})}}}}()})}removeDownlink(){return KA(this,null,function*(){this.singlePC&&(this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve&&(this._jitterBufferResolve(),this._jitterBufferResolve=void 0),this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),this._prevMids=yield this.singlePC.removeDownlink(this.userId))})}setJitterBufferDelay(A){let{mainDelay:e,auxDelay:o}=A;if(!uQ||!this.singlePC||!this._peerConnection||Ad(e)&&Ad(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(e," aux: ").concat(o));let a=this.singlePC.getReceiversByUserId(this.userId);return bn(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),bn(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,Ad(e)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(c=>{this._jitterBufferResolve=c,this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:a,resolve:c})})}doSetJitterBufferDelay(A){let{mainDelay:e,auxDelay:o,receivers:a,resolve:c}=A;try{if(e===0&&o===0)return a.forEach(d=>d.jitterBufferTarget=0),this._jitterBufferResolve=void 0,c();if(a.forEach(d=>{var C;let y=d.track===this.remoteAuxiliaryTrack.outMediaTrack||Ad(e)&&d.track===this.remoteAudioTrack.outMediaTrack;if(y&&Ad(o)||!y&&Ad(e))return;let S=y?o||0:e,k=(d.jitterBufferTarget||0)+100;k>S||(d.jitterBufferTarget=k,this._log.debug("set ".concat(y?"aux ":"").concat((C=d?.track)==null?void 0:C.kind," jitterBuffer delay ").concat(k," -> ").concat(S)))}),!a.find(d=>{let C=d.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:e;return d.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:a,resolve:c})},1e3)}catch(d){this._log.warn("set jitterBuffer delay error: ".concat(d)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,c()}}get audioReceiver(){var A;return((A=this.singlePC)==null?void 0:A.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};Ci([$k(),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=y=>{this.off("closed",C),d(new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.CONNECTION_ABORTED,data:y})}))};this.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this.off("closed",C)})})})],w1.prototype,"subscribe"),Ci([$k()],w1.prototype,"unsubscribe"),Ci([py(()=>"jitter")],w1.prototype,"setJitterBufferDelay");var OoA=w1,PoA=gc(Kl()),e8=class x9 extends PoA.EventEmitter{constructor(e,o){super(),this.room=e,this.signalChannel=o,Y(this,"log"),Y(this,"cmdIdSeqMap",new Map),Y(this,"messageMap",new Map),this.log=QA.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(ls.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",a=>{let{userId:c}=a;[...this.messageMap.keys()].forEach(d=>{d.split("_").slice(0,-1).join("_")===c&&this.messageMap.delete(d)})})}send(e){let{cmdId:o,data:a}=e,c=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),d={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(a))),ordered:!0,reliable:!0,streamSeq:c};this.cmdIdSeqMap.set(o,c+1),this.signalChannel.send(noA,d),this.log.debug("send custom msg: ".concat(JSON.stringify(d)))}onReceiveMsg(e){let{data:o}=e.data,a=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(a){let c={userId:a,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),d=>d.charCodeAt(0)).buffer};if(o.ordered){let d="".concat(a,"_").concat(c.cmdId),C=this.messageMap.get(d);if(C&&C.lastSeq!==0)if(Math.abs(C.lastSeq-c.seq)>x9.SEQ_INTERVAL)this.messageMap.set(d,{lastSeq:c.seq,cachedMessageMap:new Map}),this.emitMessage(c);else if(c.seq>C.lastSeq){if(c.seq===C.lastSeq+1)this.emitMessage(c);else if(!C.cachedMessageMap.has(c.seq)){let y=setTimeout(()=>this.emitMessage(c,!0),5e3);C.cachedMessageMap.set(c.seq,{message:c,timeoutId:y})}}else this.log.debug("drop message ".concat(c.userId,"-").concat(c.cmdId,"-").concat(c.seq));else C||(C={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(d,C),setTimeout(()=>this.emitMessage(c,!0),100)),C.cachedMessageMap.set(c.seq,{message:c})}else this.emit("message",c)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let c=d=>{d.tinyId===o.srcTinyId&&(this.room.off("peer-join",c),this.onReceiveMsg(e))};this.room.on("peer-join",c),LC(2e3).then(()=>this.room.off("peer-join",c))}}emitMessage(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var a;let c=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),d=e;if(c){if(o){let y=[...c.cachedMessageMap.values()].sort((S,k)=>S.message.seq-k.message.seq);y[0]&&(d=y[0].message)}c.lastSeq!==0&&d.seq-c.lastSeq>1&&this.log.debug("msg lost userId: ".concat(d.userId," seq: ").concat(c.lastSeq," -> ").concat(d.seq)),c.lastSeq=d.seq,clearTimeout((a=c.cachedMessageMap.get(d.seq))==null?void 0:a.timeoutId),c.cachedMessageMap.delete(d.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(d))),this.emit("message",d);let C=c?.cachedMessageMap.get(d.seq+1);C&&this.emitMessage(C.message)}};Y(e8,"SEQ_INTERVAL",300);var xoA=e8,{isString:t8,isUndefined:Av,getNetworkType:YoA,isEmpty:VoA}=Hd,wy=class extends RoA{constructor(A){super(A),Y(this,"_businessInfo"),Y(this,"userManager"),Y(this,"_version"),Y(this,"_heartbeat",-1),Y(this,"_lastHeartBeatTime",-1),Y(this,"_stats"),Y(this,"_joinTimeout",-1),Y(this,"_firstPublishedList",null),Y(this,"_joinReject",null),Y(this,"_isRelayChanged",!1),Y(this,"sdpSemantics"),Y(this,"signalChannel",null),Y(this,"uplinkConnection",null),Y(this,"singlePC",null),Y(this,"enableSPC",GM),Y(this,"_changeBigSmallRecords",new Map),Y(this,"networkQuality"),Y(this,"_iceTransportPolicy"),Y(this,"forceRelay",!1),Y(this,"_turnServers",[]),Y(this,"_iceServersFromJoin"),Y(this,"_syncUserListInterval",-1),Y(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Y(this,"enableSEI",!1),Y(this,"_enableAudioVolumeEvaluation",!1),Y(this,"_audioVolumeIntervalId",0),Y(this,"_enableMultiAuxStream",!1),Y(this,"_pureAudioPushMode",!1),Y(this,"_customMessageManager"),Y(this,"_enableDataChannel",!1),Y(this,"preferHW",!1),Y(this,"healthDetector"),Y(this,"playoutDelay"),Y(this,"jitterBufferDelay"),Y(this,"_updateAudioLevelTaskId",-1),Y(this,"switchRoomSubedReq"),Y(this,"resolveSwitchRoomSubedReq"),Y(this,"enableVolumeControlInIOS"),Y(this,"capturedLocalMainAudioTrack"),Y(this,"capturedLocalMainVideoTrack"),Y(this,"capturedLocalAuxVideoTrack"),Y(this,"PRELINK_EXPIRED_TIME",3e5),Y(this,"PRELINK_TIMEOUT",1e4),Y(this,"prelinkTimeoutId",null),Y(this,"firewallDetector"),this.firewallDetector=new ciA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new uoA(this,this._log),this.userManager=new aiA(this.userId,this._log),this._version=qd,this.sdpSemantics=l0,Av(A.sdpSemantics)?te.isUnifiedPlanDefault()&&(this.sdpSemantics=zS):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(YoA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!Av(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&GM,!Av(A.enableSPC)&&GM&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new boA(this)}get isMainStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isMainStreamPublished)}get isMainAudioPublished(){var A;return!((A=this.uplinkConnection)==null||!A.localMainAudioTrack)}get isAuxStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(A=>A.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(A=>[A.tinyId,A.userId]))}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get downlinkVideoCodec(){var A;return((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}join(A,e,o){return KA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",a=>{this.emit("peer-join",a)}),this.userManager.on("8",a=>{this.emit("asr-robot-peer-join",a)}),this.userManager.on("9",a=>{this.emit("asr-robot-peer-leave",a)}),this.userManager.on("2",a=>{let{userId:c,reason:d}=a;this.closeDownLinkConnection(c,"remote user exitRoom"),this.emit("peer-leave",{userId:c,reason:d})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var c=yx(a,[]);F.emit(nA.REMOTE_PUBLISH_STATE_CHANGED,mi({room:this},c)),this.emit("remote-publish-state-changed",mi({},c))}),this.joinParams=A,Nr(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((a,c)=>KA(this,null,function*(){var d,C;this._joinReject=c;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(S){if(!(S instanceof ai&&S.code===dt.SPC_INITIALIZED_FAILED))return c(S);(d=this.signalChannel)==null||d.destroy(),yield this.initialize()}let y=ko();yield this.doJoin(A,(C=this.singlePC)==null?void 0:C.clientAbility),ii.addSuccessEvent({key:521708,cost:ko()-y}),a(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(y){ii.addFailedEvent({key:521708,error:y}),c(y)}this._joinReject=null}))})}initSinglePC(){return KA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new Ry({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),this.singlePC.on("sei-message",A=>this.emit("sei-message",A)),this.singlePC.on("dump",A=>this.emit("dump",A)),this.singlePC.once("error",()=>this.fallbackToMPC()),this.singlePC.on("data_channel_msg",A=>{let e=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(e)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new ai({code:dt.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,e){return new Promise((o,a)=>KA(this,null,function*(){var c,d,C,y,S,k,V,J;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(p1,MA=>{this.clearJoinTimeout(),F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this,error:MA}),a(MA)}),Nr((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&GM&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((y=(C=this.scheduleResult)==null?void 0:C.config)!=null&&y.jitterDelay)&&!((k=(S=this.scheduleResult)==null?void 0:S.config)!=null&&k.jitterDelayAux)||!uQ)&&e&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),e.playoutDelay=this.playoutDelay);let gA={roomId:String(A.roomId||A.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:A.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cn(),netType:qf(),bussinessInfo:this._businessInfo,ability:e,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&$0(),transcription:this._enableDataChannel,downUseVp8:((V=this.scheduleResult.config)==null?void 0:V.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(gA)));let CA=5e3;(J=this.scheduleResult.config)!=null&&J.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(CA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{a(new ai({code:dt.JOIN_ROOM_FAILED,message:Xo({key:Mo.JOIN_ROOM_TIMEOUT})}))},CA),F.emit(nA.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?ioA:YiA,gA),this.signalChannel.once(ls.JOIN_ROOM_RESULT,MA=>KA(this,null,function*(){this.clearJoinTimeout();let{code:$A,message:Be,data:Ye,tinyId:ve}=MA.data;F.emit(nA.JOIN_RECEIVED_CMD_RES,{room:this,code:$A}),$A===0?(this._log.info("Join room success, start heartbeat"),ve&&(this.tinyId=ve),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=Ye.publishers,this._iceServersFromJoin=Ye.iceServer?[Ye.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var yi;(yi=this.singlePC)==null||yi.connect(Qo(mi({},Ye.ability),{useVp8:Ye.ability.useVp8||!!A.useVp8,useH265:Ye.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat($A," error: ").concat(Be)),a(new ai({code:dt.JOIN_ROOM_FAILED,extraCode:$A,message:Xo({key:Mo.JOIN_ROOM_FAILED,data:{error:Be,code:$A}})})))}))}))}reJoin(){return KA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,e=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,e.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),e.push(this.signalChannel.connect())),yield Promise.all(e),yield this.doJoin(Qo(mi({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),sn.logSuccessEvent({userId:this.userId,eventType:Ja.REJOIN}),this.singlePC){let o=a=>{var c;a.state==="CONNECTED"&&((c=this.singlePC)==null||c.off(p_.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof $z&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(p_.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof M1&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),sn.logFailedEvent({userId:this.userId,eventType:Ja.REJOIN,error:A}),this.emit("error",new ai({code:dt.JOIN_ROOM_FAILED,message:Xo({key:Mo.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return KA(this,null,function*(){var e,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(e=this.signalChannel)!=null&&e.isPrelinkValid(this.sdkAppId,this.userId,this.userSig))return this._log.info("reuse prelink signal channel"),void this.signalChannel.consumePrelink();(o=this.signalChannel)!=null&&o.prelink&&this.signalChannel.close();let a,{mainUrl:c,backupUrl:d}=this.getSignalChannelUrl(),C=this.signalChannel||function(S){return[...y1.values()].find(V=>V.room.userId===S&&!V.room.isJoined)||null}(this.userId),y=!!(C&&C.isConnected&&C.keepAlive&&C.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(a=this.scheduleResult.domains[0]),this._log.info("".concat(y?"reuse":"setup"," signal channel")),y?(C.url=c,C.backupUrl=d,C.room.setSignalChannel(null),C.room=this,this.signalChannel=C):(C&&C.close(),this.signalChannel=new Nz({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:c,backupUrl:d,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?a:void 0,prelink:A?.isPrelink}),this._customMessageManager=new xoA(this,this.signalChannel),this._customMessageManager.on("message",S=>{this.emit("custom-message",S)})),this.networkQuality||(this.networkQuality=new Uz({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(Uz.EVENT_NETWORK_QUALITY,S=>{var k;this.emit("network-quality",S),(k=this.singlePC)==null||k.detectTCPAndUDP(S)})),rd(this,this.signalChannel).add(dj,S=>{F.emit(nA.SIGNAL_CONNECTION_STATE_CHANGED,mi({room:this},S)),this.emit("signal-connection-state-changed",S)}).add(OiA,S=>{this.reset(),this.emit("error",S)}).add(ls.PEER_JOIN,S=>{let{srcTinyId:k,userId:V,role:J,fromType:gA}=S.data.data;this.userManager.addUser({userId:V,tinyId:k,role:J,fromType:gA})}).add(ls.PEER_LEAVE,S=>{let{userId:k,reason:V=0}=S.data.data;this.userManager.deleteUser(k,V)}).add(ls.UPDATE_REMOTE_MUTE_STAT,S=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(S.data)}).add(ls.CLIENT_BANNED,S=>{let k=S.data.data,{reason:V}=k;if(sn.uploadEvent({log:"stat-banned:".concat(V),userId:this.userId}),V==="user_time_out")return this._log.warn("".concat(V," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[V==="kick"?"error":"info"]("user was banned because of [".concat(V,"]")),this.reset(),this.emit("banned",{reason:V})}).add(ls.SEND_SWITCH_ROOM_SUBED_REQ,S=>{if(!this.singlePC)return;let{subList:k}=S.data.data;this._log.info("auto subscribe ".concat(zd(k,{keysToInclude:["userId"]}))),k.forEach(V=>{this.singlePC.autoSubscribedUserMap.set(V.userId,V)}),this.resolveSwitchRoomSubedReq()}).add(ls.FALLBACK_CODEC,S=>KA(this,null,function*(){var k,V,J,gA,CA;let MA=S.data.data;((k=MA.videoControlInfo)==null?void 0:k.enableH265Enc)===0&&((V=this.singlePC)==null?void 0:V.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((J=MA.videoControlInfo)==null?void 0:J.enableH265Enc)),ii.addCount({key:513e3}),yield(gA=this.singlePC)==null?void 0:gA.switchVideoEncoder("h264"),yield(CA=this.uplinkConnection)==null?void 0:CA.sendMediaSettings())})),this.signalChannel.once(Dz,S=>{this.tinyId=S.signalInfo.tinyId,F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this})}),F.emit(nA.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),y&&F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this}),y})}setSignalChannel(A){this.signalChannel=A,A||kn(this)}leave(){return KA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),F.emit(nA.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(ViA),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(A=>{this.closeDownLinkConnection(A.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Gr.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Gr.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return KA(this,null,function*(){var A;let e=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let a=(A=this.signalChannel)!=null&&A.isConnected?function(d){if(u_.has(d)){let C=u_.get(d).map(y=>({uint32_event_id:y.eventId,uint64_date:y.timestamp,str_userid:y.remoteUserId,uint32_param1:y.param1,uint32_param2:y.param2,uint32_video_stream_type:y.streamType}));return u_.delete(d),C}return[]}(this.userId):[],c=Qo(mi({str_sdk_version:t0,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:a,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:mi({uint32_terminal_type:15,str_device_name:rQ(),str_os_version:"",uint32_net_type:qf()},o.msg_device_info)});if(this.heartbeatReport=c,this.heartbeatCount++,F.emit(nA.HEARTBEAT_REPORT,{room:this,report:c}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(JiA,c);let d=Date.now();this._lastHeartBeatTime>0&&d-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(d-this._lastHeartBeatTime)),this._lastHeartBeatTime=d,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",Qo(mi({},c),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(A){if(!this.isJoined)return;let e=!1,o=A.data.userList||[],a=A.data.mixRobotList||[],c=[];for(let C of o){if(C.flag===vb)continue;let{userId:y,srcTinyId:S,flag:k,fromType:V}=C;y===this.userId&&(e=!0,this.uplinkConnection&&(this.uplinkConnection.flag=k),this.localPublishFlag!==k&&(this.localPublishFlag=k,this.emit("local-publish-flag-changed",k))),c.push({userId:y,tinyId:S,flag:k,fromType:V})}let d=[...a.map(C=>{let{userId:y,srcTinyId:S,flag:k,mixUserList:V,fromType:J}=C;return{userId:y,tinyId:S,flag:k,isRobot:!0,mixUserList:V,fromType:J}}),...c];d.forEach(C=>{let{userId:y}=C,S=this.remotePublishedUserMap.get(y);S&&this.checkSubscribeBigSmallVideo(S)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,d.push(A.data.fakeMixUser)),F.emit(nA.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:d}),e||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(d)}closeUplink(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(A),A==="you exitRoom"&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof M1&&(this.uplinkConnection=null)),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:e,tinyId:o,flag:a,isRobot:c,fromType:d}=A,C=new(this.singlePC?OoA:kz)({userId:e,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:a,isRobot:c,fromType:d});this.userManager.addRemotePublishedUser(C),this.installDownlinkEvents(C,e),this.emit("remote-published",C)}closeDownLinkConnection(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(e),this.emit("remote-unpublished",o))}installDownlinkEvents(A,e){A.on("error",o=>{let a=o.getCode();a!==dt.ICE_TRANSPORT_ERROR&&(a===dt.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(e),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",Qo(mi({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Gr.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){Gr.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(A=>{this.userManager.setUserList(A)}).catch(A=>{this._log.debug("sync user list failed: ".concat(A))})}getUserList(){var A;return(A=this.signalChannel)!=null&&A.isConnected?this.signalChannel.sendWaitForResponse({command:AoA,responseCommand:ls.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(e=>{let{data:o}=e,{code:a,message:c}=o;if(a===0)return(o.data&&o.data.userList||[]).map(d=>{let{userId:C,srcTinyId:y,role:S,fromType:k}=d;return{userId:C,tinyId:y,role:S,fromType:k}});throw Xo({key:Mo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.USER_LIST_RES,code:a,message:c}})}):Promise.reject("not connected")}getAllConnections(){let A=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&A.push(this.uplinkConnection),A}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!Gz)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let e=0;e{if(e instanceof tm&&!e.getIsReconnecting()){let o=e.getPeerConnection();o&&o.connectionState===Co.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return KA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),sn.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(A=this.singlePC)==null||A.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new M1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let e of[...this.remotePublishedUserMap.values()]){let o=new kz({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(o,e.userId),this.remotePublishedUserMap.set(e.userId,o),e.isMainStreamSubscribed&&(yield o.subscribe(e.subscribeState,"main")),e.isAuxStreamSubscribed&&(yield o.subscribe(e.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),Gr.clearTask(this._audioVolumeIntervalId))}switchRole(A){return KA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let e={command:eoA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:ls.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(e.data))),this.signalChannel.sendWaitForResponseWithRetry(e).then(o=>{let{code:a,message:c}=o.data;if(a!==0)throw new ai({code:dt.SWITCH_ROLE_FAILED,message:Xo({key:Mo.SWITCH_ROLE_FAILED,data:{message:c,code:a}})});this.role=A}).catch(o=>{throw o instanceof ai&&o.getCode()===dt.API_CALL_TIMEOUT&&(o=new ai({code:dt.SWITCH_ROLE_FAILED,message:Xo({key:Mo.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return KA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===d0);this._log.info("subscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>KA(this,null,function*(){try{yield e.subscribe(Qo(mi({},e.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",e.userId,o)}})))})}unsubscribeDataChannel(){return KA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===d0);this._log.info("unsubscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new $z({userId:this.userId,tinyId:this.tinyId,room:this}):new M1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",A=>{this.emit("media-connection-state-changed",Qo(mi({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let e=A.getCode();e!==dt.ICE_TRANSPORT_ERROR&&(e===dt.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return KA(this,null,function*(){var e;this.uplinkConnection||this._initUplinkConnection();let o="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("publish() => ".concat(o)),yield(e=this.singlePC)==null?void 0:e.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof HM?A:null,localVideoTrack:A instanceof dQ?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return KA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let e="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(e)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof HM?A:null,localVideoTrack:A instanceof dQ?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let e=this.uplinkConnection.addTrack(A);return A.publish(this,e),e}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&b2()?this.uplinkConnection.replaceTrack(A).then(e=>{e&&F.emit(nA.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return KA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return KA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:YA.VIDEO,videoType:YA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,e=new Array(A),o=0;o!C.isSubscribed),e.length===0)return;let{userId:a}=e[0],c=this.remotePublishedUserMap.get(a);if(!c)return;let d=e.find(C=>C.mediaType===2)?"auxiliary":"main";try{let C=mi({},c.subscribeState);e.forEach(S=>{switch(S.mediaType){case 1:C.audio=!0;break;case 4:C.video=!0;break;case 8:C.smallVideo=!0;break;case 2:C.auxiliary=!0}});let y=this._changeBigSmallRecords.get(a);y&&y.options.smallVideo&&c.muteState.hasSmall&&C.video&&(C.video=!1,C.smallVideo=!0),F.emit(nA.SUBSCRIBE_START,{room:this,streamType:d,remotePublishedUser:c,subscribeState:C}),this._log.info("subscribe() => ".concat(a," ").concat(d," ").concat(e.map(S=>S.strMediaType).join(",")," [").concat(pj(C),"] prev: [").concat(pj(c.subscribeState),"]")),yield c.subscribe(C,d),this._log.info("subscribe ".concat(a," ").concat(d," done"));for(let S of e)S.mediaTrack||(yield S.waitHasMediaTrack());F.emit(nA.SUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:c})}catch(C){let y=C instanceof ai?C.getCode():dt.UNKNOWN,S=C;throw C instanceof ai?y===dt.REMOTE_STREAM_NOT_EXIST&&(S=new ai({code:dt.API_CALL_ABORTED,message:Xo({key:Mo.API_CALL_ABORTED,data:{message:C.message,userId:a,streamType:d}})}),this._log.warn(S)):(S=new ai({code:y,message:Xo({key:Mo.SUBSCRIBE_FAILED,data:{message:C.message,userId:a,streamType:d}})}),this._log.error(S)),S}})}unsubscribe(){for(var A=arguments.length,e=new Array(A),o=0;oC.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(a," ").concat(d," ").concat(e.map(C=>C.strMediaType).join(",")));try{yield c.unsubscribe({remoteTracks:e,streamType:d})}catch(C){this._log.warn("unsubscribe() => failed ".concat(C))}e.forEach(C=>{C.unsubscribe(),C.mediaType===8&&C.setMediaType(4)}),F.emit(nA.UNSUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:c})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,e=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void Gr.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),F.emit(nA.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&Gr.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Gr.run("intervalInWorker",()=>{var o;H2.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,e);let a=[];(o=this.remotePublishedUserMap)==null||o.forEach(c=>{if(c.muteState.hasAudio){!H2.isRunning&&c.muteState.audioAvailable&&c.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(c):c.remoteAudioTrack.volume=0;let d=Math.floor(100*c.remoteAudioTrack.getAudioLevel());a.push({userId:c.userId,volume:d,floatVolume:c.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",a)},{delay:A,backgroundTask:e})}updateAudioLevelFromSenderStat(A,e){return KA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let a=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!a)return;let c=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(c)),this._updateAudioLevelTaskId=Gr.run("intervalInWorker",()=>KA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let d=yield a.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:C}=this.uplinkConnection;d.forEach(y=>{y.type==="media-source"&&y.audioLevel&&(C.volume=y.audioLevel)})}),{delay:c,backgroundTask:e})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Gr.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var e;let{audioReceiver:o}=A;if(!Pk||!o)return;let a=(e=o.getSynchronizationSources()[0])==null?void 0:e.audioLevel;bn(a)?A.remoteAudioTrack.volume=Math.min(2*a,1):o.getStats().then(c=>{c.forEach(d=>{d.type==="inbound-rtp"&&bn(d.audioLevel)&&(A.remoteAudioTrack.volume=d.audioLevel)})})}getLocalAudioStats(){return KA(this,null,function*(){var A;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return KA(this,null,function*(){var A,e;let o={};return o[this.userId]=((e=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:e.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return KA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let e=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=e.rtt}for(let[,e]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(e);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return KA(this,null,function*(){let e={};for(let[o,a]of this.remotePublishedUserMap)A==="main"&&a.muteState.hasVideo&&(e[o]=a.remoteVideoTrack.stat),A==="auxiliary"&&a.muteState.hasAuxiliary&&(e[o]=a.remoteAuxiliaryTrack.stat);return e})}getRemoteAudioStats(){return KA(this,null,function*(){let A={};for(let[e,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[e]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,e){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(e||""));let o=[];Array.isArray(A)?A.forEach(a=>o.push(Hd.getTurnServer(a))):Hd.isPlainObject(A)&&o.push(Hd.getTurnServer(A)),this._turnServers=o,e&&(this._iceTransportPolicy=e)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:WiA,data:A,timeout:5e3,responseCommand:ls.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==dt.API_CALL_ABORTED)throw e})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:ziA,data:A,timeout:5e3,responseCommand:ls.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==dt.API_CALL_ABORTED)throw e})}sendStartPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?HiA:KiA,data:A,timeout:5e3,responseCommand:e?ls.START_PUBLISH_TENCENT_CDN_RES:ls.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==dt.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?qiA:jiA,data:A,timeout:5e3,responseCommand:e?ls.STOP_PUBLISH_TENCENT_CDN_RES:ls.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==dt.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:ZiA,data:A,timeout:5e3,responseCommand:ls.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==dt.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:XiA,data:A,timeout:5e3,responseCommand:ls.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==dt.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:$iA,data:A,timeout:5e3,responseCommand:ls.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==dt.API_CALL_ABORTED)throw e})}sendAbilityStatus(A){var e;(e=this.signalChannel)==null||e.sendWaitForResponse({command:ooA,data:A,timeout:5e3,responseCommand:ls.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var e,o;return this._turnServers.length>0?this._turnServers:(e=this.scheduleResult.iceServers)!=null&&e.length?this.scheduleResult.iceServers:A!=null&&A.length?A:(o=this._iceServersFromJoin)!=null&&o.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let A={mainUrl:"",backupUrl:""},e=Hd.getEnv();return e?(A.mainUrl="wss://".concat(Hd.getTestSignalDomain(e)),A.backupUrl=A.mainUrl):this.proxy_ws?(A.mainUrl=this.proxy_ws,A.backupUrl=A.mainUrl):this.proxy_unified?(A.mainUrl="wss://".concat(this.proxy_unified),A.backupUrl=A.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(A.mainUrl="wss://".concat(this.scheduleResult.domains[0]),A.backupUrl=A.mainUrl,this.scheduleResult.domains[1]&&(A.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),A}getSignalInfo(){var A;return((A=this.signalChannel)==null?void 0:A.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(A&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this.clearPrelinkTimeout(),this.prelinkPromise=null}prelink(A,e,o,a,c,d){return KA(this,null,function*(){var C;if(this.isJoined)throw new ai({code:dt.INVALID_OPERATION,message:"already joined room"});if(!c&&!d)throw new ai({code:dt.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((C=this.signalChannel)!=null&&C.prelink){if(this.signalChannel.isConnecting)return void this._log.warn("prelink is connecting, please wait");if(this.signalChannel.isConnected)return void this._log.warn("prelink is already connected")}return this.userId=e,this.sdkAppId=A,this.userSig=o,this.roomId=String(c||d),this.useStringRoomId=!(!d||c),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,e,o,a,c,d),new Promise((y,S)=>{this.prelinkTimeoutId=setTimeout(()=>{S(new ai({code:dt.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(y=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),y}),this.prelinkPromise})}doPrelink(A,e,o,a,c,d){return KA(this,null,function*(){var C,y,S;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Hd.getEnv()&&(yield this.schedule({sdkAppId:A,userId:e,userSig:o,roomId:c,strRoomId:d,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},a)),(C=this.scheduleResult.config)==null||!C.prelink)throw new ai({code:dt.INVALID_OPERATION,message:"prelink failed: your sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it."});yield this.initialize({isPrelink:!0}),(y=this.signalChannel)==null||y.markPrelinkConnected({sdkAppId:A,userId:e,userSig:o}),(S=this.signalChannel)==null||S.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(k){throw this._log.error("prelink failed",k),k}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return KA(this,null,function*(){var A;if(this.isJoined)throw new ai({code:dt.INVALID_OPERATION,message:"close prelink failed: has joined room"});if((A=this.signalChannel)!=null&&A.prelink){if(this.signalChannel.keepAlive)return void this._log.info("skip close prelink: use keepAlive");this.reset()}})}checkSubscribeBigSmallVideo(A){return KA(this,null,function*(){let{subscribeState:e,userId:o,muteState:{hasSmall:a,hasVideo:c}}=A;if(!a&&!c||!e.video&&!e.smallVideo)return;let d=this._changeBigSmallRecords.get(o);if(!d||d.isSubscribing||d.reSubscribeCount<=0)return;let{options:C,reSubscribeCount:y}=d;if(C.video&&e.video||C.smallVideo&&e.smallVideo&&a)return;let S={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:C.video,smallVideo:C.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!a&&S.smallVideo&&(S.video=!0,S.smallVideo=!1),S.smallVideo===e.smallVideo&&S.video===e.video)return;d.isSubscribing=!0,d.reSubscribeCount=y-1,yield A.subscribe(S,"main"),A.remoteVideoTrack.setMediaType(S.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video successfully. count ").concat(XS-d.reSubscribeCount,".")),d.isSubscribing=!1,d.reSubscribeCount=XS}catch(k){this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video failed. count ").concat(XS-d.reSubscribeCount,". reason: ").concat(k)),d.isSubscribing=!1,d.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,e){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:XS};this._changeBigSmallRecords.set(e.userId,o),this._log.info("set [".concat(e.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:e.userId,isSmall:A});let a=this.remotePublishedUserMap.get(e.userId);a&&this.checkSubscribeBigSmallVideo(a)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let e={};if(t8(A.businessInfo)&&(e=JSON.parse(A.businessInfo)),!Av(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!Av(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_USER_DEFINE_RECORDID})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!Av(A.userDefinePushArgs)){if(!(t8(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new ai({code:dt.INVALID_PARAMETER,message:Xo({key:Mo.INVALID_USER_DEFINE_PUSH_ARGS})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}VoA(e)||(this._businessInfo=JSON.stringify(e))}sendCustomMessage(A){var e;(e=this._customMessageManager)==null||e.send(A)}enableInsertableStreams(){return KA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Kp)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var e;return this.signalChannel?(e=this.signalChannel)==null?void 0:e.sendWaitForResponseWithRetry(A):Promise.reject(new ai({code:dt.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var A;return(A=this.singlePC)==null?void 0:A.scriptTransformWorker}switchRoom(A){return KA(this,null,function*(){var e;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:a,userSig:c,privateMapKey:d}=A,C=((e=this.scheduleResult.config)==null?void 0:e.autoSubscribeCount)||A?.autoSubscribeCount||1,y=String(this.useStringRoomId?a:o),S=[];for(let gA=0;gA{this.resolveSwitchRoomSubedReq=gA,LC(5e3).then(gA)}),F.emit(nA.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),V=yield this.signalChannel.sendWaitForResponse({command:roA,responseCommand:ls.SEND_SWITCH_ROOM_RES,data:k});let{code:gA,message:CA}=V.data;if(gA!==0){this._log.error("switch room failed. result: ".concat(gA," error: ").concat(CA));let MA=new ai({code:dt.SWITCH_ROOM_FAILED,extraCode:gA,message:CA});throw F.emit(nA.SWITCH_ROOM_FAILED,{room:this,error:MA}),MA}this.userSig=c,Av(d)||(this.privateMapKey=d),F.emit(nA.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:J,targetRoomId:y})}catch(gA){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=J,this.resolveSwitchRoomSubedReq(),gA}})}isSwitchRoomSupported(){var A;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((A=this.scheduleResult.config)==null?void 0:A.switchRoom)!==!0?(this._log.warn("".concat(e," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(e," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(e," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(e," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var A;(A=this.singlePC)==null||A.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let A=[];for(let e=0;e<5;e++)A.push(this.updateNTPTime());return Promise.all(A).then(e=>{var o;let a=e[0].offset,c=e[0].offset;e.forEach(y=>{a=Math.min(y.offset,a),c=Math.max(y.offset,c)});let d=Math.floor(e.reduce((y,S)=>y+S.rtt,0)/e.length),C=Math.floor(e.reduce((y,S)=>y+S.offset,0)/e.length);(c-a>30||d>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),KB(C),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:C}),this._log.debug("ntp updated offset: ".concat(C)),this.emit("ntp-time-updated")}).catch(e=>{this._log.warn("ntp updated failed: ".concat(e))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:aoA,responseCommand:ls.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(e=>{let o=Number(e.data.data.serverSendTime),a=Number(e.data.data.serverRecvTime),c=e.data.receiveTime||Date.now();return{rtt:c-A-(a-o),offset:(a-A+(o-c))/2}})}};return Ci([lc(["left",Zs.INIT],"joined"),$h({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),hQ(!0),this.reset(),e()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),e()):(this.reset(),e())}}),jr(A=>{let e=new LiA;return function(o,a,c){return KA(this,null,function*(){let d=String(o.roomId||o.strRoomId);if(this.userId=o.userId,this.sdkAppId=o.sdkAppId,this.userSig=o.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=a,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.INVALID_JOIN})});if(this.checkDestroy(),e.isJoined({userId:this.userId,roomId:d,sdkAppId:this.sdkAppId,room:this}))throw new ai({code:dt.INVALID_OPERATION,message:Xo({key:Mo.REPEAT_JOIN,data:this.userId})});e.add({room:this,roomId:d}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(d," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),F.emit(nA.JOIN_START,{room:this,roomId:d,params:o});let C=Hd.getEnv();C||(C=jB.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Uf.OLD_CLOUD_LADDER)?C=jB.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Uf.WEBRTC)&&(C=jB.WEBRTC))),sn.setConfig({env:C,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:d}),te.checkSystemRequirementsInternal(c).then(y=>{this.checkSystemResult=y,UiA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Hd.getEnv()&&(yield this.schedule(o,c));let y=yield A.call(this,o,a,c);return this.roomId=d,this._joinedTimestamp=Hd.performanceNow(),F.emit(nA.JOIN_SUCCESS,{room:this}),c===30&&!o.component&&sn.uploadEvent({log:"stat-conv-".concat(Number(Op),"-").concat(location.hostname),userId:this.userId}),y}catch(y){throw e.delete({room:this,roomId:d}),F.emit(nA.JOIN_FAILED,{room:this,error:y}),y}})}})],wy.prototype,"join"),Ci([lc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;aA.mediaType),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.outMediaTrack&&d.state==="ready"),!o.length))return;F.emit("61",{room:this});let c=A.apply(this,o);return Promise.all(o.map(d=>d.publish(this,c)))})}),$h({settings:{retries:xf,timeout:A=>Rp(A)},onError(A,e,o,a){let[c]=a;var d;(d=A.message)!=null&&d.includes("timeout")?(this._log.warn("publish ".concat(c.strMediaType," timeout"),A),e()):(this._log.error("publish ".concat(c.strMediaType," failed: ").concat(A)),o(A),F.emit(nA.PUBLISH_FAILED,{room:this}))}})],wy.prototype,"publish"),Ci([n_({fnName:"publish"}),py(A=>A.mediaType),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.unpublish()),c}),VM(function(){var A,e;this.localTracks.size===0&&LI()&&((e=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||e.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],wy.prototype,"unpublish"),Ci([r5(A=>{if(A.code!==dt.API_CALL_ABORTED)throw A}),py(A=>A.userId)],wy.prototype,"replaceTrack"),Ci([py(function(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var e=arguments.length,o=new Array(e),a=0;a!d.isSubscribed&&d.subscribe(c)),c}),$h({settings:{retries:xf,timeout:A=>Rp(A)},onError(A,e,o,a){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),e();else{let c=A?.code===dt.API_CALL_ABORTED;this._log[c?"warn":"error"]("subscribe failed ".concat(a.map(d=>d.strMediaType).join(","),": ").concat(A)),o(A),F.emit(nA.SUBSCRIBE_FAILED,{room:this,remoteTracks:a})}}})],wy.prototype,"subscribe"),Ci([n_({fnName:"subscribe",callback(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=this.remotePublishedUserMap.get(a.userId);c&&!c.isMainStreamSubscribed&&!c.isAuxStreamSubscribed&&c.close("you unsubscribed")})}}),py(function(){for(var A=arguments.length,e=new Array(A),o=0;oi in t?IV(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,OrA=(t,i)=>{for(var r in i||(i={}))J9.call(i,r)&&F3(t,r,i[r]);if(z8)for(var r of z8(i))FrA.call(i,r)&&F3(t,r,i[r]);return t},PrA=(t,i)=>function(){return i||(0,t[V9(t)[0]])((i={exports:{}}).exports,i),i.exports},xrA=(t,i,r,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of V9(i))J9.call(t,I)||I===r||IV(t,I,{get:()=>i[I],enumerable:!(l=Y9(i,I))||l.enumerable});return t},YrA=(t,i,r)=>(r=t!=null?LrA(UrA(t)):{},xrA(IV(r,"default",{value:t,enumerable:!0}),t)),P_=(t,i,r,l)=>{for(var I,h=Y9(i,r),f=t.length-1;f>=0;f--)(I=t[f])&&(h=I(i,r,h)||h);return h&&IV(i,r,h),h},pn=(t,i,r)=>F3(t,typeof i!="symbol"?i+"":i,r),VrA=PrA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,l="~";function I(){}function h(G,U,j){this.fn=G,this.context=U,this.once=j||!1}function f(G,U,j,lA,sA){if(typeof j!="function")throw new TypeError("The listener must be a function");var mA=new h(j,lA||G,sA),IA=l?l+U:U;return G._events[IA]?G._events[IA].fn?G._events[IA]=[G._events[IA],mA]:G._events[IA].push(mA):(G._events[IA]=mA,G._eventsCount++),G}function w(G,U){--G._eventsCount===0?G._events=new I:delete G._events[U]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(l=!1)),_.prototype.eventNames=function(){var G,U,j=[];if(this._eventsCount===0)return j;for(U in G=this._events)r.call(G,U)&&j.push(l?U.slice(1):U);return Object.getOwnPropertySymbols?j.concat(Object.getOwnPropertySymbols(G)):j},_.prototype.listeners=function(G){var U=l?l+G:G,j=this._events[U];if(!j)return[];if(j.fn)return[j.fn];for(var lA=0,sA=j.length,mA=new Array(sA);lA{if(!navigator.userAgent.includes("Firefox"))return t;const i=t.split(`\r -`),r=[],l=[];i.forEach(f=>{const w=f.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&r.push(f)}),r.length>1&&l.push(...r.slice(1));const I=l.map(f=>{const w=/a=rtpmap:(\d+)\s/.exec(f);return w&&w.length>1?w[1]:null}).filter(f=>f!==null),h=[];return i.forEach(f=>{let w=f;if(f.includes("a=setup")&&(w="a=setup:passive"),(f.includes("m=audio")||f.includes("m=video"))&&(w=f.split(" ").filter((_,G)=>G<3||!I.includes(_)).join(" ")),f.includes("a=fmtp")||f.includes("a=rtcp-fb")||f.includes("a=rtpmap")){const _=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(f);if(_&&_.length>1&&I.includes(_[1]))return}h.push(w)}),h.join(`\r -`)},Z8=t=>{const i=t.split(`\r -`),r=[];i.forEach(f=>{const w=f.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&r.push(f)});const l=r.map(f=>{const w=/a=rtpmap:(\d+)\s/.exec(f);return w&&w.length>1?w[1]:null}).filter(f=>f!==null),I=[];i.forEach(f=>{let w=f;if(f.includes("a=fmtp:111")&&(w=`${f};stereo=1`),f.includes("a=fmtp")){const _=/a=fmtp:(\d+)\s/.exec(f);_&&_.length>1&&l.includes(_[1])&&(w=`${f};sps-pps-idr-in-keyframe=1`)}I.push(w)});const h=I.join(`\r -`);return HrA(h)},qrA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Fj=(t=21)=>{let i="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)i+=qrA[63&r[t]];return i},N_=t=>typeof t=="function",KrA=0,jrA=1,X8=2;function WrA({retryFunction:t,settings:i,onError:r,onRetrying:l,onRetryFailed:I,onRetrySuccess:h,context:f}){return function(...w){const{retries:_=5,timeout:G=1e3}=i;let U=0,j=-1,lA=KrA;const sA=async(mA,IA)=>{const cA=f||this;try{const TA=await t.apply(cA,w);U>0&&h&&h.call(this,U),U=0,mA(TA)}catch(TA){const WA=()=>{clearTimeout(j),U=0,lA=X8,IA(TA)},ue=()=>{lA!==X8&&U<(N_(_)?_():_)?(U++,lA=jrA,N_(l)&&l.call(this,U,WA),j=window.setTimeout(()=>{j=-1,sA(mA,IA)},N_(G)?G(U):G)):(WA(),N_(I)&&I.call(this,TA))};N_(r)?r.call(this,{error:TA,retry:ue,reject:IA,retryFuncArgs:w,retriedCount:U}):ue()}};return new Promise(sA)}}var zrA=WrA,pQ=new WeakMap;function ZrA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:l}){return function(I,h,f){const w=zrA({retryFunction:f.value,settings:t,onError({error:_,retry:G,reject:U,retryFuncArgs:j}){var lA;i?i.call(this,_,()=>{var sA;(sA=pQ.get(I))!=null&&sA.has(h)?G():U(_)},U,j):(lA=pQ.get(I))!=null&&lA.has(h)?G():U(_)},onRetrying(_,G){var U;N_(r)&&r.call(this,_,G),(U=pQ.get(I))!=null&&U.has(h)&&(pQ.get(I).get(h).stopRetry=G)},onRetryFailed:l});return f.value=function(..._){const G=pQ.get(I);return G?G.set(h,{args:_}):pQ.set(I,new Map([[h,{args:_}]])),w.apply(this,_).finally(()=>{var U;return(U=pQ.get(I))==null?void 0:U.delete(h)})},f}}function XrA({fnName:t,callback:i,validateArgs:r=!0}){return function(l,I,h){const f=h.value;return h.value=function(...w){var _,G;if((_=pQ.get(l))!=null&&_.has(t)){const{stopRetry:U,args:j}=pQ.get(l).get(t);let lA=!0;if(r){for(const sA of j)if(!w.find(mA=>mA===sA)){lA=!1;break}}lA&&(i&&i.apply(this,w),U&&U(),(G=pQ.get(l))==null||G.delete(t))}return f.apply(this,w)},h}}var $rA=class{constructor(t,i){this.core=i,pn(this,"peerConnection"),pn(this,"audioTransceiver",null),pn(this,"videoTransceiver",null),pn(this,"timerId",null),pn(this,"callback",null),pn(this,"previousRawStats",null),pn(this,"_prevReportTime",0),pn(this,"_prevDecoderImplementation",""),pn(this,"_decodeMap",new Map),this.peerConnection=t,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const t=this.peerConnection.getTransceivers();for(const i of t)if(i.receiver&&i.receiver.track){const{track:r}=i.receiver;r.kind==="audio"?this.audioTransceiver=i:r.kind==="video"&&(this.videoTransceiver=i)}}start(t,i=2e3){this.stop(),this.callback=t,this.collectStats(),this.timerId=window.setInterval(()=>{this.collectStats()},i)}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.callback=null,this.previousRawStats=null,this._prevReportTime=0}async collectStats(){if(this.callback)try{const t=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),r=[];t.forEach(w=>i.has(w.type)&&r.push(w));const l=Date.now(),I=this.parseAudioStats(r),h=this.parseVideoStats(r),f=this.parseNetworkStats(r);this._prevReportTime=l,this.callback({audio:I,video:h,network:f})}catch(t){this.core.log.error("Failed to collect WebRTC stats:",t)}}getDifferenceValue(t,i){if(this.core.utils.isUndefined(t))return i;const r=(i||0)-t;return r<0?0:r}parseAudioStats(t){var i,r,l,I;const h={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const f of t){if(f.type==="inbound-rtp"&&(f.mediaType==="audio"||f.kind==="audio")){if(h.bytesReceived=f.bytesReceived||0,h.packetsReceived=f.packetsReceived||0,h.packetsLost=f.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const G=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,h.bytesReceived);h.bitrate=Math.round(8*G/this.statInterval/1e3)}const w=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,h.packetsLost),_=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.audio.packetsReceived,h.packetsReceived)+w;if(_>0&&(h.packetLossRate=Math.round(w/_*100)),this.core.utils.isUndefined(f.audioLevel)||(h.volume=f.audioLevel||0),f.jitterBufferDelay&&f.jitterBufferEmittedCount){let{jitterBufferEmittedCount:G}=f,{jitterBufferDelay:U}=f;(l=this.previousRawStats)!=null&&l.audio&&(G=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,f.jitterBufferEmittedCount),U=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,f.jitterBufferDelay)),G>0&&(h.jitterBufferDelay=Math.floor(U/G*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=f.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=f.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=h.bytesReceived,this.previousRawStats.audio.packetsReceived=h.packetsReceived,this.previousRawStats.audio.packetsLost=h.packetsLost}!this.core.utils.isUndefined(f.audioLevel)&&((I=this.audioTransceiver)!=null&&I.receiver.track)&&f.trackIdentifier===this.audioTransceiver.receiver.track.id&&(h.volume=f.audioLevel||0)}return h}parseVideoStats(t){var i,r,l,I,h;const f={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const w of t){if(w.type==="codec"&&this._decodeMap.set(w.id,w),w.type==="inbound-rtp"&&(w.mediaType==="video"||w.kind==="video")){if(f.bytesReceived=w.bytesReceived||0,f.packetsReceived=w.packetsReceived||0,f.packetsLost=w.packetsLost||0,f.framesDecoded=w.framesDecoded||0,this.core.utils.isUndefined(w.framesPerSecond)||(f.frameRate=Math.round(w.framesPerSecond)),w.decoderImplementation&&this._prevDecoderImplementation!==w.decoderImplementation){const U=this._decodeMap.get(w.codecId),j=((i=U?.mimeType)==null?void 0:i.split("/")[1])||"unknown",lA=w.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${w.decoderImplementation}(${j}) HWDecoder: ${lA}`),this._prevDecoderImplementation=w.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const U=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,f.bytesReceived);f.bitrate=Math.round(8*U/this.statInterval/1e3)}const _=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.video.packetsLost,f.packetsLost),G=this.getDifferenceValue((l=this.previousRawStats)==null?void 0:l.video.packetsReceived,f.packetsReceived)+_;if(G>0&&(f.packetLossRate=Math.round(_/G*100)),w.jitterBufferDelay&&w.jitterBufferEmittedCount){let{jitterBufferEmittedCount:U}=w,{jitterBufferDelay:j}=w;(I=this.previousRawStats)!=null&&I.video&&(U=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,w.jitterBufferEmittedCount),j=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,w.jitterBufferDelay)),U>0&&(f.jitterBufferDelay=Math.floor(j/U*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=w.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=w.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=f.bytesReceived,this.previousRawStats.video.packetsReceived=f.packetsReceived,this.previousRawStats.video.packetsLost=f.packetsLost}!this.core.utils.isUndefined(w.frameWidth)&&((h=this.videoTransceiver)!=null&&h.receiver.track)&&w.trackIdentifier===this.videoTransceiver.receiver.track.id&&(f.width=w.frameWidth,f.height=w.frameHeight)}return f}parseNetworkStats(t){const i={rtt:0};for(const r of t)if(r.type==="candidate-pair"&&(r.selected||r.state==="succeeded")&&this.core.utils.isNumber(r.currentRoundTripTime)){i.rtt=Math.floor(1e3*r.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},AaA=YrA(VrA()),$8=Symbol("instance"),k1=Symbol("cacheResult"),Oj=class{constructor(i,r,l){this.oldState=i,this.newState=r,this.action=l,this.aborted=!1}abort(i){this.aborted=!0,eU.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},Pj=class extends Error{constructor(i,r,l){super(r),this.state=i,this.message=r,this.cause=l}};function eaA(t){return typeof t=="object"&&t&&"then"in t}var AU=new Map;function L1(t,i,r={}){return(l,I,h)=>{const f=r.action||I;if(!r.context){const _=AU.get(l)||[];AU.has(l)||AU.set(l,_),_.push({from:t,to:i,action:f})}const w=h.value;h.value=function(..._){let G=this;if(r.context&&(G=XC.get(typeof r.context=="function"?r.context.call(this,..._):r.context)),G.state===i)return r.sync?G[k1]:Promise.resolve(G[k1]);G.state instanceof Oj&&G.state.action==r.abortAction&&G.state.abort(G);let U=null;Array.isArray(t)?t.length==0?G.state instanceof Oj&&G.state.abort(G):typeof G.state=="string"&&t.includes(G.state)||(U=new Pj(G._state,`${G.name} ${f} to ${i} failed: current state ${G._state} not from ${t.join("|")}`)):t!==G.state&&(U=new Pj(G._state,`${G.name} ${f} to ${i} failed: current state ${G._state} not from ${t}`));const j=cA=>{if(r.fail&&r.fail.call(this,cA),r.sync){if(r.ignoreError)return cA;throw cA}return r.ignoreError?Promise.resolve(cA):Promise.reject(cA)};if(U)return j(U);const lA=G.state,sA=new Oj(lA,i,f);eU.call(G,sA);const mA=cA=>{var TA;return G[k1]=cA,sA.aborted||(eU.call(G,i),(TA=r.success)===null||TA===void 0||TA.call(this,G[k1])),cA},IA=cA=>(eU.call(G,lA,cA),j(cA));try{const cA=w.apply(this,_);return eaA(cA)?cA.then(mA).catch(IA):r.sync?mA(cA):Promise.resolve(mA(cA))}catch(cA){return IA(new Pj(G._state,`${G.name} ${f} from ${t} to ${i} failed: ${cA}`,cA instanceof Error?cA:new Error(String(cA))))}}}}var taA=typeof window<"u"&&window.__AFSM__?(r,l)=>{window.dispatchEvent(new CustomEvent(r,{detail:l}))}:typeof importScripts<"u"?(r,l)=>{postMessage({type:r,payload:l})}:()=>{};function eU(t,i){const r=this._state;this._state=t;const l=t.toString();t&&this.emit(l,r),this.emit(XC.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var XC=class jC extends AaA.default{constructor(i,r,l){super(),this.name=i,this.groupName=r,this._state=jC.INIT,i||(i=Date.now().toString(36)),l?Object.setPrototypeOf(this,l):l=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const I=l[$8];I?this.name=I.name+"-"+I.count++:l[$8]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=AU.get(i)||[];let l=new Set,I=[],h=[];const f=new Set,w=Object.getPrototypeOf(i);AU.has(w)&&(w.stateDiagram.forEach(G=>l.add(G)),w.allStates.forEach(G=>f.add(G))),r.forEach(({from:G,to:U,action:j})=>{typeof G=="string"?I.push({from:G,to:U,action:j}):G.length?G.forEach(lA=>{I.push({from:lA,to:U,action:j})}):h.push({to:U,action:j})}),I.forEach(({from:G,to:U,action:j})=>{f.add(G),f.add(U),f.add(j+"ing"),l.add(`${G} --> ${j}ing : ${j}`),l.add(`${j}ing --> ${U} : ${j} 🟢`),l.add(`${j}ing --> ${G} : ${j} 🔴`)}),h.forEach(({to:G,action:U})=>{l.add(`${U}ing --> ${G} : ${U} 🟢`),f.forEach(j=>{j!==G&&l.add(`${j} --> ${U}ing : ${U}`)})});const _=[...l];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:f}}),_}static get(i){let r;return typeof i=="string"?(r=jC.instances.get(i),r||jC.instances.set(i,r=new jC(i,void 0,Object.create(jC.prototype)))):(r=jC.instances2.get(i),r||jC.instances2.set(i,r=new jC(i.constructor.name,void 0,Object.create(jC.prototype)))),r}static getState(i){var r;return(r=jC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){taA(jC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){eU.call(this,i)}};XC.STATECHANGED="stateChanged",XC.UPDATEAFSM="updateAFSM",XC.INIT="[*]",XC.ON="on",XC.OFF="off",XC.instances=new Map,XC.instances2=new WeakMap;var LL=class extends XC{constructor(i,r){super(),this.core=i,pn(this,"audioPlayer"),pn(this,"videoPlayer"),pn(this,"callback"),pn(this,"avPlayerStateSyncManager"),pn(this,"_log"),pn(this,"_videoPlayerLog"),pn(this,"_audioPlayerLog"),pn(this,"lastPausedReason"),pn(this,"muted",!1),this._log=r,this._videoPlayerLog=this._log.createChild({id:"vp"}),this._audioPlayerLog=this._log.createChild({id:"ap"}),this.videoPlayer=new i.VideoPlayer({id:"vp",log:this._videoPlayerLog,track:null,muted:!1,container:null,enableLogTrackState:!0}),this.audioPlayer=new i.RemoteAudioPlayer({id:"ap",log:this._audioPlayerLog,track:null,muted:!1,container:null,enableVolumeControlInIOS:!0,enableLogTrackState:!0}),this.audioPlayer.on(i.PlayerEvent.AUTOPLAY_FAILED,l=>this.handleAutoPlayFailed(this.audioPlayer,l)),this.videoPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("video")),this.audioPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("audio")),this.videoPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.audioPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.videoPlayer.on(i.PlayerEvent.ENTER_PICTURE_IN_PICTURE,this.handleEnterPictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.ENTER_FULL_SCREEN,this.handleEnterFullScreen,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.avPlayerStateSyncManager=new i.AVPlayerStateSyncManager({log:this._log,audioPlayer:this.audioPlayer,videoPlayer:this.videoPlayer})}get isPlaying(){return this.videoPlayer.isPlaying&&this.audioPlayer.isPlaying}get isPaused(){return this.videoPlayer.isPaused&&this.audioPlayer.isPaused}get isStopped(){return this.videoPlayer.isStopped&&this.audioPlayer.isStopped}setCallback(i){this.callback=i}updateLogConfig(i){this._audioPlayerLog.setSdkAppId(i.sdkAppId),this._audioPlayerLog.setUserId(i.userId),this._videoPlayerLog.setSdkAppId(i.sdkAppId),this._videoPlayerLog.setUserId(i.userId)}handleLoadStart(i){this.onLoadStart()}handlePlayerStateChanged(i){i.state==="PLAYING"&&this.isPlaying&&this.onPlaying(),i.state==="PAUSED"&&this.isPaused&&this.onPaused(i.reason),i.state==="STOPPED"&&this.isStopped&&this.onStopped()}async handleEnterPictureInPicture(){var i,r;await this.videoPlayer.enterPIPPromise,(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,r;(r=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||r.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,r;(r=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||r.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const r=document.getElementById(i);r&&this.videoPlayer.setContainer(r)}else this.videoPlayer.setContainer(i)}setVolume(i){this.core.utils.isUndefined(i)||this.audioPlayer.setVolume(i/100)}setMuted(i){this.core.utils.isUndefined(i)||(this.muted=i,this.audioPlayer.setMuted(i))}setFillMode(i){i&&this.videoPlayer.setObjectFit(i)}setAudioTrack(i){this.audioPlayer.setTrack(i)}setVideoTrack(i){this.videoPlayer.setTrack(i)}async play(){const i=this.videoPlayer.play().catch(l=>{this.handleAutoPlayFailed(this.videoPlayer,l,"video")}),r=this.audioPlayer.play().catch(l=>{this.handleAutoPlayFailed(this.audioPlayer,l)});await Promise.all([i,r])}handleAutoPlayFailed(i,r,l="audio"){var I,h;this._log.warn("handleAutoPlayFailed",r);const f=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",f,!0)})};document.addEventListener("click",f,!0),(h=(I=this.callback)==null?void 0:I.onAutoPlayFailed)==null||h.call(I,{type:l,resume:()=>i.resume()})}pause(){this.videoPlayer.pause(!0),this.audioPlayer.setMuted(!0),this.audioPlayer.pause()}resume(){this.videoPlayer.resume(!0),this.audioPlayer.setMuted(this.muted),this.audioPlayer.resume()}async enterFullscreen(){await this.videoPlayer.enterFullscreen()}async exitFullscreen(){await this.videoPlayer.exitFullscreen()}async enterPictureInPicture(){await this.videoPlayer.enterPictureInPicture()}async exitPictureInPicture(){await this.videoPlayer.exitPictureInPicture()}stop(){this.videoPlayer&&this.videoPlayer.stop(),this.audioPlayer&&(this.audioPlayer.stop(),this.audioPlayer.setMuted(!1))}};P_([L1([XC.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onLoadStart)==null||i.call(t)},fail(t){this._log.warn("onLoadStart",t)}})],LL.prototype,"onLoadStart"),P_([L1(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPlaying)==null||i.call(t)},fail(t){this._log.warn("onPlaying",t)}})],LL.prototype,"onPlaying"),P_([L1("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPaused)==null||i.call(t,{reason:this.lastPausedReason})},fail(t){this._log.warn("onPaused",t)}})],LL.prototype,"onPaused"),P_([L1([],XC.INIT,{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onStopped)==null||i.call(t)},fail(t){this._log.warn("onStopped",t)}})],LL.prototype,"onStopped");var AZ=LL,iaA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],sY=class H9{constructor(i){this.core=i,pn(this,"_sdkAppId"),pn(this,"_userId"),pn(this,"connectedRoomIdSet",new Set),pn(this,"updateSeq",0),pn(this,"_log"),pn(this,"player"),pn(this,"peerConnection"),pn(this,"svrSig"),pn(this,"streamURL"),pn(this,"signalURL"),pn(this,"insertableStreamsAbortMap",new Map),pn(this,"scriptTransformWorker"),pn(this,"connectionState","disconnected"),pn(this,"isStarted",!1),pn(this,"isStopped",!0),pn(this,"isReconnecting",!1),pn(this,"callback"),pn(this,"isFireWallErrorEmitted",!1),pn(this,"stat"),pn(this,"isH264DecodeSupported"),pn(this,"connectionTimeoutId"),pn(this,"streamHealthCheckTimeoutId"),pn(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new AZ(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return H9.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return JrA;case"update":case"stop":return{}}}get enableSEI(){return this.core.room.enableSEI&&(this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED||this.core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)}wrapCallback(i){if(!i)return;const r={},l=["onStats","onSEIMessage"];for(const I of Object.keys(i)){const h=i[I];typeof h=="function"&&(l.includes(I)?r[I]=h:r[I]=(...f)=>(this._log.debug(`callback ${I} called`,f.length>0?f[0]:""),h(...f)))}return r}async start(i){var r;this.isStopped=!1;const{view:l,url:I,volume:h,muted:f,fillMode:w,loggerConfig:_,callback:G}=i;this.callback=this.wrapCallback(G),this.player.setCallback(this.callback);const{errorModule:{RtcError:U,ErrorCode:j,ErrorCodeDictionary:lA},loggerManager:sA,rtcDectection:mA}=this.core;if(this._sdkAppId=_.sdkAppId,this._userId=_.userId,this._log.setSdkAppId(_.sdkAppId),this._log.setUserId(_.userId),this.player.updateLogConfig(_),sA.addJoinedUser(_),!mA.isWebRTCSupported()||!mA.isAddTransceiverSupported())throw new U({code:j.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await mA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new U({code:j.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!mA.IS_SEI_SUPPORTED&&G?.onSEIMessage&&((r=G.onError)==null||r.call(G,new U({code:j.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(l),this.player.setMuted(f),this.player.setFillMode(w);try{await this.connect(I),this.stat=new $rA(this.peerConnection,this.core),this.stat.start(TA=>{var WA,ue;return(ue=(WA=this.callback)==null?void 0:WA.onStats)==null?void 0:ue.call(WA,TA)});const IA=this.player.play();this.player.setVolume(h);const cA=this.createStreamHealthCheckPromise();await Promise.race([IA,cA]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(IA){throw this.stop(),IA}}async update(i){const{view:r,url:l,volume:I,muted:h,fillMode:f,action:w,fullScreen:_,pictureInPicture:G}=i;l&&l!==this.streamURL&&await this.switchStream(l),this.player.setMuted(h),this.player.setVolume(I),this.player.setFillMode(f),r&&this.player.videoPlayer.setContainer(this.core.utils.isString(r)?document.getElementById(r):r),w==="pause"?this.player.pause():w==="resume"&&this.player.resume(),this.core.utils.isBoolean(_)&&(_?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(G)&&(G?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const r=this.peerConnection,l=this.streamURL,I=this.signalURL,h=this.svrSig,f=new Map(this.insertableStreamsAbortMap),w=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const _=new AZ(this.core,this._log);_.setVideoContainer(w.videoPlayer.container),_.setFillMode(w.videoPlayer.objectFit),_.setMuted(w.muted),_.setCallback(this.callback);const G=U=>{const{track:j}=U;this.createEncodedStreams(U.receiver),this.initReceiverTransform(U.receiver,j.kind==="audio"),j.kind==="audio"?_.setAudioTrack(j):_.setVideoTrack(j)};try{await this.connectForSwitch(i,G),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(_),this._log.info("switchStream: new stream first frame received"),w.audioPlayer.setMuted(!0),w.stop(),this.player=_,r&&(clearTimeout(this.connectionTimeoutId),r.close(),r.getReceivers().forEach(U=>f.delete(U)),l&&h&&I&&this.fetchStopStreamWithParams(l,I,h).catch(U=>{this._log.warn("switchStream: stop old stream failed",U)})),this._log.info("switchStream: switch completed successfully")}catch(U){this._log.error("switchStream failed",U),_.stop();const j=this.peerConnection;throw j&&(j.close(),j.getReceivers().forEach(lA=>this.insertableStreamsAbortMap.delete(lA))),this.peerConnection=r,this.streamURL=l,this.signalURL=I,this.svrSig=h,this.insertableStreamsAbortMap=f,this.player=w,w.audioPlayer.setMuted(w.muted),U}}waitForNewPlayerFirstFrame(i){return new Promise((r,l)=>{let I=0,h=!1;const f=i.videoPlayer.getElement();if(!f)return void l(new Error("VideoPlayer has no video element"));const w=()=>{h=!0,clearInterval(U),f.removeEventListener("loadeddata",_),f.removeEventListener("playing",G)},_=()=>{h||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),w(),r())},G=()=>{h||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),w(),r())};f.addEventListener("loadeddata",_,{once:!0}),f.addEventListener("playing",G,{once:!0}),i.play().catch(j=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",j)});const U=setInterval(()=>{if(!h){if(I+=100,f.videoWidth>0&&f.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${f.videoWidth}x${f.videoHeight}`),w(),void r();I>=1e4&&(w(),l(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,r){return new Promise((l,I)=>{try{this.initScriptTransformWorker();const h={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},f=new RTCPeerConnection(h);this.peerConnection=f,f.onconnectionstatechange=()=>{this.connectionState=f.connectionState,this._log.info("connectForSwitch connectionState",f.connectionState),f.connectionState!=="failed"&&f.connectionState!=="closed"||I(new Error(`connection is ${f.connectionState}`)),f.connectionState==="connected"&&(this.logSelectedCandidate(),l())},f.ontrack=r,f.addTransceiver("audio",{direction:"recvonly"}),f.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),f.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(w=>(w.sdp=Z8(w.sdp),this._log.info("connectForSwitch setOffer"),f.setLocalDescription(w))).then(()=>{const w={sessionId:Fj(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:f.localDescription};return this.exchangeSDP(i,w)}).then(w=>(this._log.info("connectForSwitch setAnswer"),f.setRemoteDescription(w))).catch(I)}catch(h){I(h)}this.connectionTimeoutId=setTimeout(()=>I(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,r,l){try{const I=`${r}/webrtc/v1/stopstream`,h=await U1(I,{streamurl:i,svrsig:l},{timeout:3}),{errcode:f,errmsg:w}=h;if(f!==0)throw new Error(`errCode:${f}, errmsg:${w}`);return h}catch(I){this._log.error("fetchStopStreamWithParams error",I)}}async stop(){this.isStopped=!0,this.clearStreamHealthCheck(),this.player.stop(),this.peerConnection&&(clearTimeout(this.connectionTimeoutId),this.peerConnection.close(),this.peerConnection.getReceivers().forEach(i=>this.insertableStreamsAbortMap.delete(i)),delete this.peerConnection,await this.fetchStopStream(),delete this.streamURL,delete this.signalURL,delete this.svrSig),this.stat&&(this.stat.stop(),delete this.stat),this.core.room.keyPointManager.uploadKVStat(this.core.kvStatManager,this._sdkAppId)}destroy(){this.stop(),this.core.innerEmitter.off(this.core.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}createStreamHealthCheckPromise(){return new Promise((i,r)=>{this.streamHealthCheckReject=r,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(r),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const r=this.peerConnection.getReceivers().find(j=>{var lA;return((lA=j.track)==null?void 0:lA.kind)==="video"});if(!r)return void this._log.warn("checkStreamHealth: no video receiver found");const l=await r.getStats();let I=0,h=0;l.forEach(j=>{j.type==="inbound-rtp"&&(j.mediaType==="video"||j.kind==="video")&&(I=j.bytesReceived||0,h=j.framesDecoded||0)});const{isPlaying:f}=this.player,w=f||h>0;this._log.info(`checkStreamHealth: bytesReceived=${I}, framesDecoded=${h}, isPlaying=${f}`);const{RtcError:_,ErrorCode:G,ErrorCodeDictionary:U}=this.core.errorModule;I===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new _({code:G.OPERATION_FAILED,message:"no stream data received"}))):w||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new _({code:G.ENV_NOT_SUPPORTED,extraCode:U.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(r){this._log.warn("checkStreamHealth error",r)}}connect(i){return new Promise((r,l)=>{try{this.initScriptTransformWorker();const I={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},h=new RTCPeerConnection(I);this.peerConnection=h,h.onconnectionstatechange=()=>{this.connectionState=h.connectionState,this._log.info("connectionState",h.connectionState),h.connectionState!=="failed"&&h.connectionState!=="closed"||(this.isStarted?this.reconnect(i):l(new Error(`connection is ${h.connectionState}`))),h.connectionState==="connected"&&(this.logSelectedCandidate(),r())},h.ontrack=f=>this.onTrack(f),h.addTransceiver("audio",{direction:"recvonly"}),h.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),h.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(f=>(f.sdp=Z8(f.sdp),this._log.info("setOffer"),h.setLocalDescription(f))).then(()=>{const f={sessionId:Fj(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:h.localDescription};return this.exchangeSDP(i,f)}).then(f=>(this._log.info("setAnswer"),h.setRemoteDescription(f))).catch(l)}catch(I){l(I)}this.connectionTimeoutId=setTimeout(()=>l(new Error("connection timeout")),1e4)})}async exchangeSDP(i,r){let l,I,h;try{this._log.info("exchangeSDP");const f=oaA(i);if(!f)throw new Error("streamDomain is empty");const{signalDomain:w,cached:_}=await this.fetchSignalDomain(f);if(!w)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",w,_);const G=await this.doExchangeSDP(`https://${w}`,r,3);l=G.url,I=G.remoteSdp,h=G.svrSig}}catch(f){this._log.warn("exchangeSDP failed, fallback",f);try{const w=await this.core.utils.promiseAny(iaA.map(_=>this.doExchangeSDP(`https://${_}`,r,3)));l=w.url,I=w.remoteSdp,h=w.svrSig}catch(w){throw this._log.error("exchangeSDP failed",w),w[0]||w}}return this.streamURL=i,this.signalURL=l,this.svrSig=h,I}async reconnect(i){var r,l;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(I){this._log.error("reconnect error",I);const{RtcError:h,ErrorCode:f}=this.core.errorModule;(l=(r=this.callback)==null?void 0:r.onError)==null||l.call(r,new h({code:f.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[r,l]of i)if(this.core.rtcDectection.isSelectedCandidatePair(l)){const I=i.get(l.localCandidateId),h=i.get(l.remoteCandidateId);I&&this._log.info(`local candidate: ${I.candidateType} ${I.protocol}:${I.ip||I.address}:${I.port} ${I.networkType||""} ${I.relayProtocol?`relayProtocol:${I.relayProtocol} url: ${I.url}`:""}`),h&&this._log.info(`remote candidate: ${h.candidateType} ${h.protocol}:${h.ip||h.address}:${h.port}`);break}}async doExchangeSDP(i,r,l){const I=`${i}/webrtc/v1/pullstream`,h=await U1(I,r,{timeout:l}),{errcode:f,errmsg:w,remotesdp:_,svrsig:G}=h;if(f!==0){const U=new Error(`errCode:${f}, errMsg:${w}`);throw U.name="RequestSignalError",U}return{url:i,remoteSdp:_,svrSig:G}}createEncodedStreams(i){var r;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const l=i.createEncodedStreams(),I=new AbortController,h={abortController:I,enqueue:f=>i.track.kind==="audio"?f:this.decodeVideoFrame(f)};l.readable.pipeThrough(new TransformStream({transform:(f,w)=>{const _=h.enqueue(f);_&&w.enqueue(_)}})).pipeTo(l.writable,I).catch(f=>{f!=="destroy"&&this._log.warn(f)}),(r=this.insertableStreamsAbortMap.get(i))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(i,I)}}catch(l){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,l)}}initReceiverTransform(i,r){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:r,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:r,createScriptTransformWorker:l,trtc:I,TRTC:h}=this.core;!this.enableSEI||r.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||r.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=l({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=f=>{var w,_;f.data.type==="sei"&&((_=(w=this.callback)==null?void 0:w.onSEIMessage)==null||_.call(w,{data:f.data.data,seiPayloadType:f.data.seiPayloadType}))},this.scriptTransformWorker.onerror=f=>{this._log.error("scriptTransformWorker error: ",f.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const r of this.core.room.videoManager.decodePipeline)if(r&&!(i=r({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,r=await U1(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:l,errmsg:I}=r;if(l!==0)throw new Error(`errCode:${l}, errmsg:${I}`);return r}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:r}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,r.kind==="audio"),r.kind==="audio"?this.player.setAudioTrack(r):this.player.setVideoTrack(r)}onSEIMessage({room:i,nalu:r}){var l,I;i===this.core.room&&((I=(l=this.callback)==null?void 0:l.onSEIMessage)==null||I.call(l,{data:r.seiPayload.buffer,seiPayloadType:r.seiPayloadType}))}async fetchSignalDomain(i,r=F1[0]){var l;const I=`https://${r}/signal_query`;try{const h=window.localStorage.getItem(xj);if(h){const U=JSON.parse(h);if(((l=U[i])==null?void 0:l.expire)-new Date().getTime()>0)return{signalDomain:U[i].signal,cached:!0}}const f=await U1(I,{domain:i,requestid:Fj(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:w,errmsg:_,data:G}=f;if(w===0){const{signal_domain:U,cache_time:j}=G;let lA={};const sA=window.localStorage.getItem(xj);sA&&(lA=JSON.parse(sA)),lA[i]={signal:U,expire:new Date().getTime()+1e3*j};try{window.localStorage.setItem(xj,JSON.stringify(lA))}catch{}return{signalDomain:U,cached:!1}}throw new Error(`errCode:${w} errmsg:${_}`)}catch(h){return this._log.error("fetchSignalDomain error",h),F1[1]&&r!==F1[1]?this.fetchSignalDomain(i,F1[1]):{signalDomain:"",cached:!1}}}};pn(sY,"Name","LEBPlayer"),P_([XrA({fnName:"connect"})],sY.prototype,"stop"),P_([ZrA({settings:{retries:1/0,timeout:2e3},onRetrying(t){var i;if(this._log.warn(`retry connect ${t}`),t>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:r,ErrorCode:l,ErrorCodeDictionary:I}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new r({code:l.OPERATION_FAILED,extraCode:I.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(t,i,r,l){var I;if(this._log.warn("connect failed",t),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((I=t.message||t)==null?void 0:I.includes("connection")))i();else{const{RtcError:h,ErrorCode:f}=this.core.errorModule;r(new h({code:f.UNKNOWN_ERROR,message:t.message}))}}})],sY.prototype,"connect");var q9=sY,U1=async(t,i,r={})=>{const{timeout:l=10}=r;let I,h=0,f={};window.AbortController&&(I=new window.AbortController,f={signal:I.signal},h=window.setTimeout(()=>I.abort(),1e3*l));const w=await fetch(t,OrA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},f));if(h&&window.clearTimeout(h),w.status!==200)throw new Error(`Network Error, status code:${w.status}`);return w.json()},F1=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],xj="LEB_PLAYER_STORAGE_KEY",oaA=t=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(t);return i?i[1]:""},saA=q9;const naA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:q9,default:saA},Symbol.toStringTag,{value:"Module"})),raA=kU(naA);var K9=Object.defineProperty,aaA=Object.defineProperties,gaA=Object.getOwnPropertyDescriptors,eZ=Object.getOwnPropertySymbols,caA=Object.prototype.hasOwnProperty,laA=Object.prototype.propertyIsEnumerable,O3=(t,i,r)=>i in t?K9(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,IaA=(t,i)=>{for(var r in i||(i={}))caA.call(i,r)&&O3(t,r,i[r]);if(eZ)for(var r of eZ(i))laA.call(i,r)&&O3(t,r,i[r]);return t},uaA=(t,i)=>aaA(t,gaA(i)),EaA=(t,i)=>{for(var r in i)K9(t,r,{get:i[r],enumerable:!0})},Hg=(t,i,r)=>O3(t,typeof i!="symbol"?i+"":i,r);async function daA({sdkAppId:t,userId:i,userSig:r,core:l}){var I;const h=Math.round(new Date().getTime()/1e3);try{const f=await l.schedule.getAbilityConfig(t,l.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:t,userId:i,userSig:r,timestamp:h});l.log.info(`virtual background ability response: ${JSON.stringify(f)}`);const{data:w}=f;return(I=w?.trtcAutoConf)!=null&&I.web_ar?{auth:!0,timestamp:h}:{auth:!1}}catch(f){return l.log.error("virtual background fetch error",f),{auth:!1}}}var CaA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function haA(t){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:uaA(IaA({},CaA),{type:{required:!1,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},onAbort:{required:!1},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}}),validate(i,r,l,I){var h;const{RtcError:f,ErrorCode:w,ErrorCodeDictionary:_}=t.errorModule;if(!i)return;const{type:G,src:U,onAbort:j}=i;if(G==="image"&&!U)throw new f({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_REQUIRED,fnName:l,messageParams:{key:"src"}});if(j&&!t.utils.isFunction(j))throw new f({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_TYPE,fnName:l,messageParams:{key:"onAbort",value:typeof j,rule:{type:"Function"}}});if(!((h=t.room.videoManager.cameraTrack)!=null&&h.mediaTrack))throw new f({code:w.INVALID_OPERATION,extraCode:_.INVALID_OPERATION_NEED_VIDEO,fnName:l})}}}function BaA(t){return{name:"UpdateVirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:{type:{required:!0,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}},validate(i,r,l,I){if(!i)return;const{RtcError:h,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule,{type:_,src:G}=i;if(_==="image"&&!G)throw new h({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_REQUIRED,fnName:l,messageParams:{key:"src"}})}}}function QaA(t){return{name:"StopVirtualBackgroundOptions",required:!1}}var paA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,l,I=i;I.ready=new Promise(($,K)=>{r=$,l=K});var h=Object.assign({},I),f="";typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),t&&(f=t),f=f.indexOf("blob:")!==0?f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,G=I.print||console.log.bind(console),U=I.printErr||console.error.bind(console);function j($){if(Me($))return function(K){for(var vA=atob(K),qA=new Uint8Array(vA.length),Ae=0;Ae$.startsWith(yt);function Oe($){return Promise.resolve().then(()=>function(K){if(K==re&&w)return new Uint8Array(w);var vA=j(K);if(vA)return vA;throw"both async and sync fetching of the wasm failed"}($))}function gt($,K,vA,qA){return function(Ae,me,Pe){return Oe(Ae).then(Fe=>WebAssembly.instantiate(Fe,me)).then(Fe=>Fe).then(Pe,Fe=>{U(`failed to asynchronously prepare wasm: ${Fe}`),Et(Fe)})}(K,vA,qA)}Me(re="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(qe=re,re=I.locateFile?I.locateFile(qe,f):f+qe);var Fi=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function To($){this.excPtr=$,this.ptr=$-24,this.set_type=function(K){TA[this.ptr+4>>2]=K},this.get_type=function(){return TA[this.ptr+4>>2]},this.set_destructor=function(K){TA[this.ptr+8>>2]=K},this.get_destructor=function(){return TA[this.ptr+8>>2]},this.set_caught=function(K){K=K?1:0,lA[this.ptr+12|0]=K},this.get_caught=function(){return lA[this.ptr+12|0]!=0},this.set_rethrown=function(K){K=K?1:0,lA[this.ptr+13|0]=K},this.get_rethrown=function(){return lA[this.ptr+13|0]!=0},this.init=function(K,vA){this.set_adjusted_ptr(0),this.set_type(K),this.set_destructor(vA)},this.set_adjusted_ptr=function(K){TA[this.ptr+16>>2]=K},this.get_adjusted_ptr=function(){return TA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(ba(this.get_type()))return TA[this.excPtr>>2];var K=this.get_adjusted_ptr();return K!==0?K:this.excPtr}}var io,Eo,Vs,ki=$=>{for(var K="",vA=$;sA[vA];)K+=io[sA[vA++]];return K},ns={},jo={},Ao={},Zt=$=>{throw new Eo($)},oo=$=>{throw new Vs($)},bi=($,K,vA)=>{function qA(Fe){var rt=vA(Fe);rt.length!==$.length&&oo("Mismatched type converter count");for(var Ct=0;Ct<$.length;++Ct)vs($[Ct],rt[Ct])}$.forEach(function(Fe){Ao[Fe]=K});var Ae=new Array(K.length),me=[],Pe=0;K.forEach((Fe,rt)=>{jo.hasOwnProperty(Fe)?Ae[rt]=jo[Fe]:(me.push(Fe),ns.hasOwnProperty(Fe)||(ns[Fe]=[]),ns[Fe].push(()=>{Ae[rt]=jo[Fe],++Pe===me.length&&qA(Ae)}))}),me.length===0&&qA(Ae)};function vs($,K,vA={}){if(!("argPackAdvance"in K))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(qA,Ae,me={}){var Pe=Ae.name;if(qA||Zt(`type "${Pe}" must have a positive integer typeid pointer`),jo.hasOwnProperty(qA)){if(me.ignoreDuplicateRegistrations)return;Zt(`Cannot register type '${Pe}' twice`)}if(jo[qA]=Ae,delete Ao[qA],ns.hasOwnProperty(qA)){var Fe=ns[qA];delete ns[qA],Fe.forEach(rt=>rt())}}($,K,vA)}var HA,ce=$=>{Zt($.$$.ptrType.registeredClass.name+" instance already deleted")},Ve=!1,Ot=$=>{},nt=$=>{$.count.value-=1,$.count.value===0&&(K=>{K.smartPtr?K.smartPtrType.rawDestructor(K.smartPtr):K.ptrType.registeredClass.rawDestructor(K.ptr)})($)},It=($,K,vA)=>{if(K===vA)return $;if(vA.baseClass===void 0)return null;var qA=It($,K,vA.baseClass);return qA===null?null:vA.downcast(qA)},ei={},ti=()=>Object.keys(Oi).length,be=()=>{var $=[];for(var K in Oi)Oi.hasOwnProperty(K)&&$.push(Oi[K]);return $},Ze=[],wt=()=>{for(;Ze.length;){var $=Ze.pop();$.$$.deleteScheduled=!1,$.delete()}},Nt=$=>{HA=$,Ze.length&&HA&&HA(wt)},Oi={},po=($,K)=>(K=((vA,qA)=>{for(qA===void 0&&Zt("ptr should not be undefined");vA.baseClass;)qA=vA.upcast(qA),vA=vA.baseClass;return qA})($,K),Oi[K]),No=($,K)=>(K.ptrType&&K.ptr||oo("makeClassHandle requires ptr and ptrType"),!!K.smartPtrType!=!!K.smartPtr&&oo("Both smartPtrType and smartPtr must be specified"),K.count={value:1},Go(Object.create($,{$$:{value:K}})));function so($){var K=this.getPointee($);if(!K)return this.destructor($),null;var vA=po(this.registeredClass,K);if(vA!==void 0){if(vA.$$.count.value===0)return vA.$$.ptr=K,vA.$$.smartPtr=$,vA.clone();var qA=vA.clone();return this.destructor($),qA}function Ae(){return this.isSmartPointer?No(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:K,smartPtrType:this,smartPtr:$}):No(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var me,Pe=this.registeredClass.getActualType(K),Fe=ei[Pe];if(!Fe)return Ae.call(this);me=this.isConst?Fe.constPointerType:Fe.pointerType;var rt=It(K,this.registeredClass,me.registeredClass);return rt===null?Ae.call(this):this.isSmartPointer?No(me.registeredClass.instancePrototype,{ptrType:me,ptr:rt,smartPtrType:this,smartPtr:$}):No(me.registeredClass.instancePrototype,{ptrType:me,ptr:rt})}var Go=$=>typeof FinalizationRegistry>"u"?(Go=K=>K,$):(Ve=new FinalizationRegistry(K=>{nt(K.$$)}),Ot=K=>Ve.unregister(K),(Go=K=>{var vA=K.$$;if(vA.smartPtr){var qA={$$:vA};Ve.register(K,qA,K)}return K})($));function An(){}var rn=($,K)=>Object.defineProperty(K,"name",{value:$}),Es=($,K,vA)=>{if($[K].overloadTable===void 0){var qA=$[K];$[K]=function(){return $[K].overloadTable.hasOwnProperty(arguments.length)||Zt(`Function '${vA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[K].overloadTable})!`),$[K].overloadTable[arguments.length].apply(this,arguments)},$[K].overloadTable=[],$[K].overloadTable[qA.argCount]=qA}};function an($,K,vA,qA,Ae,me,Pe,Fe){this.name=$,this.constructor=K,this.instancePrototype=vA,this.rawDestructor=qA,this.baseClass=Ae,this.getActualType=me,this.upcast=Pe,this.downcast=Fe,this.pureVirtualFunctions=[]}var Do=($,K,vA)=>{for(;K!==vA;)K.upcast||Zt(`Expected null or instance of ${vA.name}, got an instance of ${K.name}`),$=K.upcast($),K=K.baseClass;return $};function pA($,K){if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`);var vA=K.$$.ptrType.registeredClass;return Do(K.$$.ptr,vA,this.registeredClass)}function Jn($,K){var vA;if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),this.isSmartPointer?(vA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,vA),vA):0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&K.$$.ptrType.isConst&&Zt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);var qA=K.$$.ptrType.registeredClass;if(vA=Do(K.$$.ptr,qA,this.registeredClass),this.isSmartPointer)switch(K.$$.smartPtr===void 0&&Zt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:K.$$.smartPtrType===this?vA=K.$$.smartPtr:Zt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:vA=K.$$.smartPtr;break;case 2:if(K.$$.smartPtrType===this)vA=K.$$.smartPtr;else{var Ae=K.clone();vA=this.rawShare(vA,cn.toHandle(()=>Ae.delete())),$!==null&&$.push(this.rawDestructor,vA)}break;default:Zt("Unsupporting sharing policy")}return vA}function Qr($,K){if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`),K.$$.ptrType.isConst&&Zt(`Cannot convert argument of type ${K.$$.ptrType.name} to parameter type ${this.name}`);var vA=K.$$.ptrType.registeredClass;return Do(K.$$.ptr,vA,this.registeredClass)}function ds($){return this.fromWireType(TA[$>>2])}function zr($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct,Rt){this.name=$,this.registeredClass=K,this.isReference=vA,this.isConst=qA,this.isSmartPointer=Ae,this.pointeeType=me,this.sharingPolicy=Pe,this.rawGetPointee=Fe,this.rawConstructor=rt,this.rawShare=Ct,this.rawDestructor=Rt,Ae||K.baseClass!==void 0?this.toWireType=Jn:qA?(this.toWireType=pA,this.destructorFunction=null):(this.toWireType=Qr,this.destructorFunction=null)}var Pi,Rs,or=[],en=$=>{var K=or[$];return K||($>=or.length&&(or.length=$+1),or[$]=K=Pi.get($)),K},wn=($,K,vA)=>$.includes("j")?((qA,Ae,me)=>{var Pe=I["dynCall_"+qA];return me&&me.length?Pe.apply(null,[Ae].concat(me)):Pe.call(null,Ae)})($,K,vA):en(K).apply(null,vA),qt=($,K)=>{var vA,qA,Ae,me=($=ki($)).includes("j")?(vA=$,qA=K,Ae=[],function(){return Ae.length=0,Object.assign(Ae,arguments),wn(vA,qA,Ae)}):en(K);return typeof me!="function"&&Zt(`unknown function pointer with signature ${$}: ${K}`),me},yg=$=>{var K=Ea($),vA=ki(K);return yn(K),vA},On=($,K)=>{var vA=[],qA={};throw K.forEach(function Ae(me){qA[me]||jo[me]||(Ao[me]?Ao[me].forEach(Ae):(vA.push(me),qA[me]=!0))}),new Rs(`${$}: `+vA.map(yg).join([", "]))},Gn=($,K)=>{for(var vA=[],qA=0;qA<$;qA++)vA.push(TA[K+4*qA>>2]);return vA},Js=$=>{for(;$.length;){var K=$.pop();$.pop()(K)}};function pr($,K,vA,qA,Ae,me){var Pe=K.length;Pe<2&&Zt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Fe=K[1]!==null&&vA!==null,rt=!1,Ct=1;Ct($ instanceof Object||Zt(`${vA} with invalid "this": ${$}`),$ instanceof K.registeredClass.constructor||Zt(`${vA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Zt(`cannot call emscripten binding method ${vA} on deleted object`),Do($.$$.ptr,$.$$.ptrType.registeredClass,K.registeredClass));function mr(){this.allocated=[void 0],this.freelist=[]}var mo=new mr,gn=$=>{$>=mo.reserved&&--mo.get($).refcount===0&&mo.free($)},Sl=()=>{for(var $=0,K=mo.reserved;K($||Zt("Cannot use deleted val. handle = "+$),mo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return mo.allocate({refcount:1,value:$})}}};function fr($){return this.fromWireType(cA[$>>2])}var Ls,Jc,ms,as=$=>{if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$},Ru=($,K)=>{switch(K){case 4:return function(vA){return this.fromWireType(WA[vA>>2])};case 8:return function(vA){return this.fromWireType(ue[vA>>3])};default:throw new TypeError(`invalid float width (${K}): ${$}`)}},Wa=($,K,vA)=>{switch(K){case 1:return vA?qA=>lA[qA|0]:qA=>sA[qA|0];case 2:return vA?qA=>mA[qA>>1]:qA=>IA[qA>>1];case 4:return vA?qA=>cA[qA>>2]:qA=>TA[qA>>2];default:throw new TypeError(`invalid integer width (${K}): ${$}`)}},Cs=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,sg=($,K,vA)=>{for(var qA=K+vA,Ae=K;$[Ae]&&!(Ae>=qA);)++Ae;if(Ae-K>16&&$.buffer&&Cs)return Cs.decode($.subarray(K,Ae));for(var me="";K>10,56320|1023&Ct)}}else me+=String.fromCharCode((31&Pe)<<6|Fe)}else me+=String.fromCharCode(Pe)}return me},HI=($,K)=>$?sg(sA,$,K):"",As=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,$i=($,K)=>{for(var vA=$,qA=vA>>1,Ae=qA+K/2;!(qA>=Ae)&&IA[qA];)++qA;if((vA=qA<<1)-$>32&&As)return As.decode(sA.subarray($,vA));for(var me="",Pe=0;!(Pe>=K/2);++Pe){var Fe=mA[$+2*Pe>>1];if(Fe==0)break;me+=String.fromCharCode(Fe)}return me},pc=($,K,vA)=>{if(vA===void 0&&(vA=2147483647),vA<2)return 0;for(var qA=K,Ae=(vA-=2)<2*$.length?vA/2:$.length,me=0;me>1]=Pe,K+=2}return mA[K>>1]=0,K-qA},ng=$=>2*$.length,Dg=($,K)=>{for(var vA=0,qA="";!(vA>=K/4);){var Ae=cA[$+4*vA>>2];if(Ae==0)break;if(++vA,Ae>=65536){var me=Ae-65536;qA+=String.fromCharCode(55296|me>>10,56320|1023&me)}else qA+=String.fromCharCode(Ae)}return qA},ua=($,K,vA)=>{if(vA===void 0&&(vA=2147483647),vA<4)return 0;for(var qA=K,Ae=qA+vA-4,me=0;me<$.length;++me){var Pe=$.charCodeAt(me);if(Pe>=55296&&Pe<=57343&&(Pe=65536+((1023&Pe)<<10)|1023&$.charCodeAt(++me)),cA[K>>2]=Pe,(K+=4)+4>Ae)break}return cA[K>>2]=0,K-qA},bo=$=>{for(var K=0,vA=0;vA<$.length;++vA){var qA=$.charCodeAt(vA);qA>=55296&&qA<=57343&&++vA,K+=4}return K},Zr=($,K)=>{var vA=jo[$];return vA===void 0&&Zt(K+" has unknown type "+yg($)),vA},_o=($,K,vA)=>{var qA=[],Ae=$.toWireType(qA,vA);return qA.length&&(TA[K>>2]=cn.toHandle(qA)),Ae},Hc={},Hn=[],Hs=Reflect.construct,Sg=[null,[],[]],mc=($,K)=>{var vA=Sg[$];K===0||K===10?(($===1?G:U)(sg(vA,0)),vA.length=0):vA.push(K)};(()=>{for(var $=new Array(256),K=0;K<256;++K)$[K]=String.fromCharCode(K);io=$})(),Eo=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},Vs=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(An.prototype,{isAliasOf($){if(!(this instanceof An)||!($ instanceof An))return!1;var K=this.$$.ptrType.registeredClass,vA=this.$$.ptr;$.$$=$.$$;for(var qA=$.$$.ptrType.registeredClass,Ae=$.$$.ptr;K.baseClass;)vA=K.upcast(vA),K=K.baseClass;for(;qA.baseClass;)Ae=qA.upcast(Ae),qA=qA.baseClass;return K===qA&&vA===Ae},clone(){if(this.$$.ptr||ce(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,K=Go(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return K.$$.count.value+=1,K.$$.deleteScheduled=!1,K},delete(){this.$$.ptr||ce(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Zt("Object already scheduled for deletion"),Ot(this),nt(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ce(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Zt("Object already scheduled for deletion"),Ze.push(this),Ze.length===1&&HA&&HA(wt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=ti,I.getLiveInheritedInstances=be,I.flushPendingDeletes=wt,I.setDelayFunction=Nt,Object.assign(zr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:ds,deleteObject($){$!==null&&$.delete()},fromWireType:so}),Rs=I.UnboundTypeError=(Ls=Error,(ms=rn(Jc="UnboundTypeError",function($){this.name=Jc,this.message=$;var K=new Error($).stack;K!==void 0&&(this.stack=this.toString()+` -`+K.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Ls.prototype),ms.prototype.constructor=ms,ms.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},ms),Object.assign(mr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var K=this.freelist.pop()||this.allocated.length;return this.allocated[K]=$,K},free($){this.allocated[$]=void 0,this.freelist.push($)}}),mo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),mo.reserved=mo.allocated.length,I.count_emval_handles=Sl;var fn,Ga={w:($,K,vA)=>{throw new To($).init(K,vA),$},q:($,K,vA,qA,Ae)=>{},u:($,K,vA,qA)=>{vs($,{name:K=ki(K),fromWireType:function(Ae){return!!Ae},toWireType:function(Ae,me){return me?vA:qA},argPackAdvance:8,readValueFromPointer:function(Ae){return this.fromWireType(sA[Ae])},destructorFunction:null})},y:($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct,Rt,Yt,Ii)=>{Rt=ki(Rt),me=qt(Ae,me),Fe&&(Fe=qt(Pe,Fe)),Ct&&(Ct=qt(rt,Ct)),Ii=qt(Yt,Ii);var ct=(xt=>{if(xt===void 0)return"_unknown";var Ji=(xt=xt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return Ji>=48&&Ji<=57?`_${xt}`:xt})(Rt);((xt,Ji,Ki)=>{I.hasOwnProperty(xt)?(Zt(`Cannot register public name '${xt}' twice`),Es(I,xt,xt),I.hasOwnProperty(Ki)&&Zt(`Cannot register multiple overloads of a function with the same number of arguments (${Ki})!`),I[xt].overloadTable[Ki]=Ji):I[xt]=Ji})(ct,function(){On(`Cannot construct ${Rt} due to unbound types`,[qA])}),bi([$,K,vA],qA?[qA]:[],function(xt){var Ji,Ki;xt=xt[0],Ki=qA?(Ji=xt.registeredClass).instancePrototype:An.prototype;var qs=rn(Rt,function(){if(Object.getPrototypeOf(this)!==Mi)throw new Eo("Use 'new' to construct "+Rt);if(zo.constructor_body===void 0)throw new Eo(Rt+" has no accessible constructor");var xn=zo.constructor_body[arguments.length];if(xn===void 0)throw new Eo(`Tried to invoke ctor of ${Rt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(zo.constructor_body).toString()}) parameters instead!`);return xn.apply(this,arguments)}),Mi=Object.create(Ki,{constructor:{value:qs}});qs.prototype=Mi;var zo=new an(Rt,qs,Mi,Ii,Ji,me,Fe,Ct);zo.baseClass&&(zo.baseClass.__derivedClasses===void 0&&(zo.baseClass.__derivedClasses=[]),zo.baseClass.__derivedClasses.push(zo));var Mg=new zr(Rt,zo,!0,!1,!1),sr=new zr(Rt+"*",zo,!1,!1,!1),yr=new zr(Rt+" const*",zo,!1,!0,!1);return ei[$]={pointerType:sr,constPointerType:yr},((xn,Ml,Ks)=>{I.hasOwnProperty(xn)||oo("Replacing nonexistant public symbol"),I[xn].overloadTable!==void 0&&Ks!==void 0?I[xn].overloadTable[Ks]=Ml:(I[xn]=Ml,I[xn].argCount=Ks)})(ct,qs),[Mg,sr,yr]})},x:($,K,vA,qA,Ae,me)=>{var Pe=Gn(K,vA);Ae=qt(qA,Ae),bi([],[$],function(Fe){var rt=`constructor ${(Fe=Fe[0]).name}`;if(Fe.registeredClass.constructor_body===void 0&&(Fe.registeredClass.constructor_body=[]),Fe.registeredClass.constructor_body[K-1]!==void 0)throw new Eo(`Cannot register multiple constructors with identical number of parameters (${K-1}) for class '${Fe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Fe.registeredClass.constructor_body[K-1]=()=>{On(`Cannot construct ${Fe.name} due to unbound types`,Pe)},bi([],Pe,Ct=>(Ct.splice(1,0,null),Fe.registeredClass.constructor_body[K-1]=pr(rt,Ct,null,Ae,me),[])),[]})},i:($,K,vA,qA,Ae,me,Pe,Fe,rt)=>{var Ct=Gn(vA,qA);K=(Rt=>{const Yt=(Rt=Rt.trim()).indexOf("(");return Yt!==-1?Rt.substr(0,Yt):Rt})(K=ki(K)),me=qt(Ae,me),bi([],[$],function(Rt){var Yt=`${(Rt=Rt[0]).name}.${K}`;function Ii(){On(`Cannot call ${Yt} due to unbound types`,Ct)}K.startsWith("@@")&&(K=Symbol[K.substring(2)]),Fe&&Rt.registeredClass.pureVirtualFunctions.push(K);var ct=Rt.registeredClass.instancePrototype,xt=ct[K];return xt===void 0||xt.overloadTable===void 0&&xt.className!==Rt.name&&xt.argCount===vA-2?(Ii.argCount=vA-2,Ii.className=Rt.name,ct[K]=Ii):(Es(ct,K,Yt),ct[K].overloadTable[vA-2]=Ii),bi([],Ct,function(Ji){var Ki=pr(Yt,Ji,Rt,me,Pe);return ct[K].overloadTable===void 0?(Ki.argCount=vA-2,ct[K]=Ki):ct[K].overloadTable[vA-2]=Ki,[]}),[]})},k:($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct)=>{K=ki(K),Ae=qt(qA,Ae),bi([],[$],function(Rt){var Yt=`${(Rt=Rt[0]).name}.${K}`,Ii={get(){On(`Cannot access ${Yt} due to unbound types`,[vA,Pe])},enumerable:!0,configurable:!0};return Ii.set=rt?()=>On(`Cannot access ${Yt} due to unbound types`,[vA,Pe]):ct=>Zt(Yt+" is a read-only property"),Object.defineProperty(Rt.registeredClass.instancePrototype,K,Ii),bi([],rt?[vA,Pe]:[vA],function(ct){var xt=ct[0],Ji={get(){var qs=Pn(this,Rt,Yt+" getter");return xt.fromWireType(Ae(me,qs))},enumerable:!0};if(rt){rt=qt(Fe,rt);var Ki=ct[1];Ji.set=function(qs){var Mi=Pn(this,Rt,Yt+" setter"),zo=[];rt(Ct,Mi,Ki.toWireType(zo,qs)),Js(zo)}}return Object.defineProperty(Rt.registeredClass.instancePrototype,K,Ji),[]}),[]})},t:($,K)=>{vs($,{name:K=ki(K),fromWireType:vA=>{var qA=cn.toValue(vA);return gn(vA),qA},toWireType:(vA,qA)=>cn.toHandle(qA),argPackAdvance:8,readValueFromPointer:fr,destructorFunction:null})},p:($,K,vA)=>{vs($,{name:K=ki(K),fromWireType:qA=>qA,toWireType:(qA,Ae)=>Ae,argPackAdvance:8,readValueFromPointer:Ru(K,vA),destructorFunction:null})},g:($,K,vA,qA,Ae)=>{K=ki(K);var me=rt=>rt;if(qA===0){var Pe=32-8*vA;me=rt=>rt<>>Pe}var Fe=K.includes("unsigned");vs($,{name:K,fromWireType:me,toWireType:Fe?function(rt,Ct){return this.name,Ct>>>0}:function(rt,Ct){return this.name,Ct},argPackAdvance:8,readValueFromPointer:Wa(K,vA,qA!==0),destructorFunction:null})},a:($,K,vA)=>{var qA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][K];function Ae(me){var Pe=TA[me>>2],Fe=TA[me+4>>2];return new qA(lA.buffer,Fe,Pe)}vs($,{name:vA=ki(vA),fromWireType:Ae,argPackAdvance:8,readValueFromPointer:Ae},{ignoreDuplicateRegistrations:!0})},o:($,K)=>{var vA=(K=ki(K))==="std::string";vs($,{name:K,fromWireType(qA){var Ae,me=TA[qA>>2],Pe=qA+4;if(vA)for(var Fe=Pe,rt=0;rt<=me;++rt){var Ct=Pe+rt;if(rt==me||sA[Ct]==0){var Rt=HI(Fe,Ct-Fe);Ae===void 0?Ae=Rt:(Ae+="\0",Ae+=Rt),Fe=Ct+1}}else{var Yt=new Array(me);for(rt=0;rt{for(var Ii=0,ct=0;ct=55296&&xt<=57343?(Ii+=4,++ct):Ii+=3}return Ii})(Ae):Ae.length;var Fe=fs(4+me+1),rt=Fe+4;if(TA[Fe>>2]=me,vA&&Pe)((Yt,Ii,ct,xt)=>{if(!(xt>0))return 0;for(var Ji=ct,Ki=ct+xt-1,qs=0;qs=55296&&Mi<=57343&&(Mi=65536+((1023&Mi)<<10)|1023&Yt.charCodeAt(++qs)),Mi<=127){if(ct>=Ki)break;Ii[ct++]=Mi}else if(Mi<=2047){if(ct+1>=Ki)break;Ii[ct++]=192|Mi>>6,Ii[ct++]=128|63&Mi}else if(Mi<=65535){if(ct+2>=Ki)break;Ii[ct++]=224|Mi>>12,Ii[ct++]=128|Mi>>6&63,Ii[ct++]=128|63&Mi}else{if(ct+3>=Ki)break;Ii[ct++]=240|Mi>>18,Ii[ct++]=128|Mi>>12&63,Ii[ct++]=128|Mi>>6&63,Ii[ct++]=128|63&Mi}}Ii[ct]=0})(Ae,sA,rt,me+1);else if(Pe)for(var Ct=0;Ct255&&(yn(rt),Zt("String has UTF-16 code units that do not fit in 8 bits")),sA[rt+Ct]=Rt}else for(Ct=0;Ct{var qA,Ae,me,Pe,Fe;vA=ki(vA),K===2?(qA=$i,Ae=pc,Pe=ng,me=()=>IA,Fe=1):K===4&&(qA=Dg,Ae=ua,Pe=bo,me=()=>TA,Fe=2),vs($,{name:vA,fromWireType:rt=>{for(var Ct,Rt=TA[rt>>2],Yt=me(),Ii=rt+4,ct=0;ct<=Rt;++ct){var xt=rt+4+ct*K;if(ct==Rt||Yt[xt>>Fe]==0){var Ji=qA(Ii,xt-Ii);Ct===void 0?Ct=Ji:(Ct+="\0",Ct+=Ji),Ii=xt+K}}return yn(rt),Ct},toWireType:(rt,Ct)=>{typeof Ct!="string"&&Zt(`Cannot pass non-string to C++ string type ${vA}`);var Rt=Pe(Ct),Yt=fs(4+Rt+K);return TA[Yt>>2]=Rt>>Fe,Ae(Ct,Yt+4,Rt+K),rt!==null&&rt.push(yn,Yt),Yt},argPackAdvance:8,readValueFromPointer:fr,destructorFunction(rt){yn(rt)}})},v:($,K)=>{vs($,{isVoid:!0,name:K=ki(K),argPackAdvance:0,fromWireType:()=>{},toWireType:(vA,qA)=>{}})},j:($,K,vA)=>($=cn.toValue($),K=Zr(K,"emval::as"),_o(K,vA,$)),e:($,K,vA,qA,Ae)=>{var me,Pe;return($=Hn[$])(K=cn.toValue(K),K[vA=(Pe=Hc[me=vA])===void 0?ki(me):Pe],qA,Ae)},d:gn,f:($,K,vA)=>{var qA=((Ct,Rt)=>{for(var Yt=new Array(Ct),Ii=0;Ii>2],"parameter "+Ii);return Yt})($,K),Ae=qA.shift();$--;var me,Pe,Fe=new Array($),rt=`methodCaller<(${qA.map(Ct=>Ct.name).join(", ")}) => ${Ae.name}>`;return me=rn(rt,(Ct,Rt,Yt,Ii)=>{for(var ct=0,xt=0;xt<$;++xt)Fe[xt]=qA[xt].readValueFromPointer(Ii+ct),ct+=qA[xt].argPackAdvance;var Ji=vA===1?Hs(Rt,Fe):Rt.apply(Ct,Fe);for(xt=0;xt<$;++xt)qA[xt].deleteObject&&qA[xt].deleteObject(Fe[xt]);return _o(Ae,Yt,Ji)}),Pe=Hn.length,Hn.push(me),Pe},c:$=>{$>4&&(mo.get($).refcount+=1)},b:$=>{var K=cn.toValue($);Js(K),gn($)},h:($,K)=>{var vA=($=Zr($,"_emval_take_value")).readValueFromPointer(K);return cn.toHandle(vA)},m:()=>{Et("")},s:($,K,vA)=>sA.copyWithin($,K,K+vA),r:$=>{sA.length,Et("OOM")},n:($,K,vA,qA)=>{for(var Ae=0,me=0;me>2],Fe=TA[K+4>>2];K+=8;for(var rt=0;rt>2]=Ae,0}},In=function(){var $={a:Ga};function K(vA,qA){var Ae,me;return In=vA.exports,_=In.z,Ae=_.buffer,I.HEAP8=lA=new Int8Array(Ae),I.HEAP16=mA=new Int16Array(Ae),I.HEAPU8=sA=new Uint8Array(Ae),I.HEAPU16=IA=new Uint16Array(Ae),I.HEAP32=cA=new Int32Array(Ae),I.HEAPU32=TA=new Uint32Array(Ae),I.HEAPF32=WA=new Float32Array(Ae),I.HEAPF64=ue=new Float64Array(Ae),Pi=In.C,me=In.A,Qe.unshift(me),function(){if(Mt--,I.monitorRunDependencies&&I.monitorRunDependencies(Mt),Mt==0&&jt){var Pe=jt;jt=null,Pe()}}(),In}if(Mt++,I.monitorRunDependencies&&I.monitorRunDependencies(Mt),I.instantiateWasm)try{return I.instantiateWasm($,K)}catch(vA){U(`Module.instantiateWasm callback failed with error: ${vA}`),l(vA)}return gt(0,re,$,function(vA){K(vA.instance)}).catch(l),{}}(),fs=$=>(fs=In.B)($),Ea=$=>(Ea=In.D)($),yn=$=>(yn=In.E)($),ba=$=>(ba=In.F)($);I.dynCall_jiji=($,K,vA,qA,Ae)=>(I.dynCall_jiji=In.G)($,K,vA,qA,Ae),I._vertexShaderSource=10688;function Sa(){function $(){fn||(fn=!0,I.calledRun=!0,Ce||(Fi(Qe),r(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)je(I.postRun.shift());Fi(ut)}()))}Mt>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)ft(I.preRun.shift());Fi(xe)}(),Mt>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(jt=function $(){fn||Sa(),fn||(jt=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Sa(),i.ready}})(),maA=paA,um=typeof navigator>"u"?"":navigator.userAgent,xs=t=>new RegExp(t,"i").test(um),Bc=t=>{if(xs(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=um.match(i);if(r&&r[1])return r[1]}return""},uV=t=>{if(xs(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=um.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},tZ=/AppleWebKit\/([\d.]+)/i.exec(um);tZ&&parseFloat(tZ[1]);var j9=xs("iPad"),W9=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&xs("Macintosh"),z9=xs("iPhone")&&!j9,faA=xs("iPod"),Z9=z9||j9||faA||W9,xW=xs("Android"),yaA=function(){if(xW){const t=um.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();xW&&xs("webkit")&&yaA<2.3;var DaA=xs("Firefox"),SaA=Bc("Firefox");uV("Firefox");var X9=xs("Edge"),MaA=Bc("Edge"),$9=xs("Edg"),vaA=Bc("Edg");uV("Edg");var AX=xs("SogouMobileBrowser"),RaA=Bc("SogouMobileBrowser"),eX=xs("MetaSr\\s"),waA=Bc("MetaSr\\s"),Lv=xs("TBS"),_aA=Bc("TBS"),tX=xs("XWEB"),TaA=Bc("XWEB");xs("MSIE\\s8\\.0");var NaA=xs("MSIE\\/\\d+");(function(){if(NaA){const t=/MSIE\s(\d+)\.\d/.exec(um);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(um)&&/rv:11.0/.test(um)&&(i=11),i}return NaN})();var GaA=xs("(micromessenger|webbrowser)"),baA=Bc("MicroMessenger"),YW=!Lv&&xs("MQQBrowser")&&xs("COVC"),VW=!Lv&&xs("MQQBrowser")&&!xs("COVC"),iZ=VW||YW?Bc("MQQBrowser"):"",iX=!Lv&&xs(" QQBrowser"),kaA=Bc(" QQBrowser"),oX=!Lv&&xs("QQBrowserLite"),LaA=Bc("QQBrowserLite"),sX=!Lv&&xs("MQBHD"),UaA=Bc("MQBHD");xs("Windows");!Z9&&xs("MAC OS X");!xW&&xs("Linux");xs("CrOS");xs("MicroMessenger");xs("UCBrowser");xs("Electron");var nX=xs("MiuiBrowser"),FaA=Bc("MiuiBrowser"),rX=xs("HuaweiBrowser");xs("Huawei")||xs("HUAWEI");xs("Honor")||xs("HONOR");var OaA=Bc("HuaweiBrowser"),aX=xs("SamsungBrowser"),PaA=Bc("SamsungBrowser"),gX=xs("HeyTapBrowser"),xaA=Bc("HeyTapBrowser"),cX=xs("VivoBrowser"),YaA=Bc("VivoBrowser");xs("OpenHarmony");Bc("OpenHarmony");var VaA=()=>uV("Chrome"),oZ=xs("CriOS"),lX=xs("Chrome"),JaA=!X9&&!eX&&!AX&&!Lv&&!tX&&!$9&&!iX&&!nX&&!rX&&!aX&&!gX&&!cX&&lX;xs("HeadlessChrome");var HaA=VaA(),qaA=Bc("Chrome");uV("Electron");var KaA=!lX&&!VW&&!YW&&!oX&&!sX&&xs("Safari"),IX=Bc("Version"),uX=(()=>{if(W9)return IX;if(Z9){const t=um.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();Number(uX.split(".")[0]);(()=>{const t=Number(uX.split(".")[0]);return t===14||t===13})();jaA();function jaA(){const t=new Map([[DaA,["Firefox",SaA]],[$9,["Edg",vaA]],[JaA,["Chrome",qaA]],[oZ,["ChiOS",Bc("CriOS")]],[KaA&&!oZ,["Safari",IX]],[Lv,["TBS",_aA]],[tX,["XWEB",TaA]],[GaA&&z9,["WeChat",baA]],[iX,["QQ(Win)",kaA]],[VW,["QQ(Mobile)",iZ]],[YW,["QQ(Mobile X5)",iZ]],[oX,["QQ(Mac)",LaA]],[sX,["QQ(iPad)",UaA]],[nX,["MI",FaA]],[rX,["HW",OaA]],[aX,["Samsung",PaA]],[gX,["OPPO",xaA]],[cX,["VIVO",YaA]],[X9,["EDGE",MaA]],[AX,["SogouMobile",RaA]],[eX,["Sogou",waA]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}var dc=1e-6,sT=typeof Float32Array<"u"?Float32Array:Array,EX={};function WaA(){var t=new sT(16);return sT!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function zaA(t){var i=new sT(16);return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],i}function ZaA(t,i){return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function XaA(t,i,r,l,I,h,f,w,_,G,U,j,lA,sA,mA,IA){var cA=new sT(16);return cA[0]=t,cA[1]=i,cA[2]=r,cA[3]=l,cA[4]=I,cA[5]=h,cA[6]=f,cA[7]=w,cA[8]=_,cA[9]=G,cA[10]=U,cA[11]=j,cA[12]=lA,cA[13]=sA,cA[14]=mA,cA[15]=IA,cA}function $aA(t,i,r,l,I,h,f,w,_,G,U,j,lA,sA,mA,IA,cA){return t[0]=i,t[1]=r,t[2]=l,t[3]=I,t[4]=h,t[5]=f,t[6]=w,t[7]=_,t[8]=G,t[9]=U,t[10]=j,t[11]=lA,t[12]=sA,t[13]=mA,t[14]=IA,t[15]=cA,t}function dX(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function AgA(t,i){if(t===i){var r=i[1],l=i[2],I=i[3],h=i[6],f=i[7],w=i[11];t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=r,t[6]=i[9],t[7]=i[13],t[8]=l,t[9]=h,t[11]=i[14],t[12]=I,t[13]=f,t[14]=w}else t[0]=i[0],t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=i[1],t[5]=i[5],t[6]=i[9],t[7]=i[13],t[8]=i[2],t[9]=i[6],t[10]=i[10],t[11]=i[14],t[12]=i[3],t[13]=i[7],t[14]=i[11],t[15]=i[15];return t}function egA(t,i){var r=i[0],l=i[1],I=i[2],h=i[3],f=i[4],w=i[5],_=i[6],G=i[7],U=i[8],j=i[9],lA=i[10],sA=i[11],mA=i[12],IA=i[13],cA=i[14],TA=i[15],WA=r*w-l*f,ue=r*_-I*f,Ce=r*G-h*f,xe=l*_-I*w,Qe=l*G-h*w,ut=I*G-h*_,ft=U*IA-j*mA,je=U*cA-lA*mA,Mt=U*TA-sA*mA,jt=j*cA-lA*IA,Et=j*TA-sA*IA,re=lA*TA-sA*cA,qe=WA*re-ue*Et+Ce*jt+xe*Mt-Qe*je+ut*ft;return qe?(qe=1/qe,t[0]=(w*re-_*Et+G*jt)*qe,t[1]=(I*Et-l*re-h*jt)*qe,t[2]=(IA*ut-cA*Qe+TA*xe)*qe,t[3]=(lA*Qe-j*ut-sA*xe)*qe,t[4]=(_*Mt-f*re-G*je)*qe,t[5]=(r*re-I*Mt+h*je)*qe,t[6]=(cA*Ce-mA*ut-TA*ue)*qe,t[7]=(U*ut-lA*Ce+sA*ue)*qe,t[8]=(f*Et-w*Mt+G*ft)*qe,t[9]=(l*Mt-r*Et-h*ft)*qe,t[10]=(mA*Qe-IA*Ce+TA*WA)*qe,t[11]=(j*Ce-U*Qe-sA*WA)*qe,t[12]=(w*je-f*jt-_*ft)*qe,t[13]=(r*jt-l*je+I*ft)*qe,t[14]=(IA*ue-mA*xe-cA*WA)*qe,t[15]=(U*xe-j*ue+lA*WA)*qe,t):null}function tgA(t,i){var r=i[0],l=i[1],I=i[2],h=i[3],f=i[4],w=i[5],_=i[6],G=i[7],U=i[8],j=i[9],lA=i[10],sA=i[11],mA=i[12],IA=i[13],cA=i[14],TA=i[15],WA=r*w-l*f,ue=r*_-I*f,Ce=r*G-h*f,xe=l*_-I*w,Qe=l*G-h*w,ut=I*G-h*_,ft=U*IA-j*mA,je=U*cA-lA*mA,Mt=U*TA-sA*mA,jt=j*cA-lA*IA,Et=j*TA-sA*IA,re=lA*TA-sA*cA;return t[0]=w*re-_*Et+G*jt,t[1]=I*Et-l*re-h*jt,t[2]=IA*ut-cA*Qe+TA*xe,t[3]=lA*Qe-j*ut-sA*xe,t[4]=_*Mt-f*re-G*je,t[5]=r*re-I*Mt+h*je,t[6]=cA*Ce-mA*ut-TA*ue,t[7]=U*ut-lA*Ce+sA*ue,t[8]=f*Et-w*Mt+G*ft,t[9]=l*Mt-r*Et-h*ft,t[10]=mA*Qe-IA*Ce+TA*WA,t[11]=j*Ce-U*Qe-sA*WA,t[12]=w*je-f*jt-_*ft,t[13]=r*jt-l*je+I*ft,t[14]=IA*ue-mA*xe-cA*WA,t[15]=U*xe-j*ue+lA*WA,t}function igA(t){var i=t[0],r=t[1],l=t[2],I=t[3],h=t[4],f=t[5],w=t[6],_=t[7],G=t[8],U=t[9],j=t[10],lA=t[11],sA=t[12],mA=t[13],IA=t[14],cA=i*f-r*h,TA=i*w-l*h,WA=r*w-l*f,ue=G*mA-U*sA,Ce=G*IA-j*sA,xe=U*IA-j*mA;return _*(i*xe-r*Ce+l*ue)-I*(h*xe-f*Ce+w*ue)+t[15]*(G*WA-U*TA+j*cA)-lA*(sA*WA-mA*TA+IA*cA)}function CX(t,i,r){var l=i[0],I=i[1],h=i[2],f=i[3],w=i[4],_=i[5],G=i[6],U=i[7],j=i[8],lA=i[9],sA=i[10],mA=i[11],IA=i[12],cA=i[13],TA=i[14],WA=i[15],ue=r[0],Ce=r[1],xe=r[2],Qe=r[3];return t[0]=ue*l+Ce*w+xe*j+Qe*IA,t[1]=ue*I+Ce*_+xe*lA+Qe*cA,t[2]=ue*h+Ce*G+xe*sA+Qe*TA,t[3]=ue*f+Ce*U+xe*mA+Qe*WA,ue=r[4],Ce=r[5],xe=r[6],Qe=r[7],t[4]=ue*l+Ce*w+xe*j+Qe*IA,t[5]=ue*I+Ce*_+xe*lA+Qe*cA,t[6]=ue*h+Ce*G+xe*sA+Qe*TA,t[7]=ue*f+Ce*U+xe*mA+Qe*WA,ue=r[8],Ce=r[9],xe=r[10],Qe=r[11],t[8]=ue*l+Ce*w+xe*j+Qe*IA,t[9]=ue*I+Ce*_+xe*lA+Qe*cA,t[10]=ue*h+Ce*G+xe*sA+Qe*TA,t[11]=ue*f+Ce*U+xe*mA+Qe*WA,ue=r[12],Ce=r[13],xe=r[14],Qe=r[15],t[12]=ue*l+Ce*w+xe*j+Qe*IA,t[13]=ue*I+Ce*_+xe*lA+Qe*cA,t[14]=ue*h+Ce*G+xe*sA+Qe*TA,t[15]=ue*f+Ce*U+xe*mA+Qe*WA,t}function ogA(t,i,r){var l,I,h,f,w,_,G,U,j,lA,sA,mA,IA=r[0],cA=r[1],TA=r[2];return i===t?(t[12]=i[0]*IA+i[4]*cA+i[8]*TA+i[12],t[13]=i[1]*IA+i[5]*cA+i[9]*TA+i[13],t[14]=i[2]*IA+i[6]*cA+i[10]*TA+i[14],t[15]=i[3]*IA+i[7]*cA+i[11]*TA+i[15]):(l=i[0],I=i[1],h=i[2],f=i[3],w=i[4],_=i[5],G=i[6],U=i[7],j=i[8],lA=i[9],sA=i[10],mA=i[11],t[0]=l,t[1]=I,t[2]=h,t[3]=f,t[4]=w,t[5]=_,t[6]=G,t[7]=U,t[8]=j,t[9]=lA,t[10]=sA,t[11]=mA,t[12]=l*IA+w*cA+j*TA+i[12],t[13]=I*IA+_*cA+lA*TA+i[13],t[14]=h*IA+G*cA+sA*TA+i[14],t[15]=f*IA+U*cA+mA*TA+i[15]),t}function sgA(t,i,r){var l=r[0],I=r[1],h=r[2];return t[0]=i[0]*l,t[1]=i[1]*l,t[2]=i[2]*l,t[3]=i[3]*l,t[4]=i[4]*I,t[5]=i[5]*I,t[6]=i[6]*I,t[7]=i[7]*I,t[8]=i[8]*h,t[9]=i[9]*h,t[10]=i[10]*h,t[11]=i[11]*h,t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function ngA(t,i,r,l){var I,h,f,w,_,G,U,j,lA,sA,mA,IA,cA,TA,WA,ue,Ce,xe,Qe,ut,ft,je,Mt,jt,Et=l[0],re=l[1],qe=l[2],yt=Math.sqrt(Et*Et+re*re+qe*qe);return yt0?(r[0]=2*(w*f+U*l+_*h-G*I)/j,r[1]=2*(_*f+U*I+G*l-w*h)/j,r[2]=2*(G*f+U*h+w*I-_*l)/j):(r[0]=2*(w*f+U*l+_*h-G*I),r[1]=2*(_*f+U*I+G*l-w*h),r[2]=2*(G*f+U*h+w*I-_*l)),hX(t,i,r),t}function hgA(t,i){return t[0]=i[12],t[1]=i[13],t[2]=i[14],t}function BX(t,i){var r=i[0],l=i[1],I=i[2],h=i[4],f=i[5],w=i[6],_=i[8],G=i[9],U=i[10];return t[0]=Math.sqrt(r*r+l*l+I*I),t[1]=Math.sqrt(h*h+f*f+w*w),t[2]=Math.sqrt(_*_+G*G+U*U),t}function BgA(t,i){var r=new sT(3);BX(r,i);var l=1/r[0],I=1/r[1],h=1/r[2],f=i[0]*l,w=i[1]*I,_=i[2]*h,G=i[4]*l,U=i[5]*I,j=i[6]*h,lA=i[8]*l,sA=i[9]*I,mA=i[10]*h,IA=f+U+mA,cA=0;return IA>0?(cA=2*Math.sqrt(IA+1),t[3]=.25*cA,t[0]=(j-sA)/cA,t[1]=(lA-_)/cA,t[2]=(w-G)/cA):f>U&&f>mA?(cA=2*Math.sqrt(1+f-U-mA),t[3]=(j-sA)/cA,t[0]=.25*cA,t[1]=(w+G)/cA,t[2]=(lA+_)/cA):U>mA?(cA=2*Math.sqrt(1+U-f-mA),t[3]=(lA-_)/cA,t[0]=(w+G)/cA,t[1]=.25*cA,t[2]=(j+sA)/cA):(cA=2*Math.sqrt(1+mA-f-U),t[3]=(w-G)/cA,t[0]=(lA+_)/cA,t[1]=(j+sA)/cA,t[2]=.25*cA),t}function QgA(t,i,r,l){i[0]=l[12],i[1]=l[13],i[2]=l[14];var I=l[0],h=l[1],f=l[2],w=l[4],_=l[5],G=l[6],U=l[8],j=l[9],lA=l[10];r[0]=Math.sqrt(I*I+h*h+f*f),r[1]=Math.sqrt(w*w+_*_+G*G),r[2]=Math.sqrt(U*U+j*j+lA*lA);var sA=1/r[0],mA=1/r[1],IA=1/r[2],cA=I*sA,TA=h*mA,WA=f*IA,ue=w*sA,Ce=_*mA,xe=G*IA,Qe=U*sA,ut=j*mA,ft=lA*IA,je=cA+Ce+ft,Mt=0;return je>0?(Mt=2*Math.sqrt(je+1),t[3]=.25*Mt,t[0]=(xe-ut)/Mt,t[1]=(Qe-WA)/Mt,t[2]=(TA-ue)/Mt):cA>Ce&&cA>ft?(Mt=2*Math.sqrt(1+cA-Ce-ft),t[3]=(xe-ut)/Mt,t[0]=.25*Mt,t[1]=(TA+ue)/Mt,t[2]=(Qe+WA)/Mt):Ce>ft?(Mt=2*Math.sqrt(1+Ce-cA-ft),t[3]=(Qe-WA)/Mt,t[0]=(TA+ue)/Mt,t[1]=.25*Mt,t[2]=(xe+ut)/Mt):(Mt=2*Math.sqrt(1+ft-cA-Ce),t[3]=(TA-ue)/Mt,t[0]=(Qe+WA)/Mt,t[1]=(xe+ut)/Mt,t[2]=.25*Mt),t}function pgA(t,i,r,l){var I=i[0],h=i[1],f=i[2],w=i[3],_=I+I,G=h+h,U=f+f,j=I*_,lA=I*G,sA=I*U,mA=h*G,IA=h*U,cA=f*U,TA=w*_,WA=w*G,ue=w*U,Ce=l[0],xe=l[1],Qe=l[2];return t[0]=(1-(mA+cA))*Ce,t[1]=(lA+ue)*Ce,t[2]=(sA-WA)*Ce,t[3]=0,t[4]=(lA-ue)*xe,t[5]=(1-(j+cA))*xe,t[6]=(IA+TA)*xe,t[7]=0,t[8]=(sA+WA)*Qe,t[9]=(IA-TA)*Qe,t[10]=(1-(j+mA))*Qe,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function mgA(t,i,r,l,I){var h=i[0],f=i[1],w=i[2],_=i[3],G=h+h,U=f+f,j=w+w,lA=h*G,sA=h*U,mA=h*j,IA=f*U,cA=f*j,TA=w*j,WA=_*G,ue=_*U,Ce=_*j,xe=l[0],Qe=l[1],ut=l[2],ft=I[0],je=I[1],Mt=I[2],jt=(1-(IA+TA))*xe,Et=(sA+Ce)*xe,re=(mA-ue)*xe,qe=(sA-Ce)*Qe,yt=(1-(lA+TA))*Qe,Me=(cA+WA)*Qe,Oe=(mA+ue)*ut,gt=(cA-WA)*ut,Fi=(1-(lA+IA))*ut;return t[0]=jt,t[1]=Et,t[2]=re,t[3]=0,t[4]=qe,t[5]=yt,t[6]=Me,t[7]=0,t[8]=Oe,t[9]=gt,t[10]=Fi,t[11]=0,t[12]=r[0]+ft-(jt*ft+qe*je+Oe*Mt),t[13]=r[1]+je-(Et*ft+yt*je+gt*Mt),t[14]=r[2]+Mt-(re*ft+Me*je+Fi*Mt),t[15]=1,t}function fgA(t,i){var r=i[0],l=i[1],I=i[2],h=i[3],f=r+r,w=l+l,_=I+I,G=r*f,U=l*f,j=l*w,lA=I*f,sA=I*w,mA=I*_,IA=h*f,cA=h*w,TA=h*_;return t[0]=1-j-mA,t[1]=U+TA,t[2]=lA-cA,t[3]=0,t[4]=U-TA,t[5]=1-G-mA,t[6]=sA+IA,t[7]=0,t[8]=lA+cA,t[9]=sA-IA,t[10]=1-G-j,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function ygA(t,i,r,l,I,h,f){var w=1/(r-i),_=1/(I-l),G=1/(h-f);return t[0]=2*h*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*h*_,t[6]=0,t[7]=0,t[8]=(r+i)*w,t[9]=(I+l)*_,t[10]=(f+h)*G,t[11]=-1,t[12]=0,t[13]=0,t[14]=f*h*2*G,t[15]=0,t}function QX(t,i,r,l,I){var h=1/Math.tan(i/2);if(t[0]=h/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,I!=null&&I!==1/0){var f=1/(l-I);t[10]=(I+l)*f,t[14]=2*I*l*f}else t[10]=-1,t[14]=-2*l;return t}EaA(EX,{add:()=>GgA,adjoint:()=>tgA,clone:()=>zaA,copy:()=>ZaA,create:()=>WaA,decompose:()=>QgA,determinant:()=>igA,equals:()=>UgA,exactEquals:()=>LgA,frob:()=>NgA,fromQuat:()=>fgA,fromQuat2:()=>CgA,fromRotation:()=>IgA,fromRotationTranslation:()=>hX,fromRotationTranslationScale:()=>pgA,fromRotationTranslationScaleOrigin:()=>mgA,fromScaling:()=>lgA,fromTranslation:()=>cgA,fromValues:()=>XaA,fromXRotation:()=>ugA,fromYRotation:()=>EgA,fromZRotation:()=>dgA,frustum:()=>ygA,getRotation:()=>BgA,getScaling:()=>BX,getTranslation:()=>hgA,identity:()=>dX,invert:()=>egA,lookAt:()=>wgA,mul:()=>FgA,multiply:()=>CX,multiplyScalar:()=>bgA,multiplyScalarAndAdd:()=>kgA,ortho:()=>vgA,orthoNO:()=>pX,orthoZO:()=>RgA,perspective:()=>DgA,perspectiveFromFieldOfView:()=>MgA,perspectiveNO:()=>QX,perspectiveZO:()=>SgA,rotate:()=>ngA,rotateX:()=>rgA,rotateY:()=>agA,rotateZ:()=>ggA,scale:()=>sgA,set:()=>$aA,str:()=>TgA,sub:()=>OgA,subtract:()=>mX,targetTo:()=>_gA,translate:()=>ogA,transpose:()=>AgA});var DgA=QX;function SgA(t,i,r,l,I){var h=1/Math.tan(i/2);if(t[0]=h/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=h,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,I!=null&&I!==1/0){var f=1/(l-I);t[10]=I*f,t[14]=I*l*f}else t[10]=-1,t[14]=-l;return t}function MgA(t,i,r,l){var I=Math.tan(i.upDegrees*Math.PI/180),h=Math.tan(i.downDegrees*Math.PI/180),f=Math.tan(i.leftDegrees*Math.PI/180),w=Math.tan(i.rightDegrees*Math.PI/180),_=2/(f+w),G=2/(I+h);return t[0]=_,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=G,t[6]=0,t[7]=0,t[8]=-(f-w)*_*.5,t[9]=(I-h)*G*.5,t[10]=l/(r-l),t[11]=-1,t[12]=0,t[13]=0,t[14]=l*r/(r-l),t[15]=0,t}function pX(t,i,r,l,I,h,f){var w=1/(i-r),_=1/(l-I),G=1/(h-f);return t[0]=-2*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*_,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*G,t[11]=0,t[12]=(i+r)*w,t[13]=(I+l)*_,t[14]=(f+h)*G,t[15]=1,t}var vgA=pX;function RgA(t,i,r,l,I,h,f){var w=1/(i-r),_=1/(l-I),G=1/(h-f);return t[0]=-2*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*_,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=G,t[11]=0,t[12]=(i+r)*w,t[13]=(I+l)*_,t[14]=h*G,t[15]=1,t}function wgA(t,i,r,l){var I,h,f,w,_,G,U,j,lA,sA,mA=i[0],IA=i[1],cA=i[2],TA=l[0],WA=l[1],ue=l[2],Ce=r[0],xe=r[1],Qe=r[2];return Math.abs(mA-Ce)0&&(U*=sA=1/Math.sqrt(sA),j*=sA,lA*=sA);var mA=_*lA-G*j,IA=G*U-w*lA,cA=w*j-_*U;return(sA=mA*mA+IA*IA+cA*cA)>0&&(mA*=sA=1/Math.sqrt(sA),IA*=sA,cA*=sA),t[0]=mA,t[1]=IA,t[2]=cA,t[3]=0,t[4]=j*cA-lA*IA,t[5]=lA*mA-U*cA,t[6]=U*IA-j*mA,t[7]=0,t[8]=U,t[9]=j,t[10]=lA,t[11]=0,t[12]=I,t[13]=h,t[14]=f,t[15]=1,t}function TgA(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function NgA(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function GgA(t,i,r){return t[0]=i[0]+r[0],t[1]=i[1]+r[1],t[2]=i[2]+r[2],t[3]=i[3]+r[3],t[4]=i[4]+r[4],t[5]=i[5]+r[5],t[6]=i[6]+r[6],t[7]=i[7]+r[7],t[8]=i[8]+r[8],t[9]=i[9]+r[9],t[10]=i[10]+r[10],t[11]=i[11]+r[11],t[12]=i[12]+r[12],t[13]=i[13]+r[13],t[14]=i[14]+r[14],t[15]=i[15]+r[15],t}function mX(t,i,r){return t[0]=i[0]-r[0],t[1]=i[1]-r[1],t[2]=i[2]-r[2],t[3]=i[3]-r[3],t[4]=i[4]-r[4],t[5]=i[5]-r[5],t[6]=i[6]-r[6],t[7]=i[7]-r[7],t[8]=i[8]-r[8],t[9]=i[9]-r[9],t[10]=i[10]-r[10],t[11]=i[11]-r[11],t[12]=i[12]-r[12],t[13]=i[13]-r[13],t[14]=i[14]-r[14],t[15]=i[15]-r[15],t}function bgA(t,i,r){return t[0]=i[0]*r,t[1]=i[1]*r,t[2]=i[2]*r,t[3]=i[3]*r,t[4]=i[4]*r,t[5]=i[5]*r,t[6]=i[6]*r,t[7]=i[7]*r,t[8]=i[8]*r,t[9]=i[9]*r,t[10]=i[10]*r,t[11]=i[11]*r,t[12]=i[12]*r,t[13]=i[13]*r,t[14]=i[14]*r,t[15]=i[15]*r,t}function kgA(t,i,r,l){return t[0]=i[0]+r[0]*l,t[1]=i[1]+r[1]*l,t[2]=i[2]+r[2]*l,t[3]=i[3]+r[3]*l,t[4]=i[4]+r[4]*l,t[5]=i[5]+r[5]*l,t[6]=i[6]+r[6]*l,t[7]=i[7]+r[7]*l,t[8]=i[8]+r[8]*l,t[9]=i[9]+r[9]*l,t[10]=i[10]+r[10]*l,t[11]=i[11]+r[11]*l,t[12]=i[12]+r[12]*l,t[13]=i[13]+r[13]*l,t[14]=i[14]+r[14]*l,t[15]=i[15]+r[15]*l,t}function LgA(t,i){return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}function UgA(t,i){var r=t[0],l=t[1],I=t[2],h=t[3],f=t[4],w=t[5],_=t[6],G=t[7],U=t[8],j=t[9],lA=t[10],sA=t[11],mA=t[12],IA=t[13],cA=t[14],TA=t[15],WA=i[0],ue=i[1],Ce=i[2],xe=i[3],Qe=i[4],ut=i[5],ft=i[6],je=i[7],Mt=i[8],jt=i[9],Et=i[10],re=i[11],qe=i[12],yt=i[13],Me=i[14],Oe=i[15];return Math.abs(r-WA)<=dc*Math.max(1,Math.abs(r),Math.abs(WA))&&Math.abs(l-ue)<=dc*Math.max(1,Math.abs(l),Math.abs(ue))&&Math.abs(I-Ce)<=dc*Math.max(1,Math.abs(I),Math.abs(Ce))&&Math.abs(h-xe)<=dc*Math.max(1,Math.abs(h),Math.abs(xe))&&Math.abs(f-Qe)<=dc*Math.max(1,Math.abs(f),Math.abs(Qe))&&Math.abs(w-ut)<=dc*Math.max(1,Math.abs(w),Math.abs(ut))&&Math.abs(_-ft)<=dc*Math.max(1,Math.abs(_),Math.abs(ft))&&Math.abs(G-je)<=dc*Math.max(1,Math.abs(G),Math.abs(je))&&Math.abs(U-Mt)<=dc*Math.max(1,Math.abs(U),Math.abs(Mt))&&Math.abs(j-jt)<=dc*Math.max(1,Math.abs(j),Math.abs(jt))&&Math.abs(lA-Et)<=dc*Math.max(1,Math.abs(lA),Math.abs(Et))&&Math.abs(sA-re)<=dc*Math.max(1,Math.abs(sA),Math.abs(re))&&Math.abs(mA-qe)<=dc*Math.max(1,Math.abs(mA),Math.abs(qe))&&Math.abs(IA-yt)<=dc*Math.max(1,Math.abs(IA),Math.abs(yt))&&Math.abs(cA-Me)<=dc*Math.max(1,Math.abs(cA),Math.abs(Me))&&Math.abs(TA-Oe)<=dc*Math.max(1,Math.abs(TA),Math.abs(Oe))}var FgA=CX,OgA=mX,fL=`#version 300 es + `],{type:"application/javascript"}),e=URL.createObjectURL(A);this.worker=new Worker(e),URL.revokeObjectURL(e),this.worker.onerror=o=>this._log.warn("worker error:",o.message,o.filename||"unknown",o.lineno||"unknown"),this.worker.onmessage=o=>{var a;let{type:l,trackId:d,message:h,count:y}=o.data;if(l==="black")(a=this.callbacks.get(d))==null||a();else if(l==="log")this._log.warn(h);else if(l==="blackCount"){let S=this.userIdMap.get(d);this._log.warn("".concat(S||d," black count: ").concat(y))}}}return this.worker}start(A){let{track:e,isUplink:o,room:a,userId:l,onBlack:d}=A;if(this._log.debug("start detect black video",e.id),!TM()||!d||!e||typeof Worker>"u")return void this._log.warn("black video detector not supported");let h=y=>{var S,k,V,J;let cA;if(o)cA=(k=(S=y.msg_up_stream_info)==null?void 0:S.msg_video_status)==null?void 0:k.filter(CA=>CA.uint32_video_stream_type===3)[0];else{let CA=(V=y.msg_down_stream_info)==null?void 0:V.filter(MA=>{var ie;return((ie=MA.msg_user_info)==null?void 0:ie.str_identifier)===l})[0];cA=(J=CA?.msg_video_status)==null?void 0:J.filter(MA=>MA.uint32_video_stream_type===3)[0]}if(cA){let CA=(cA.uint32_video_codec_bitrate||0)/1e3;if(this.sleep[e.id]&&this.sleep[e.id]>0)return void(this.sleep[e.id]-=1);CA>0&&CA<10&&(this.sleep[e.id]=30,this._log.info("track bitrate",CA,"start check"),this.checkOnce(e,3e4))}};return a.on("heartbeat-report",h),this.heartbeatListenerCleaner.set(e.id,()=>a.off("heartbeat-report",h)),this.callbacks.set(e.id,d),this.userIdMap.set(e.id,l),e.id}checkOnce(A,e){try{let o=this.getWorker();if(!o)throw new Error("Worker not available");let a=new MediaStreamTrackProcessor({track:A});o.postMessage({type:"addTrack",trackId:A.id,timeout:e,readable:a.readable},[a.readable])}catch(o){this._log.warn("check error:",o),this.stop(A.id)}}stop(A){if(A){this.worker&&this.worker.postMessage({type:"removeTrack",trackId:A}),this.callbacks.delete(A),delete this.sleep[A];let e=this.heartbeatListenerCleaner.get(A);e&&e(),this.heartbeatListenerCleaner.delete(A),this.userIdMap.delete(A)}}destroy(){this.callbacks.forEach((A,e)=>this.stop(e)),this.worker&&(this.worker.terminate(),this.worker=null)}},F1=class extends Q8{constructor(A){super(po(fi({},A),{isUplink:!0})),Y(this,"localMainAudioTrack",null),Y(this,"localMainVideoTrack",null),Y(this,"localAuxAudioTrack",null),Y(this,"localAuxVideoTrack",null),Y(this,"_isPublishingAux",!1),Y(this,"_publishingLocalAudioTrack"),Y(this,"_publishingLocalVideoTrack"),Y(this,"_mediaSettings",{videoCodec:"",videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,videoDecCodec:"",audioCodec:"opus",audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0,auxVideoWidth:0,auxVideoHeight:0,auxVideoFps:0,auxVideoBps:0}),Y(this,"_flag",0),Y(this,"_checkPublishStateTimeoutId",-1),this.initialize()}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get ssrc(){if(!this.singlePC)return{audio:0,video:0,videoRtx:0,small:0,smallRtx:0,auxiliary:0,auxiliaryRtx:0};let{audioSsrc:A,bigVideoSsrc:e,bigVideoRtxSsrc:o,smallVideoSsrc:a,smallVideoRtxSsrc:l,auxVideoSsrc:d,auxVideoRtxSsrc:h}=this.singlePC.uplinkSSRC;return{audio:A||0,video:e||0,videoRtx:o||0,small:a||0,smallRtx:l||0,auxiliary:d||0,auxiliaryRtx:h||0}}get flag(){return this._flag}set flag(A){this._flag!==A&&(this._flag=A,this.checkPublishState())}checkPublishState(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];try{if(!A&&this._checkPublishStateTimeoutId>0)return;let{serverPublishState:e}=this,{publishState:o}=this._room,a=Object.keys(o).filter(l=>{if(o[l]!==e[l]&&o[l])switch(l){case"audio":return!(!this.localMainAudioTrack||!this.localMainAudioTrack.isMediaTrackActive);case"bigVideo":case"smallVideo":return!(!this.localMainVideoTrack||!this.localMainVideoTrack.isMediaTrackActive);case"auxVideo":return!(!this.localAuxVideoTrack||!this.localAuxVideoTrack.isMediaTrackActive)}return!1});if(a.length>0){if(!A)return void(this._checkPublishStateTimeoutId=Gr.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));si.addCount({key:521e3}),a.forEach(l=>{this._log.warn("".concat(l," publish failed during call ").concat(Hp()," ").concat(cQ())),si.addEnum({key:521719,value:m8[l]})}),Gr.clearTask(this._checkPublishStateTimeoutId),this._checkPublishStateTimeoutId=-1}}catch(e){this._log.warn("checkPublishState failed",e)}}get isMainStreamPublished(){return!(!this.localMainAudioTrack&&!this.localMainVideoTrack)}get isAuxStreamPublished(){return!(!this.localAuxVideoTrack&&!this.localAuxAudioTrack)}get serverPublishState(){return{audio:!!(this.flag&ZS),bigVideo:!!(this.flag&WS),smallVideo:!!(this.flag&Nb),auxVideo:!!(this.flag&zS)}}initialize(){this.installEvents()}close(A){var e;let o=((e=this._peerConnection)==null?void 0:e.getSenders())||[];for(let a of o)a.replaceTrack(null);super.close(A),this.uninstallEvents(),this.uninstallTrackMuteEvents(this.localMainAudioTrack,this.localMainVideoTrack,this.localAuxVideoTrack),this.emitConnectionStateChangedEvent("DISCONNECTED")}installEvents(){this.listeners("connection-state-changed").includes(this.handleConnectionStateChange)||this.on("connection-state-changed",this.handleConnectionStateChange,this),this.installSPCEvents()}installSPCEvents(){var A,e;(A=this.singlePC)!=null&&A.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||(e=this.singlePC)==null||e.on("spc-reconnected",this.onSinglePCReconnected,this)}uninstallSPCEvents(){var A;(A=this.singlePC)==null||A.off("spc-reconnected",this.onSinglePCReconnected,this)}uninstallEvents(){this.off("connection-state-changed",this.handleConnectionStateChange,this),this.uninstallSPCEvents()}emitConnectionStateChangedEvent(A,e){var o,a,l;let d=this._currentState,h=super.emitConnectionStateChangedEvent(A);return h&&d!==A&&(e?e.emit("connection-state-changed",{prevState:d,state:A}):((o=this.localMainVideoTrack)==null||o.emit("connection-state-changed",{prevState:d,state:A}),(a=this.localAuxVideoTrack)==null||a.emit("connection-state-changed",{prevState:d,state:A}),(l=this._publishingLocalVideoTrack)==null||l.emit("connection-state-changed",{prevState:d,state:A}))),h}onVideoEncodeFailed(A){return WA(this,null,function*(){if(!A||!A.isMediaTrackActive)return;let{videoCodec:e,singlePC:o}=this;if(!o)return;let a={h265:{supported:o.isH264EncodeSupported,target:"h264",log:"h265 encoder not working"},h264:{supported:o.isVP8EncodeSupported,target:"vp8",log:"h264 encoder not working"},vp8:{supported:!1,target:"vp8",log:"vp8 encoder not working, no fallback available"}};if(e==="vp9"||e==="av1")return;let l=a[e];this._log.warn(l.log),l!=null&&l.supported&&(yield o.switchVideoEncoder(l.target))})}publish(A){return WA(this,arguments,function(e){var o=this;let{localAudioTrack:a,localVideoTrack:l,isAuxiliary:d}=e;return function*(){var h,y,S,k,V,J,cA;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(a,l),l&&(l.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),eg&&(gy(LI,"26.2",!0)||gy(rQ,"26.2",!0)||sQ&&gy(LI,"18.7",!0)))){o._log.warn("detectH264Supported for fallback 26.2 video encode issue");try{yield re.detectH264SupportedByFakeStreaming(500)}catch{}}if(yield o.singlePC.waitForPeerConnectionConnected(),a&&(o._publishingLocalAudioTrack=a),l){if(!o.singlePC.isH264EncodeSupported&&!o.singlePC.isVP8EncodeSupported)throw new gi({code:Ct.NOT_SUPPORTED_H264,message:Xo({key:vo.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),Ha&&yM()===115&&l.profile.width*l.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(jS))),l.setProfile(jS),yield l.applyProfile()),o._publishingLocalVideoTrack=l}let CA;if(o._isPublishingAux=d,l&&!d&&l.small&&(CA=o._room.videoManager.smallTrack),yield o._signalChannel.sendWaitForResponseWithRetry({command:$z,responseCommand:ls.SPC_PUBLISH_RESULT,data:po(fi({},o.singlePC.uplinkSSRC),{state:o._room.publishState,muteState:o._room.muteState}),retries:3}),l&&(yield o.checkHighProfile({streamType:l.streamType,newWidth:l.settings.width,newHeight:l.settings.height})),yield o.publishByTransceiver({localAudioTrack:a,localVideoTrack:l,smallTrack:CA,isAuxiliary:d}),o._publishingLocalAudioTrack=null,o._publishingLocalVideoTrack=null,o._isPublishingAux=!1,l){o[d?"localAuxVideoTrack":"localMainVideoTrack"]=l,yield o.singlePC.setDegradationPreference(o._peerConnection.getSenders()[d?3:1],l.contentHint,l.streamType);let{scaleResolutionDownBy:ie}=l;yield o.singlePC.setScaleResolutionDownBy(o._peerConnection.getSenders()[d?3:1],ie,l.streamType)}a&&(o[d?"localAuxAudioTrack":"localMainAudioTrack"]=a),yield o.singlePC.setBandwidth({audio:((h=o.localMainAudioTrack)==null?void 0:h.profile.bitrate)||((y=o.localAuxAudioTrack)==null?void 0:y.profile.bitrate),bigVideo:(S=o.localMainVideoTrack)==null?void 0:S.profile.bitrate,smallVideo:(V=(k=o.localMainVideoTrack)==null?void 0:k.small)==null?void 0:V.bitrate,auxVideo:(J=o.localAuxVideoTrack)==null?void 0:J.profile.bitrate}),o.sendMediaSettings();let MA=d?7:2;(o._room.preferHW||(cA=o._room.scheduleResult.config)!=null&&cA.preferHW)&&l&&l.profile.width*l.profile.height>=921600&&o.singlePC.useHWEncoder(!0,MA)}()})}publishByTransceiver(A){let{localAudioTrack:e,localVideoTrack:o,smallTrack:a,isAuxiliary:l}=A;if(!Xd())return;this._log.info("publish by transceiver");let d=o?.outMediaTrack,h=e?.outMediaTrack,y=this._peerConnection.getTransceivers(),S=[],k=[],V=(cA,CA,MA)=>{var ie;let pe=y[CA].sender.replaceTrack(MA);k.push(CA),(ie=this.singlePC)!=null&&ie.enableInsertableStreams&&pe.then(()=>this.createEncodedStreams(y[CA].sender,cA)),this.initSenderTransform(y[CA].sender,cA),S.push(pe)};h&&V(e.mediaType,0,h),d&&V(o.mediaType,l?3:1,d),o!=null&&o.small&&S.push(this.publishSmall(this._room.videoManager.smallMode,o));let J=this.singlePC.setTransceiverDirection(Xn.SENDONLY,k);return S.push(J),Promise.all(S)}getTrackByMediaType(A){switch(A){case 1:return this.localMainAudioTrack||this._room.localMainAudioTrack;case 4:case 8:return this.localMainVideoTrack||this._room.localMainVideoTrack;case 2:return this.localAuxVideoTrack||this._room.localAuxVideoTrack;default:return null}}createEncodedStreams(A,e){var o,a;if(this.singlePC.insertableStreamsAbortMap.has(A))return;let l=A.createEncodedStreams(),d=new AbortController;(o=this.singlePC)==null||o.addAbortController(A,d),((a=this.getTrackByMediaType(e))!=null&&a.enableEncodeFrame?l.readable.pipeThrough(new TransformStream({transform:(h,y)=>{var S,k;let V=this.getTrackByMediaType(e);if(!V||!V.encodeFrame)return y.enqueue(h);V.isAudio?y.enqueue(V.enableEncodeFrame?V.encodeFrame(h):h):y.enqueue((S=this.singlePC)!=null&&S.isUsingH264||(k=this.singlePC)!=null&&k.isUsingH265?V.encodeFrame(h,e===8):h)}}),d):l.readable).pipeTo(l.writable,d).catch(h=>{this._log.debug("encoded stream error",h),h!=="destroy"&&this._log.warn(h)})}initSenderTransform(A,e){if(!(this._peerConnection&&this.singlePC&&this.singlePC.scriptTransformWorker&&o_))return;let o=e!==2,a=e===8;A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!1,isAudio:e===1,isMain:o,isSmall:a}))}enableSmall(A){return WA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return WA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){var l;if(!o.singlePC)return;if(e==="canvas"&&!i_())return void o._log.warn("canvas mode small stream is not supported");let d=o._peerConnection.getTransceivers(),{sender:h}=d[2],y=yield o.doPublishSmall(e,a),S=e==="canvas"?524700:524701;si.addSuccessEvent({key:S}),y?((l=o.singlePC)!=null&&l.enableInsertableStreams&&o.createEncodedStreams(h,8),o.initSenderTransform(h,8),yield o.singlePC.setTransceiverDirection(Xn.SENDONLY,[2]),o.updateMediaSettings(),yield o.doPublishChange(),h.track&&(o._blackSmallVideoDetectionId=tv.start({track:h.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let k=e==="canvas"?524700:524701;si.addFailedEvent({key:k,error:10002}),tv.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):si.addFailedEvent({key:S,error:10001})}()})}doPublishSmall(A){return WA(this,arguments,function(e){var o=this;let a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.localMainVideoTrack;return function*(){if(!o.singlePC)return null;o._log.info("publish small",e);let l=o._peerConnection.getTransceivers(),{sender:d}=l[2];if(e==="canvas"&&o._room.videoManager.smallTrack)return yield d.replaceTrack(o._room.videoManager.smallTrack),"canvas";if(e==="api"&&a!=null&&a.outMediaTrack&&a!=null&&a.small){yield d.replaceTrack(a?.outMediaTrack);let h=d.getParameters(),y=N0(a?.profile,a?.small);return o._log.info("small scaleResolutionDownBy",y),h.encodings[0].scaleResolutionDownBy=y,d.setParameters(h),"api"}return o._log.warn("small track can not be enabled, smallMode: ".concat(o._room.videoManager.smallMode,", smallTrack: ").concat(!!o._room.videoManager.smallTrack,", bigVideoTrack: ").concat(!(a==null||!a.outMediaTrack))),null}()})}unpublishSmall(){return WA(this,null,function*(){this.singlePC&&(this._log.info("unpublish small"),yield this._peerConnection.getTransceivers()[2].sender.replaceTrack(null),yield this.singlePC.setTransceiverDirection(Xn.INACTIVE,[2]),this.updateMediaSettings(),yield this.doPublishChange(),tv.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return WA(this,null,function*(){var e,o;if((((e=this._room.scheduleResult.config)==null?void 0:e.profileLevelId)||{})[A.streamType==="main"?"big":"aux"]!=="high")return;let a=A.newWidth*A.newHeight>=921600&&!cy();try{yield(o=this.singlePC)==null?void 0:o.setH264ProfileLevelId(A.streamType,a)}catch(l){this._log.warn("setH264ProfileLevelId failed, ignore",l)}})}installTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{a&&(a?.on("mute",this.sendMutedFlag,this),a?.on("unmute",this.sendMutedFlag,this))})}uninstallTrackMuteEvents(){for(var A=arguments.length,e=new Array(A),o=0;o{a&&(a?.off("mute",this.sendMutedFlag,this),a?.off("unmute",this.sendMutedFlag,this))})}unpublish(A){return WA(this,arguments,function(e){var o=this;let{localAudioTrack:a,localVideoTrack:l}=e;return function*(){var d;yield(d=o.singlePC)==null?void 0:d.waitForPeerConnectionConnected();let h=l&&l===o.localAuxVideoTrack||a&&a===o.localAuxAudioTrack,y=l?.outMediaTrack,S=o._peerConnection.getSenders(),k=[];a&&(h?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield S[0].replaceTrack(null),k.push(0))),y&&(h?(yield S[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=po(fi({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),k.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=po(fi({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),k.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(Xn.INACTIVE,k),yield o.doPublishChange(!1)):yield o.doUnpublish(),o.uninstallTrackMuteEvents(a,l),l?.emit("connection-state-changed",{prevState:o._currentState,state:"DISCONNECTED"})}()})}doPublishChange(){let A=!(arguments.length>0&&arguments[0]!==void 0)||arguments[0];return WA(this,null,function*(){let e={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:Tj,data:e,responseCommand:ls.PUBLISH_STATE_CHANGE_RESULT,enableLog:A,retries:3});this.checkPublishResultCode(o.data.code,o.data.message)})}doUnpublish(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return this._signalChannel.sendWaitForResponse({command:N1,commandDesc:"unpublish",responseCommand:ls.UNPUBLISH_RESULT,enableLog:A}).catch(e=>{if(e.getCode()===Ct.API_CALL_TIMEOUT||e.getCode()===Ct.API_CALL_ABORTED)return Promise.resolve();throw e})}updateMediaSettings(){var A,e;this._mediaSettings.videoCodec=((A=this.singlePC)==null?void 0:A.videoCodec)||"h264",this._mediaSettings.videoDecCodec=((e=this.singlePC)==null?void 0:e.downlinkVideoCodec)||"h264";let o=this._publishingLocalAudioTrack||this.localMainAudioTrack||this.localAuxAudioTrack,{localMainVideoTrack:a,localAuxVideoTrack:l}=this;if(this._publishingLocalVideoTrack&&(this._isPublishingAux?l=this._publishingLocalVideoTrack:a=this._publishingLocalVideoTrack),Qy){if(o&&o.outMediaTrack){let d=o.outMediaTrack.getSettings();this._mediaSettings.audioChannel=d.channelCount||1,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=d.sampleRate||0}if(a&&a.outMediaTrack){let d=a.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=a;this._mediaSettings.videoWidth=(d.width||0)/h||0,this._mediaSettings.videoHeight=(d.height||0)/h||0,this._mediaSettings.videoFps=d.frameRate||0,this._mediaSettings.videoBps=1e3*a.profile.bitrate,a.small&&(this._mediaSettings.smallVideoWidth=a.small.width,this._mediaSettings.smallVideoHeight=a.small.height,this._mediaSettings.smallVideoFps=a.small.frameRate,this._mediaSettings.smallVideoBps=1e3*a.small.bitrate)}if(l&&l.outMediaTrack){let d=l.outMediaTrack.getSettings(),{scaleResolutionDownBy:h}=l;this._mediaSettings.auxVideoWidth=(d.width||0)/h||0,this._mediaSettings.auxVideoHeight=(d.height||0)/h||0,this._mediaSettings.auxVideoFps=d.frameRate||0,this._mediaSettings.auxVideoBps=1e3*l.profile.bitrate}}else o&&o.outMediaTrack&&(this._mediaSettings.audioChannel=o.profile.channelCount,this._mediaSettings.audioBps=1e3*o.profile.bitrate,this._mediaSettings.audioFs=o.profile.sampleRate),a&&a.outMediaTrack&&(this._mediaSettings.videoWidth=a.profile.width,this._mediaSettings.videoHeight=a.profile.height,this._mediaSettings.videoFps=a.profile.frameRate,this._mediaSettings.videoBps=1e3*a.profile.bitrate);this._log.info("updateMediaSettings: ".concat(JSON.stringify(this._mediaSettings)))}sendMediaSettings(){this.updateMediaSettings(),this._signalChannel.sendWaitForResponse({command:bj,data:this._mediaSettings,responseCommand:ls.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return WA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is adding ".concat(A.kind," track to current published local ").concat(e?YA.AUXILIARY:YA.MAIN," stream")),dQ()&&(yield this.addTrackByTransceiver(A,e))})}addTrackByTransceiver(A,e){return WA(this,null,function*(){var o;if(!A.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(A.kind===YA.AUDIO)yield a[0].sender.replaceTrack(A.outMediaTrack);else{let l=e?3:1;yield a[l].sender.replaceTrack(A.outMediaTrack),l===1&&(o=this.localMainVideoTrack)!=null&&o.small&&this._room.videoManager.smallTrack&&(yield a[2].sender.replaceTrack(this._room.videoManager.smallTrack)),a[l].direction===Xn.INACTIVE&&(yield this.singlePC.setTransceiverDirection(Xn.SENDONLY,[l]))}this.updateMediaSettings(),yield this.doPublishChange()})}removeTrack(A){return WA(this,null,function*(){if(!this._peerConnection)return;let e=A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;this._log.info("is removing ".concat(A.kind," track from current published local ").concat(e?YA.AUXILIARY:YA.MAIN," stream")),dQ()&&(yield this.removeTrackByTransceiver(A,e))})}removeTrackByTransceiver(A,e){return WA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===YA.AUDIO)yield o[0].sender.replaceTrack(null);else{let a=e?3:1;yield o[a].sender.replaceTrack(null),a===1&&this._room.videoManager.hasSmall&&(yield o[2].sender.replaceTrack(null)),yield this.singlePC.setTransceiverDirection(Xn.INACTIVE,[a])}this.updateMediaSettings(),yield this.doPublishChange()})}replaceTrack(A){return WA(this,null,function*(){var e;let o=(e=this._peerConnection)==null?void 0:e.getSenders(),a=A.outMediaTrack||A.mediaTrack;if(!o||o.length===0||!a||o.find(d=>d.track===a))return!1;let l=A.mediaType===2||A===this.localAuxAudioTrack||A===this.localAuxVideoTrack;return this._log.info("is replacing ".concat(a.kind," track ").concat(a.id," ").concat(a.label," on ").concat(l?YA.AUXILIARY:YA.MAIN," stream")),a.kind===YA.AUDIO&&o[0]&&(yield o[0].replaceTrack(a)),a.kind===YA.VIDEO&&(!l&&o[1]&&(yield o[1].replaceTrack(a)),l&&o[3]&&(yield o[3].replaceTrack(a))),!0})}setBandwidth(A){return WA(this,arguments,function(e){var o=this;let{bandwidth:a,type:l,videoType:d}=e;return function*(){if(o.singlePC){let h={};l===YA.AUDIO?h.audio=a:d==="big"?h.bigVideo=a:d==="small"?h.smallVideo=a:h.auxVideo=a,yield o.singlePC.setBandwidth(h)}}()})}sendMutedFlag(A){A===this.localAuxAudioTrack||A===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.sendWaitForResponseWithRetry({command:zz,responseCommand:ls.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&F.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:YA.VIDEO;if(this._peerConnection){let e=this._peerConnection.getSenders();if(A===YA.AUXILIARY&&e[3]&&e[3].track)return e[3].track.id;if(A===YA.VIDEO&&e[1]&&e[1].track)return e[1].track.id}if(this.localMainVideoTrack&&A===YA.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&A===YA.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,e){if(A!==0)throw A===d0?(this._log.error(cc.NOT_SUPPORTED_H264ENCODE),new gi({code:Ct.NOT_SUPPORTED_H264,message:Xo({key:vo.NOT_SUPPORTED_H264ENCODE})})):new gi({code:Ct.UNKNOWN,message:Xo({key:vo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.PUBLISH_RESULT,code:A,message:e}})})}onSinglePCReconnected(){return WA(this,null,function*(){this.isMainStreamPublished&&(this._log.warn("republish main stream"),yield this.publish({localAudioTrack:this.localMainAudioTrack,localVideoTrack:this.localMainVideoTrack,isAuxiliary:!1})),this.isAuxStreamPublished&&(this._log.warn("republish aux stream"),yield this.publish({localAudioTrack:this.localAuxAudioTrack,localVideoTrack:this.localAuxVideoTrack,isAuxiliary:!0}))})}};hi([qM(A=>{let{localVideoTrack:e}=A;e==null||delete e.retryEncodeFailed})],F1.prototype,"unpublish"),hi([p8({when(){return this.isDestroyed}})],F1.prototype,"doPublishChange"),hi([p8({when(){return this.isDestroyed}})],F1.prototype,"doUnpublish");var m8=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(m8||{}),f8=F1;function y8(A){return Object.keys(A).filter(e=>A[e])}var O1=class extends Q8{constructor(A){super(po(fi({},A),{isUplink:!1})),Y(this,"_flag",0),Y(this,"isRobot",!1),Y(this,"role","anchor"),Y(this,"fromType"),Y(this,"remoteAudioTrack"),Y(this,"remoteVideoTrack"),Y(this,"remoteAuxiliaryTrack"),Y(this,"ssrc",{audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0}),Y(this,"_prevMids"),Y(this,"jitterBufferTimeoutId",-1),Y(this,"_jitterBufferResolve"),Y(this,"_videoCodec"),Y(this,"avPlayerStateSyncManager"),Y(this,"isDataChannelSubscribed",!1),this.flag=A.flag,this.isRobot=A.isRobot||!1,this.fromType=A.fromType,this.remoteAudioTrack=new d1(this._room,this),this.remoteVideoTrack=new CL(this._room,this),this.remoteAuxiliaryTrack=new gz(this._room,this),this.avPlayerStateSyncManager=new Bj({log:this._log,audioPlayer:this.remoteAudioTrack.player,videoPlayer:this.remoteVideoTrack.player}),this.initialize()}get videoCodec(){var A;return this._videoCodec||((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}set videoCodec(A){this._videoCodec=A}get subscribeState(){return{audio:this.remoteAudioTrack.isSubscribed||this.remoteAudioTrack.isSubscribing,video:this.remoteVideoTrack.isBig&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),smallVideo:this.remoteVideoTrack.isSmall&&(this.remoteVideoTrack.isSubscribed||this.remoteVideoTrack.isSubscribing),auxiliary:this.remoteAuxiliaryTrack.isSubscribed||this.remoteAuxiliaryTrack.isSubscribing,datachannel:this.isDataChannelSubscribed}}get muteState(){return Np(this.flag,this.userId)}get flag(){return this._flag}set flag(A){var e,o,a;A!==this._flag&&(this._flag=A,(e=this.remoteAudioTrack)==null||e.onFlagChanged(),(o=this.remoteVideoTrack)==null||o.onFlagChanged(),(a=this.remoteAuxiliaryTrack)==null||a.onFlagChanged())}get hasMainStream(){return this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall}get hasAuxStream(){return this.muteState.hasAuxiliary}get isMainStreamSubscribed(){return(this.subscribeState.audio||this.subscribeState.video||this.subscribeState.smallVideo)&&(this.muteState.hasAudio||this.muteState.hasVideo||this.muteState.hasSmall)}get isAuxStreamSubscribed(){return this.subscribeState.auxiliary&&this.muteState.hasAuxiliary}get isSmallStreamSubscribed(){return this.subscribeState.smallVideo&&this.muteState.hasSmall}get isBigStreamSubscribed(){return this.subscribeState.video&&this.muteState.hasVideo}isStreamUnpublished(A){return A===YA.MAIN?!this.muteState.hasAudio&&!this.muteState.hasVideo:!this.muteState.hasAuxiliary}initialize(){this.installEvents()}close(A){clearTimeout(this.jitterBufferTimeoutId),super.close(A),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.remoteAudioTrack.close(),this.remoteVideoTrack.close(),this.remoteAuxiliaryTrack.close(),this.avPlayerStateSyncManager.destroy(),this.uninstallEvents(),this.removeDownlink()}installEvents(){this.singlePC&&(this.listeners("track").includes(this.onTrack)||this.singlePC.on("track",this.onTrack,this),this.listeners("spc-reconnected").includes(this.onSinglePCReconnected)||this.singlePC.on("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.on("decode-failed",this.onDecodeFailed,this))}uninstallEvents(){this.singlePC&&(this.singlePC.off("track",this.onTrack,this),this.singlePC.off("spc-reconnected",this.onSinglePCReconnected,this),this.remoteVideoTrack.off("decode-failed",this.onDecodeFailed,this))}emitConnectionStateChangedEvent(A){var e,o;let a=this._currentState,l=super.emitConnectionStateChangedEvent(A);return l&&a!==A&&((e=this.remoteVideoTrack)==null||e.emit("connection-state-changed",{prevState:a,state:A}),(o=this.remoteAuxiliaryTrack)==null||o.emit("connection-state-changed",{prevState:a,state:A})),l}onTrack(A){var e,o;let a=A.streams[0],{track:l,receiver:d}=A;if(!a.id.includes(this.tinyId))return;let h=a.id.includes("aux")?"auxiliary":"main";this._log.debug("ontrack ".concat(h," ").concat(l.kind));let y=YA.AUDIO;l.kind===YA.VIDEO&&(y=h===YA.MAIN?YA.VIDEO:YA.AUXILIARY);let S=this.remoteAudioTrack;y===YA.VIDEO?S=this.remoteVideoTrack:y===YA.AUXILIARY&&(S=this.remoteAuxiliaryTrack),(e=this.singlePC)==null||e.receiverRemoteTrackMap.set(d,S),(o=this.singlePC)!=null&&o.scriptTransformWorker&&this.initReceiverTransform(d,h,l.kind===YA.AUDIO),this.singlePC.enableInsertableStreams&&this.createEncodedStreams(d),S.setInputMediaStreamTrack(l)}createEncodedStreams(A){if(!this.singlePC.insertableStreamsAbortMap.has(A)){let e=A.createEncodedStreams(),o=new AbortController,a={abortController:o,enqueue:l=>{var d,h,y;let S=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(A);return S&&(S.kind!=="video"||(h=this.singlePC)!=null&&h.isUsingH264||(y=this.singlePC)!=null&&y.isUsingH265)?S.decodeFrame(l):l}};e.readable.pipeThrough(new TransformStream({transform:(l,d)=>{let h=a.enqueue(l);h&&d.enqueue(h)}})).pipeTo(e.writable,o).catch(l=>{l!=="destroy"&&this._log.warn(l)}),this.singlePC.addAbortController(A,o)}}initReceiverTransform(A,e,o){!this._peerConnection||!this.singlePC||!this.singlePC.scriptTransformWorker||A.transform||(A.transform=new RTCRtpScriptTransform(this.singlePC.scriptTransformWorker,{isReceiver:!0,isAudio:o,userId:this.userId,streamType:e}))}subscribe(A,e){return WA(this,null,function*(){var o,a;try{let l=!0;if(this._log.info("subscribe ".concat(e," ").concat(y8(A))),this.hasSSRC){let y="subscribe_change";Object.values(A).find(S=>S===!0)||(y="unsubscribe"),yield this.sendSubscription(y,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let y=this.singlePC.autoSubscribedUserMap.get(this.userId);if(y){this.singlePC.autoSubscribedUserMap.delete(this.userId);let S=(a=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:a[y.groupIndex];S&&(this.ssrc={audio:S.audioSsrc,video:S.bigVideoSsrc,videoRtx:S.bigVideoRtxSsrc,auxiliary:S.auxVideoSsrc,auxiliaryRtx:S.auxVideoRtxSsrc},l=!1)}}yield this.doSubscribe(A,l),this.checkTrackEnded(A)}let{user:d,mediaTrack:h}=this.remoteVideoTrack;A.smallVideo&&h?(si.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=tv.start({track:h,isUplink:!1,room:this._room,userId:this.userId,onBlack:()=>{this._log.warn("small video is black, auto change to big"),this._room.changeType(!1,d),si.addFailedEvent({key:524702}),tv.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(tv.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)}catch(l){throw this._room.isJoined&&this.isStreamUnpublished(e)?(this._log.warn("".concat(l.message," ").concat(JSON.stringify(this.muteState))),new gi({code:Ct.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):l}})}checkTrackEnded(A){var e,o,a;if((A.audio&&((e=this.remoteAudioTrack.mediaTrack)==null?void 0:e.readyState)==="ended"||A.video&&((o=this.remoteVideoTrack.mediaTrack)==null?void 0:o.readyState)==="ended"||A.auxiliary&&((a=this.remoteAuxiliaryTrack.mediaTrack)==null?void 0:a.readyState)==="ended")&&this.singlePC&&!this.singlePC.isReconnecting){if(this._log.warn("remote track ended start spc reconnect"),uE&&td<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return WA(this,arguments,function(e){var o=this;let{remoteTracks:a,streamType:l}=e;return function*(){var d;if(l==="main"&&!o.isMainStreamSubscribed||l==="auxiliary"&&!o.isAuxStreamSubscribed)return void o._log.info("".concat(l," stream already unsubscribed"));let h=fi({},o.subscribeState);a.forEach(S=>{switch(S.mediaType){case 1:h.audio=!1;break;case 4:h.video=!1;break;case 8:h.smallVideo=!1;break;case 2:h.auxiliary=!1}});let y="subscribe_change";Object.values(h).find(S=>S===!0)||(y="unsubscribe"),o._log.info("".concat(y==="unsubscribe"?y:"subscribe"," ").concat(l," [").concat(y8(h),"]")),y==="unsubscribe"&&((d=o.singlePC)==null||d.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(y,h),l==="main"&&(tv.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),y==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return WA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=po(fi({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return WA(this,null,function*(){let A=po(fi({},this.subscribeState),{datachannel:!1});yield this.sendSubscription("unsubscribe",A),yield this.removeDownlink()})}sendSubscription(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscribeState,o={srcTinyId:this.tinyId,srcUserId:this.userId},a=Nj,l=ls.UNSUBSCRIBE_RESULT;return A==="subscribe_change"&&(o={audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:e.datachannel,srcTinyId:this.tinyId},a=Gj,l=ls.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponseWithRetry({command:a,data:o,responseCommand:l,timeout:1e4,retries:3}).then(d=>{let{data:h}=d;if(h.code!==0){let y=new gi({code:h.code,message:Xo({key:vo.ERROR_MESSAGE,data:{type:A,message:h.message}})});throw this._log.error(y),y}})}getMainStreamVideoTrackId(){return this.remoteVideoTrack&&this.remoteVideoTrack.mediaTrack?this.remoteVideoTrack.mediaTrack.id:""}getAuxStreamVideoTrackId(){return this.remoteAuxiliaryTrack&&this.remoteAuxiliaryTrack.mediaTrack?this.remoteAuxiliaryTrack.mediaTrack.id:""}setDelay(A){let{audioDelay:e,videoDelay:o}=A;this.remoteAudioTrack.stat.end2EndDelay=e,this.remoteVideoTrack.stat.end2EndDelay=o}onSinglePCReconnected(){return WA(this,null,function*(){(this.ssrc.audio||this.ssrc.video||this.ssrc.auxiliary||this.isDataChannelSubscribed)&&(this._log.warn("resubscribe ".concat(JSON.stringify(this.subscribeState))),yield this.doSubscribe(this.subscribeState),this.remoteAudioTrack.checkDecodeResult(),this.remoteVideoTrack.checkDecodeResult(),this.remoteAuxiliaryTrack.checkDecodeResult())})}get hasSSRC(){return this.ssrc.audio&&this.ssrc.video&&this.ssrc.auxiliary}doSubscribe(){return WA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.subscribeState,o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return function*(){var a,l;if(A.singlePC){A.singlePC.addDownlinkQueue.add(A.tinyId),yield A.singlePC.waitForPeerConnectionConnected();try{if(o||!A.hasSSRC){let d={audioSsrc:sB(),bigVideoSsrc:sB(),bigVideoRtxSsrc:sB(),auxVideoSsrc:sB(),auxVideoRtxSsrc:sB()},{audioSsrc:h,bigVideoSsrc:y,bigVideoRtxSsrc:S,auxVideoSsrc:k,auxVideoRtxSsrc:V}=d;A.ssrc={audio:h,video:y,videoRtx:S,auxiliary:k,auxiliaryRtx:V},A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids});try{let J=yield A._signalChannel.sendWaitForResponseWithRetry({command:A8,responseCommand:ls.SPC_SUBSCRIBE_RESULT,data:{srcUserId:A.userId,srcTinyId:A.tinyId,audio:e.audio,bigVideo:e.video,auxVideo:e.auxiliary,smallVideo:e.smallVideo,customData:(a=e.datachannel)!=null&&a,ssrc:d},retries:3,retryTimeout:0});if(J.data.code!==0&&J.data.code!==-10036)throw new gi({code:J.data.code,message:J.data.message});A.isDataChannelSubscribed=(l=e.datachannel)!=null&&l}catch(J){throw yield A.removeDownlink(),J}return}A.singlePC.addDownlinkQueue.delete(A.tinyId),yield A.singlePC.addDownlink({userId:A.userId,tinyId:A.tinyId,ssrc:A.ssrc,prevMids:A._prevMids})}finally{if((e.audio||e.video||e.smallVideo||e.auxiliary||!e.datachannel)&&CQ){let{main:d,aux:h}=A._room.jitterBufferDelay||{},{jitterDelay:y=d,jitterDelayAux:S=h}=A._room.scheduleResult.config||{};(kn(y)||kn(S))&&A.setJitterBufferDelay({mainDelay:y,auxDelay:S})}}}}()})}removeDownlink(){return WA(this,null,function*(){this.singlePC&&(this.isDataChannelSubscribed=!1,this.ssrc={audio:0,video:0,videoRtx:0,auxiliary:0,auxiliaryRtx:0},this.singlePC.removeDownlinkQueue.delete(this.tinyId),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve&&(this._jitterBufferResolve(),this._jitterBufferResolve=void 0),this.setJitterBufferDelay({mainDelay:0,auxDelay:0}),this._prevMids=yield this.singlePC.removeDownlink(this.userId))})}setJitterBufferDelay(A){let{mainDelay:e,auxDelay:o}=A;if(!CQ||!this.singlePC||!this._peerConnection||$E(e)&&$E(o))return Promise.resolve();this._log.info("set jitterBuffer main: ".concat(e," aux: ").concat(o));let a=this.singlePC.getReceiversByUserId(this.userId);return kn(e)&&(this.remoteAudioTrack.jitterBufferDelay=e,this.remoteVideoTrack.jitterBufferDelay=e),kn(o)&&(this.remoteAuxiliaryTrack.jitterBufferDelay=o,$E(e)&&(this.remoteAudioTrack.jitterBufferDelay=o)),new Promise(l=>{this._jitterBufferResolve=l,this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:a,resolve:l})})}doSetJitterBufferDelay(A){let{mainDelay:e,auxDelay:o,receivers:a,resolve:l}=A;try{if(e===0&&o===0)return a.forEach(d=>d.jitterBufferTarget=0),this._jitterBufferResolve=void 0,l();if(a.forEach(d=>{var h;let y=d.track===this.remoteAuxiliaryTrack.outMediaTrack||$E(e)&&d.track===this.remoteAudioTrack.outMediaTrack;if(y&&$E(o)||!y&&$E(e))return;let S=y?o||0:e,k=(d.jitterBufferTarget||0)+100;k>S||(d.jitterBufferTarget=k,this._log.debug("set ".concat(y?"aux ":"").concat((h=d?.track)==null?void 0:h.kind," jitterBuffer delay ").concat(k," -> ").concat(S)))}),!a.find(d=>{let h=d.track===this.remoteAuxiliaryTrack.outMediaTrack?o||0:e;return d.jitterBufferTarget{this.doSetJitterBufferDelay({mainDelay:e,auxDelay:o,receivers:a,resolve:l})},1e3)}catch(d){this._log.warn("set jitterBuffer delay error: ".concat(d)),clearTimeout(this.jitterBufferTimeoutId),this._jitterBufferResolve=void 0,l()}}get audioReceiver(){var A;return((A=this.singlePC)==null?void 0:A.getReceiversByUserId(this.userId)[0])||null}onDecodeFailed(){this._room.downlinkVideoCodec==="h265"&&this._room.requestRemoteFallbackToH264()}};hi([sL(),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let h=y=>{this.off("closed",h),d(new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.CONNECTION_ABORTED,data:y})}))};this.on("closed",h),A.apply(this,o).then(l,d).finally(()=>{this.off("closed",h)})})})],O1.prototype,"subscribe"),hi([sL()],O1.prototype,"unsubscribe"),hi([Dy(()=>"jitter")],O1.prototype,"setJitterBufferDelay");var EsA=O1,dsA=gc(jl()),D8=class cX extends dsA.EventEmitter{constructor(e,o){super(),this.room=e,this.signalChannel=o,Y(this,"log"),Y(this,"cmdIdSeqMap",new Map),Y(this,"messageMap",new Map),this.log=pA.createLogger({parent:e.getLogger(),id:"cmm",userId:e.userId}),this.onReceiveMsg=this.onReceiveMsg.bind(this),o.on(ls.RECEIVE_CUSTOM_MSG,this.onReceiveMsg),this.room.on("peer-leave",a=>{let{userId:l}=a;[...this.messageMap.keys()].forEach(d=>{d.split("_").slice(0,-1).join("_")===l&&this.messageMap.delete(d)})})}send(e){let{cmdId:o,data:a}=e,l=this.cmdIdSeqMap.get(o)||Math.floor(16383*Math.random()),d={cmdId:o,msg:btoa(String.fromCharCode(...new Uint8Array(a))),ordered:!0,reliable:!0,streamSeq:l};this.cmdIdSeqMap.set(o,l+1),this.signalChannel.send(koA,d),this.log.debug("send custom msg: ".concat(JSON.stringify(d)))}onReceiveMsg(e){let{data:o}=e.data,a=this.room.tinyIdToUserIdMap.get(o.srcTinyId);if(a){let l={userId:a,cmdId:o.cmdId,seq:o.streamSeq,data:Uint8Array.from(atob(o.msg),d=>d.charCodeAt(0)).buffer};if(o.ordered){let d="".concat(a,"_").concat(l.cmdId),h=this.messageMap.get(d);if(h&&h.lastSeq!==0)if(Math.abs(h.lastSeq-l.seq)>cX.SEQ_INTERVAL)this.messageMap.set(d,{lastSeq:l.seq,cachedMessageMap:new Map}),this.emitMessage(l);else if(l.seq>h.lastSeq){if(l.seq===h.lastSeq+1)this.emitMessage(l);else if(!h.cachedMessageMap.has(l.seq)){let y=setTimeout(()=>this.emitMessage(l,!0),5e3);h.cachedMessageMap.set(l.seq,{message:l,timeoutId:y})}}else this.log.debug("drop message ".concat(l.userId,"-").concat(l.cmdId,"-").concat(l.seq));else h||(h={lastSeq:0,cachedMessageMap:new Map},this.messageMap.set(d,h),setTimeout(()=>this.emitMessage(l,!0),100)),h.cachedMessageMap.set(l.seq,{message:l})}else this.emit("message",l)}else{this.log.warn("receive msg from unknown user, wait peer-join tinyId: ".concat(o.srcTinyId));let l=d=>{d.tinyId===o.srcTinyId&&(this.room.off("peer-join",l),this.onReceiveMsg(e))};this.room.on("peer-join",l),OC(2e3).then(()=>this.room.off("peer-join",l))}}emitMessage(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];var a;let l=this.messageMap.get("".concat(e.userId,"_").concat(e.cmdId)),d=e;if(l){if(o){let y=[...l.cachedMessageMap.values()].sort((S,k)=>S.message.seq-k.message.seq);y[0]&&(d=y[0].message)}l.lastSeq!==0&&d.seq-l.lastSeq>1&&this.log.debug("msg lost userId: ".concat(d.userId," seq: ").concat(l.lastSeq," -> ").concat(d.seq)),l.lastSeq=d.seq,clearTimeout((a=l.cachedMessageMap.get(d.seq))==null?void 0:a.timeoutId),l.cachedMessageMap.delete(d.seq)}this.log.debug("receive custom msg: ".concat(JSON.stringify(d))),this.emit("message",d);let h=l?.cachedMessageMap.get(d.seq+1);h&&this.emitMessage(h.message)}};Y(D8,"SEQ_INTERVAL",300);var CsA=D8,{isString:S8,isUndefined:iv,getNetworkType:hsA,isEmpty:BsA}=Hd,Ny=class extends isA{constructor(A){super(A),Y(this,"_businessInfo"),Y(this,"userManager"),Y(this,"_version"),Y(this,"_heartbeat",-1),Y(this,"_lastHeartBeatTime",-1),Y(this,"_stats"),Y(this,"_joinTimeout",-1),Y(this,"_firstPublishedList",null),Y(this,"_joinReject",null),Y(this,"_isRelayChanged",!1),Y(this,"sdpSemantics"),Y(this,"signalChannel",null),Y(this,"uplinkConnection",null),Y(this,"singlePC",null),Y(this,"enableSPC",LM),Y(this,"_changeBigSmallRecords",new Map),Y(this,"networkQuality"),Y(this,"_iceTransportPolicy"),Y(this,"forceRelay",!1),Y(this,"_turnServers",[]),Y(this,"_iceServersFromJoin"),Y(this,"_syncUserListInterval",-1),Y(this,"_smallStreamConfig",{bitrate:100,frameRate:15,height:120,width:160}),Y(this,"enableSEI",!1),Y(this,"_enableAudioVolumeEvaluation",!1),Y(this,"_audioVolumeIntervalId",0),Y(this,"_enableMultiAuxStream",!1),Y(this,"_pureAudioPushMode",!1),Y(this,"_customMessageManager"),Y(this,"_enableDataChannel",!1),Y(this,"preferHW",!1),Y(this,"healthDetector"),Y(this,"playoutDelay"),Y(this,"jitterBufferDelay"),Y(this,"_updateAudioLevelTaskId",-1),Y(this,"switchRoomSubedReq"),Y(this,"resolveSwitchRoomSubedReq"),Y(this,"enableVolumeControlInIOS"),Y(this,"capturedLocalMainAudioTrack"),Y(this,"capturedLocalMainVideoTrack"),Y(this,"capturedLocalAuxVideoTrack"),Y(this,"PRELINK_EXPIRED_TIME",3e5),Y(this,"PRELINK_TIMEOUT",1e4),Y(this,"prelinkTimeoutId",null),Y(this,"firewallDetector"),this.firewallDetector=new OiA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new YoA(this,this._log),this.userManager=new UiA(this.userId,this._log),this._version=qd,this.sdpSemantics=E0,iv(A.sdpSemantics)?re.isUnifiedPlanDefault()&&(this.sdpSemantics=$S):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(hsA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!iv(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&LM,!iv(A.enableSPC)&&LM&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new gsA(this)}get isMainStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isMainStreamPublished)}get isMainAudioPublished(){var A;return!((A=this.uplinkConnection)==null||!A.localMainAudioTrack)}get isAuxStreamPublished(){var A;return!((A=this.uplinkConnection)==null||!A.isAuxStreamPublished)}get hasAuxStream(){return[...this.remotePublishedUserMap.values()].findIndex(A=>A.muteState.hasAuxiliary)>=0}get userMap(){return this.userManager.userMap}get remotePublishedUserMap(){return this.userManager.remotePublishedUserMap}get tinyIdToUserIdMap(){return new Map([...this.userMap.values()].map(A=>[A.tinyId,A.userId]))}get videoCodec(){var A;return((A=this.singlePC)==null?void 0:A.videoCodec)||"h264"}get downlinkVideoCodec(){var A;return((A=this.singlePC)==null?void 0:A.downlinkVideoCodec)||"h264"}join(A,e,o){return WA(this,null,function*(){return this.userManager.mySelfId=this.userId,this.userManager.on("1",a=>{this.emit("peer-join",a)}),this.userManager.on("8",a=>{this.emit("asr-robot-peer-join",a)}),this.userManager.on("9",a=>{this.emit("asr-robot-peer-leave",a)}),this.userManager.on("2",a=>{let{userId:l,reason:d}=a;this.closeDownLinkConnection(l,"remote user exitRoom"),this.emit("peer-leave",{userId:l,reason:d})}),this.userManager.on("3",this.createDownlinkConnection,this),this.userManager.on("5",this.closeDownLinkConnection,this),this.userManager.on("6",a=>{var l=bx(a,[]);F.emit(nA.REMOTE_PUBLISH_STATE_CHANGED,fi({room:this},l)),this.emit("remote-publish-state-changed",fi({},l))}),this.joinParams=A,Nr(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((a,l)=>WA(this,null,function*(){var d,h;this._joinReject=l;try{this.checkDestroy();try{yield Promise.all([this.initialize(),this.initSinglePC()])}catch(S){if(!(S instanceof gi&&S.code===Ct.SPC_INITIALIZED_FAILED))return l(S);(d=this.signalChannel)==null||d.destroy(),yield this.initialize()}let y=ko();yield this.doJoin(A,(h=this.singlePC)==null?void 0:h.clientAbility),si.addSuccessEvent({key:521708,cost:ko()-y}),a(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(y){si.addFailedEvent({key:521708,error:y}),l(y)}this._joinReject=null}))})}initSinglePC(){return WA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new Ty({signalChannel:this.signalChannel,room:this,enableDataChannel:this._enableDataChannel}),this.singlePC.on("sei-message",A=>this.emit("sei-message",A)),this.singlePC.on("dump",A=>this.emit("dump",A)),this.singlePC.once("error",()=>this.fallbackToMPC()),this.singlePC.on("data_channel_msg",A=>{let e=new TextDecoder().decode(A.data.data||A.data);try{this.emit("data-channel-message",{data:JSON.parse(e)})}catch{}});try{return yield this.singlePC.initialize()}catch(A){throw this.fallbackToMPC(),new gi({code:Ct.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,e){return new Promise((o,a)=>WA(this,null,function*(){var l,d,h,y,S,k,V,J;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(_1,MA=>{this.clearJoinTimeout(),F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this,error:MA}),a(MA)}),Nr((d=(l=this.scheduleResult)==null?void 0:l.config)==null?void 0:d.singlePC)&&LM&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((y=(h=this.scheduleResult)==null?void 0:h.config)!=null&&y.jitterDelay)&&!((k=(S=this.scheduleResult)==null?void 0:S.config)!=null&&k.jitterDelayAux)||!CQ)&&e&&this.playoutDelay&&(this._log.info("set playoutDelay",JSON.stringify(this.playoutDelay)),e.playoutDelay=this.playoutDelay);let cA={roomId:String(A.roomId||A.strRoomId),useStringRoomId:this.useStringRoomId,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel,trtcRole:A.role,trtcScene:this.scene==="live"?2:1,sdpSemantics:this.sdpSemantics,version:this._version,ua:navigator&&navigator.userAgent||"",terminalType:Cn(),netType:Wf(),bussinessInfo:this._businessInfo,ability:e,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&t_(),transcription:this._enableDataChannel,downUseVp8:((V=this.scheduleResult.config)==null?void 0:V.downUseVp8)||!1};this._log.debug("join room signal data: ".concat(JSON.stringify(cA)));let CA=5e3;(J=this.scheduleResult.config)!=null&&J.enterRoomTimeout&&this.scheduleResult.config.enterRoomTimeout>=1&&(CA=1e3*this.scheduleResult.config.enterRoomTimeout),this._joinTimeout=window.setTimeout(()=>{a(new gi({code:Ct.JOIN_ROOM_FAILED,message:Xo({key:vo.JOIN_ROOM_TIMEOUT})}))},CA),F.emit(nA.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?NoA:hoA,cA),this.signalChannel.once(ls.JOIN_ROOM_RESULT,MA=>WA(this,null,function*(){this.clearJoinTimeout();let{code:ie,message:pe,data:qe,tinyId:we}=MA.data;F.emit(nA.JOIN_RECEIVED_CMD_RES,{room:this,code:ie}),ie===0?(this._log.info("Join room success, start heartbeat"),we&&(this.tinyId=we),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=qe.publishers,this._iceServersFromJoin=qe.iceServer?[qe.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var Di;(Di=this.singlePC)==null||Di.connect(po(fi({},qe.ability),{useVp8:qe.ability.useVp8||!!A.useVp8,useH265:qe.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat(ie," error: ").concat(pe)),a(new gi({code:Ct.JOIN_ROOM_FAILED,extraCode:ie,message:Xo({key:vo.JOIN_ROOM_FAILED,data:{error:pe,code:ie}})})))}))}))}reJoin(){return WA(this,null,function*(){if(this.isJoined)try{this._log.warn("reJoin pending: ".concat(this.joinParams.roomId));let A,e=[];if(this.singlePC&&(this.singlePC.close(),this.singlePC=null,e.push(this.initSinglePC().then(o=>(A=o,o)))),this.signalChannel&&(this.signalChannel.close(),e.push(this.signalChannel.connect())),yield Promise.all(e),yield this.doJoin(po(fi({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),sn.logSuccessEvent({userId:this.userId,eventType:Ja.REJOIN}),this.singlePC){let o=a=>{var l;a.state==="CONNECTED"&&((l=this.singlePC)==null||l.off(y_.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof f8&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(y_.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof L1&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),sn.logFailedEvent({userId:this.userId,eventType:Ja.REJOIN,error:A}),this.emit("error",new gi({code:Ct.JOIN_ROOM_FAILED,message:Xo({key:vo.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return WA(this,null,function*(){var e,o;if(!(A!=null&&A.isPrelink)&&this.prelinkPromise&&(yield this.prelinkPromise),(e=this.signalChannel)!=null&&e.isPrelinkValid(this.sdkAppId,this.userId,this.userSig))return this._log.info("reuse prelink signal channel"),void this.signalChannel.consumePrelink();(o=this.signalChannel)!=null&&o.prelink&&this.signalChannel.close();let a,{mainUrl:l,backupUrl:d}=this.getSignalChannelUrl(),h=this.signalChannel||function(S){return[...G1.values()].find(V=>V.room.userId===S&&!V.room.isJoined)||null}(this.userId),y=!!(h&&h.isConnected&&h.keepAlive&&h.userId===this.userId);return Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(a=this.scheduleResult.domains[0]),this._log.info("".concat(y?"reuse":"setup"," signal channel")),y?(h.url=l,h.backupUrl=d,h.room.setSignalChannel(null),h.room=this,this.signalChannel=h):(h&&h.close(),this.signalChannel=new e8({sdkAppId:this.sdkAppId,userId:this.userId,userSig:this.userSig,url:l,backupUrl:d,room:this,signalDomainWhenUnifiedProxy:this.proxy_unified?a:void 0,prelink:A?.isPrelink}),this._customMessageManager=new CsA(this,this.signalChannel),this._customMessageManager.on("message",S=>{this.emit("custom-message",S)})),this.networkQuality||(this.networkQuality=new n8({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(n8.EVENT_NETWORK_QUALITY,S=>{var k;this.emit("network-quality",S),(k=this.singlePC)==null||k.detectTCPAndUDP(S)})),nd(this,this.signalChannel).add(_j,S=>{F.emit(nA.SIGNAL_CONNECTION_STATE_CHANGED,fi({room:this},S)),this.emit("signal-connection-state-changed",S)}).add(EoA,S=>{this.reset(),this.emit("error",S)}).add(ls.PEER_JOIN,S=>{let{srcTinyId:k,userId:V,role:J,fromType:cA}=S.data.data;this.userManager.addUser({userId:V,tinyId:k,role:J,fromType:cA})}).add(ls.PEER_LEAVE,S=>{let{userId:k,reason:V=0}=S.data.data;this.userManager.deleteUser(k,V)}).add(ls.UPDATE_REMOTE_MUTE_STAT,S=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(S.data)}).add(ls.CLIENT_BANNED,S=>{let k=S.data.data,{reason:V}=k;if(sn.uploadEvent({log:"stat-banned:".concat(V),userId:this.userId}),V==="user_time_out")return this._log.warn("".concat(V," last heart beat time: ").concat(this._lastHeartBeatTime," interval: ").concat(Date.now()-this._lastHeartBeatTime,", visibility: ").concat(document.visibilityState)),void this.reJoin();this._log[V==="kick"?"error":"info"]("user was banned because of [".concat(V,"]")),this.reset(),this.emit("banned",{reason:V})}).add(ls.SEND_SWITCH_ROOM_SUBED_REQ,S=>{if(!this.singlePC)return;let{subList:k}=S.data.data;this._log.info("auto subscribe ".concat(zd(k,{keysToInclude:["userId"]}))),k.forEach(V=>{this.singlePC.autoSubscribedUserMap.set(V.userId,V)}),this.resolveSwitchRoomSubedReq()}).add(ls.FALLBACK_CODEC,S=>WA(this,null,function*(){var k,V,J,cA,CA;let MA=S.data.data;((k=MA.videoControlInfo)==null?void 0:k.enableH265Enc)===0&&((V=this.singlePC)==null?void 0:V.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((J=MA.videoControlInfo)==null?void 0:J.enableH265Enc)),si.addCount({key:513e3}),yield(cA=this.singlePC)==null?void 0:cA.switchVideoEncoder("h264"),yield(CA=this.uplinkConnection)==null?void 0:CA.sendMediaSettings())})),this.signalChannel.once(Kz,S=>{this.tinyId=S.signalInfo.tinyId,F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this})}),F.emit(nA.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),y&&F.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this}),y})}setSignalChannel(A){this.signalChannel=A,A||Ln(this)}leave(){return WA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),F.emit(nA.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(BoA),this.switchRoomSubedReq=void 0,this._changeBigSmallRecords.clear()})}clearNetworkQuality(){this.networkQuality&&(this.networkQuality.stop(),delete this.networkQuality)}closeConnections(){this.remotePublishedUserMap.forEach(A=>{this.closeDownLinkConnection(A.userId,"you exitRoom")})}clearJoinTimeout(){clearTimeout(this._joinTimeout),this._joinTimeout=-1}startHeartbeat(){this._heartbeat===-1&&(this._heartbeat=Gr.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),Gr.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return WA(this,null,function*(){var A;let e=this.badCaseDetector.getMonitorFreeze(),o=yield this._stats.getStatsReport({uplinkConnection:this.uplinkConnection,downlinkConnections:this.remotePublishedUserMap,freezeMap:e});this.badCaseDetector.resetMonitor();let a=(A=this.signalChannel)!=null&&A.isConnected?function(d){if(C_.has(d)){let h=C_.get(d).map(y=>({uint32_event_id:y.eventId,uint64_date:y.timestamp,str_userid:y.remoteUserId,uint32_param1:y.param1,uint32_param2:y.param2,uint32_video_stream_type:y.streamType}));return C_.delete(d),h}return[]}(this.userId):[],l=po(fi({str_sdk_version:s0,uint64_datetime:new Date().getTime(),msg_user_info:{str_identifier:this.userId,uint64_tinyid:this.tinyId},msg_event_msg:a,str_acc_ip:this.getSignalInfo().relayIp,str_client_ip:this.getSignalInfo().clientIp},o),{msg_device_info:fi({uint32_terminal_type:15,str_device_name:cQ(),str_os_version:"",uint32_net_type:Wf()},o.msg_device_info)});if(this.heartbeatReport=l,this.heartbeatCount++,F.emit(nA.HEARTBEAT_REPORT,{room:this,report:l}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(QoA,l);let d=Date.now();this._lastHeartBeatTime>0&&d-this._lastHeartBeatTime>1e4&&this._log.warn("heartbeat took ".concat(d-this._lastHeartBeatTime)),this._lastHeartBeatTime=d,this.signalChannel.isOnline||(this._log.warn("signal channel is not online"),this.signalChannel.startReconnection())}this.emit("heartbeat-report",po(fi({},l),{bytes_sent:this._stats.totalBytesSent+this.signalChannel.bytesSent,bytes_received:this._stats.totalBytesReceived+this.signalChannel.bytesReceived}))}!this._isRelayChanged&&this.isRelayMaybeFailed()&&(this.reJoin(),this._isRelayChanged=!0)})}onPublishedUserList(A){if(!this.isJoined)return;let e=!1,o=A.data.userList||[],a=A.data.mixRobotList||[],l=[];for(let h of o){if(h.flag===Gb)continue;let{userId:y,srcTinyId:S,flag:k,fromType:V}=h;y===this.userId&&(e=!0,this.uplinkConnection&&(this.uplinkConnection.flag=k),this.localPublishFlag!==k&&(this.localPublishFlag=k,this.emit("local-publish-flag-changed",k))),l.push({userId:y,tinyId:S,flag:k,fromType:V})}let d=[...a.map(h=>{let{userId:y,srcTinyId:S,flag:k,mixUserList:V,fromType:J}=h;return{userId:y,tinyId:S,flag:k,isRobot:!0,mixUserList:V,fromType:J}}),...l];d.forEach(h=>{let{userId:y}=h,S=this.remotePublishedUserMap.get(y);S&&this.checkSubscribeBigSmallVideo(S)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,d.push(A.data.fakeMixUser)),F.emit(nA.RECEIVED_PUBLISHED_USER_LIST,{room:this,publishedUserList:d}),e||(this.localPublishFlag=0,this.emit("local-publish-flag-changed",0)),this.userManager.setRemotePublishedUserList(d)}closeUplink(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"you unpublished";this.uplinkConnection&&(this.localTracks.size>0&&this.uplinkConnection.doUnpublish().catch(()=>{}),this.uplinkConnection.close(A),A==="you exitRoom"&&(this.uplinkConnection.destroy(),this.uplinkConnection=null),this.uplinkConnection instanceof L1&&(this.uplinkConnection=null)),this.localTracks.forEach(e=>e.unpublish()),this.localTracks.clear()}createDownlinkConnection(A){let{userId:e,tinyId:o,flag:a,isRobot:l,fromType:d}=A,h=new(this.singlePC?EsA:o8)({userId:e,tinyId:o,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:a,isRobot:l,fromType:d});this.userManager.addRemotePublishedUser(h),this.installDownlinkEvents(h,e),this.emit("remote-published",h)}closeDownLinkConnection(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"remote user unpublished",o=this.remotePublishedUserMap.get(A);o&&(o.close(e),this.emit("remote-unpublished",o))}installDownlinkEvents(A,e){A.on("error",o=>{let a=o.getCode();a!==Ct.ICE_TRANSPORT_ERROR&&(a===Ct.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(e),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",po(fi({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=Gr.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){Gr.clearTask(this._syncUserListInterval),this._syncUserListInterval=-1}syncUserList(){return this.getUserList().then(A=>{this.userManager.setUserList(A)}).catch(A=>{this._log.debug("sync user list failed: ".concat(A))})}getUserList(){var A;return(A=this.signalChannel)!=null&&A.isConnected?this.signalChannel.sendWaitForResponse({command:woA,responseCommand:ls.USER_LIST_RES,enableLog:!1,timeout:2e3}).then(e=>{let{data:o}=e,{code:a,message:l}=o;if(a===0)return(o.data&&o.data.userList||[]).map(d=>{let{userId:h,srcTinyId:y,role:S,fromType:k}=d;return{userId:h,tinyId:y,role:S,fromType:k}});throw Xo({key:vo.SIGNAL_RESPONSE_FAILED,data:{signalResponse:ls.USER_LIST_RES,code:a,message:l}})}):Promise.reject("not connected")}getAllConnections(){let A=[...this.remotePublishedUserMap.values()];return this.uplinkConnection&&A.push(this.uplinkConnection),A}isRelayMaybeFailed(){if(this.signalChannel&&!this.signalChannel.isOnline||!t8)return!1;if(this.singlePC)return this.singlePC.reconnectionCount>6;let A=this.getAllConnections();if(A.length===0)return!1;for(let e=0;e{if(e instanceof sm&&!e.getIsReconnecting()){let o=e.getPeerConnection();o&&o.connectionState===ho.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return WA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),sn.uploadEvent({log:"stat-fallback",userId:this.userId}),this.enableSPC=!1,(A=this.singlePC)==null||A.close(),this.singlePC=null,this.isJoined&&(yield this.reJoin()),this.uplinkConnection){let e=this.uplinkConnection;this.uplinkConnection=new L1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),e.isMainStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localMainAudioTrack,localVideoTrack:e.localMainVideoTrack,isAuxiliary:!1})),e.isAuxStreamPublished&&(yield this.uplinkConnection.publish({localAudioTrack:e.localAuxAudioTrack,localVideoTrack:e.localAuxVideoTrack,isAuxiliary:!0})),e.close()}for(let e of[...this.remotePublishedUserMap.values()]){let o=new o8({userId:e.userId,tinyId:e.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI,flag:e.flag,remoteAudioTrack:e.remoteAudioTrack,remoteVideoTrack:e.remoteVideoTrack,remoteAuxiliaryTrack:e.remoteAuxiliaryTrack});this.installDownlinkEvents(o,e.userId),this.remotePublishedUserMap.set(e.userId,o),e.isMainStreamSubscribed&&(yield o.subscribe(e.subscribeState,"main")),e.isAuxStreamSubscribed&&(yield o.subscribe(e.subscribeState,"auxiliary"))}})}destroy(){this.isDestroyed||(this.signalChannel&&(this._log.info("destroying SignalChannel"),this.signalChannel.close(),this.signalChannel=null),super.destroy(),this._joinReject&&(this._joinReject(new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),Gr.clearTask(this._audioVolumeIntervalId))}switchRole(A){return WA(this,null,function*(){this.role!==A&&(A==="audience"&&this.uplinkConnection&&this.closeUplink("you switch role to audience"),yield this.doSwitchRole(A))})}doSwitchRole(A){let e={command:_oA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:ls.SWITCH_ROLE_RES,retries:1};return this._log.info("switchRole signal data: ".concat(JSON.stringify(e.data))),this.signalChannel.sendWaitForResponseWithRetry(e).then(o=>{let{code:a,message:l}=o.data;if(a!==0)throw new gi({code:Ct.SWITCH_ROLE_FAILED,message:Xo({key:vo.SWITCH_ROLE_FAILED,data:{message:l,code:a}})});this.role=A}).catch(o=>{throw o instanceof gi&&o.getCode()===Ct.API_CALL_TIMEOUT&&(o=new gi({code:Ct.SWITCH_ROLE_FAILED,message:Xo({key:vo.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return WA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===B0);this._log.info("subscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>WA(this,null,function*(){try{yield e.subscribe(po(fi({},e.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",e.userId,o)}})))})}unsubscribeDataChannel(){return WA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===B0);this._log.info("unsubscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new f8({userId:this.userId,tinyId:this.tinyId,room:this}):new L1({userId:this.userId,tinyId:this.tinyId,room:this,signalChannel:this.signalChannel,enableSEI:this.enableSEI}),this.uplinkConnection.on("connection-state-changed",A=>{this.emit("media-connection-state-changed",po(fi({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let e=A.getCode();e!==Ct.ICE_TRANSPORT_ERROR&&(e===Ct.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return WA(this,null,function*(){var e;this.uplinkConnection||this._initUplinkConnection();let o="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("publish() => ".concat(o)),yield(e=this.singlePC)==null?void 0:e.waitForPeerConnectionConnected(),yield this.uplinkConnection.publish({localAudioTrack:A instanceof jM?A:null,localVideoTrack:A instanceof BQ?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return WA(this,null,function*(){if((this.scene!=="live"||this.role==="anchor")&&(this.isMainStreamPublished||this.isAuxStreamPublished)&&this.uplinkConnection){try{let e="".concat(A.streamType," ").concat(A.isAudio&&A.isScreen?"screen":"").concat(A.kind);this._log.info("unpublish() => ".concat(e)),yield this.uplinkConnection.unpublish({localAudioTrack:A instanceof jM?A:null,localVideoTrack:A instanceof BQ?A:null})}catch{}this.localTracks.size===0&&this.closeUplink("you unpublished")}})}addTrack(A){if(!this.uplinkConnection||!A.mediaTrack)return Promise.resolve();let e=this.uplinkConnection.addTrack(A);return A.publish(this,e),e}removeTrack(A){return this.uplinkConnection&&A.mediaTrack?(A.unpublish(),this.uplinkConnection.removeTrack(A)):Promise.resolve()}replaceTrack(A){return this.uplinkConnection&&A.mediaTrack&&J2()?this.uplinkConnection.replaceTrack(A).then(e=>{e&&F.emit(nA.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return WA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return WA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:YA.VIDEO,videoType:YA.SMALL,bandwidth:this.uplinkConnection.localMainVideoTrack.small.bitrate})),yield this.uplinkConnection.enableSmall(A)})}subscribe(){for(var A=arguments.length,e=new Array(A),o=0;o!h.isSubscribed),e.length===0)return;let{userId:a}=e[0],l=this.remotePublishedUserMap.get(a);if(!l)return;let d=e.find(h=>h.mediaType===2)?"auxiliary":"main";try{let h=fi({},l.subscribeState);e.forEach(S=>{switch(S.mediaType){case 1:h.audio=!0;break;case 4:h.video=!0;break;case 8:h.smallVideo=!0;break;case 2:h.auxiliary=!0}});let y=this._changeBigSmallRecords.get(a);y&&y.options.smallVideo&&l.muteState.hasSmall&&h.video&&(h.video=!1,h.smallVideo=!0),F.emit(nA.SUBSCRIBE_START,{room:this,streamType:d,remotePublishedUser:l,subscribeState:h}),this._log.info("subscribe() => ".concat(a," ").concat(d," ").concat(e.map(S=>S.strMediaType).join(",")," [").concat(kj(h),"] prev: [").concat(kj(l.subscribeState),"]")),yield l.subscribe(h,d),this._log.info("subscribe ".concat(a," ").concat(d," done"));for(let S of e)S.mediaTrack||(yield S.waitHasMediaTrack());F.emit(nA.SUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})}catch(h){let y=h instanceof gi?h.getCode():Ct.UNKNOWN,S=h;throw h instanceof gi?y===Ct.REMOTE_STREAM_NOT_EXIST&&(S=new gi({code:Ct.API_CALL_ABORTED,message:Xo({key:vo.API_CALL_ABORTED,data:{message:h.message,userId:a,streamType:d}})}),this._log.warn(S)):(S=new gi({code:y,message:Xo({key:vo.SUBSCRIBE_FAILED,data:{message:h.message,userId:a,streamType:d}})}),this._log.error(S)),S}})}unsubscribe(){for(var A=arguments.length,e=new Array(A),o=0;oh.mediaType===2)?"auxiliary":"main";this._log.info("unsubscribe() => ".concat(a," ").concat(d," ").concat(e.map(h=>h.strMediaType).join(",")));try{yield l.unsubscribe({remoteTracks:e,streamType:d})}catch(h){this._log.warn("unsubscribe() => failed ".concat(h))}e.forEach(h=>{h.unsubscribe(),h.mediaType===8&&h.setMediaType(4)}),F.emit(nA.UNSUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:l})})}setEncodedDataProcessingListener(A){throw new Error("Method not implemented.")}enableAudioVolumeEvaluation(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3,e=arguments.length>1?arguments[1]:void 0;if(A<=0)return this._enableAudioVolumeEvaluation=!1,void Gr.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),F.emit(nA.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&Gr.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=Gr.run("intervalInWorker",()=>{var o;e1.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,e);let a=[];(o=this.remotePublishedUserMap)==null||o.forEach(l=>{if(l.muteState.hasAudio){!e1.isRunning&&l.muteState.audioAvailable&&l.remoteAudioTrack.isSubscribed?this.updateDownlinkAudioLevelFromReceiver(l):l.remoteAudioTrack.volume=0;let d=Math.floor(100*l.remoteAudioTrack.getAudioLevel());a.push({userId:l.userId,volume:d,floatVolume:l.remoteAudioTrack.getInternalAudioLevel()})}}),this.emit("audio-volume",a)},{delay:A,backgroundTask:e})}updateAudioLevelFromSenderStat(A,e){return WA(this,null,function*(){var o;if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack||this._updateAudioLevelTaskId!==-1)return;let a=(o=this.uplinkConnection.getPeerConnection())==null?void 0:o.getSenders()[0];if(!a)return;let l=Math.max(A,500);this._log.warn("updateAudioLevelFromSenderStat ".concat(l)),this._updateAudioLevelTaskId=Gr.run("intervalInWorker",()=>WA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainAudioTrack)return void this.stopUpdateAudioLevelFromSenderStat();let d=yield a.getStats();if(this._updateAudioLevelTaskId<0)return;let{localMainAudioTrack:h}=this.uplinkConnection;d.forEach(y=>{y.type==="media-source"&&y.audioLevel&&(h.volume=y.audioLevel)})}),{delay:l,backgroundTask:e})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),Gr.clearTask(this._updateAudioLevelTaskId),this._updateAudioLevelTaskId=-1,(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(this.uplinkConnection.localMainAudioTrack.volume=0))}updateDownlinkAudioLevelFromReceiver(A){var e;let{audioReceiver:o}=A;if(!qk||!o)return;let a=(e=o.getSynchronizationSources()[0])==null?void 0:e.audioLevel;kn(a)?A.remoteAudioTrack.volume=Math.min(2*a,1):o.getStats().then(l=>{l.forEach(d=>{d.type==="inbound-rtp"&&kn(d.audioLevel)&&(A.remoteAudioTrack.volume=d.audioLevel)})})}getLocalAudioStats(){return WA(this,null,function*(){var A;let e={};return e[this.userId]={bytesSent:0,packetsSent:0,audioLevel:0},(A=this.uplinkConnection)!=null&&A.localMainAudioTrack&&(e[this.userId]=this.uplinkConnection.localMainAudioTrack.stat),e})}getLocalVideoStats(){return WA(this,null,function*(){var A,e;let o={};return o[this.userId]=((e=(A=this.uplinkConnection)==null?void 0:A.localMainVideoTrack)==null?void 0:e.stat)||{bytesSent:0,packetsSent:0,framesEncoded:0,framesSent:0,frameWidth:0,frameHeight:0,fpsCapture:0},o})}getTransportStats(){return WA(this,null,function*(){let A={rtt:0,downlinksRTT:{}};if(this.uplinkConnection){let e=yield this._stats.getSenderStats(this.uplinkConnection);A.rtt=e.rtt}for(let[,e]of this.remotePublishedUserMap){let o=yield this._stats.getReceiverStats(e);A.downlinksRTT[o.userId]=o.rtt}return A})}getRemoteVideoStats(A){return WA(this,null,function*(){let e={};for(let[o,a]of this.remotePublishedUserMap)A==="main"&&a.muteState.hasVideo&&(e[o]=a.remoteVideoTrack.stat),A==="auxiliary"&&a.muteState.hasAuxiliary&&(e[o]=a.remoteAuxiliaryTrack.stat);return e})}getRemoteAudioStats(){return WA(this,null,function*(){let A={};for(let[e,o]of this.remotePublishedUserMap)o.muteState.hasAudio&&(A[e]=o.remoteAudioTrack.stat);return A})}setTurnServer(A,e){this._log.info("set turn server: ".concat(JSON.stringify(A)," ").concat(e||""));let o=[];Array.isArray(A)?A.forEach(a=>o.push(Hd.getTurnServer(a))):Hd.isPlainObject(A)&&o.push(Hd.getTurnServer(A)),this._turnServers=o,e&&(this._iceTransportPolicy=e)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:DoA,data:A,timeout:5e3,responseCommand:ls.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==Ct.API_CALL_ABORTED)throw e})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:SoA,data:A,timeout:5e3,responseCommand:ls.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==Ct.API_CALL_ABORTED)throw e})}sendStartPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?poA:foA,data:A,timeout:5e3,responseCommand:e?ls.START_PUBLISH_TENCENT_CDN_RES:ls.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==Ct.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?moA:yoA,data:A,timeout:5e3,responseCommand:e?ls.STOP_PUBLISH_TENCENT_CDN_RES:ls.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==Ct.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:MoA,data:A,timeout:5e3,responseCommand:ls.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==Ct.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:voA,data:A,timeout:5e3,responseCommand:ls.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==Ct.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:RoA,data:A,timeout:5e3,responseCommand:ls.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==Ct.API_CALL_ABORTED)throw e})}sendAbilityStatus(A){var e;(e=this.signalChannel)==null||e.sendWaitForResponse({command:GoA,data:A,timeout:5e3,responseCommand:ls.ABILITY_STATUS_REPORT_RESULT,commandDesc:"ability status report"}).catch(o=>{})}getIceServers(A){var e,o;return this._turnServers.length>0?this._turnServers:(e=this.scheduleResult.iceServers)!=null&&e.length?this.scheduleResult.iceServers:A!=null&&A.length?A:(o=this._iceServersFromJoin)!=null&&o.length?this._iceServersFromJoin:[]}getIceTransportPolicy(){return this.forceRelay?"relay":this._iceTransportPolicy||this.scheduleResult.iceTransportPolicy||"all"}getLogger(){return this._log}enableAIVoice(){throw new Error("Method not implemented.")}getSignalChannelUrl(){let A={mainUrl:"",backupUrl:""},e=Hd.getEnv();return e?(A.mainUrl="wss://".concat(Hd.getTestSignalDomain(e)),A.backupUrl=A.mainUrl):this.proxy_ws?(A.mainUrl=this.proxy_ws,A.backupUrl=A.mainUrl):this.proxy_unified?(A.mainUrl="wss://".concat(this.proxy_unified),A.backupUrl=A.mainUrl):Array.isArray(this.scheduleResult.domains)&&this.scheduleResult.domains.length>0&&(A.mainUrl="wss://".concat(this.scheduleResult.domains[0]),A.backupUrl=A.mainUrl,this.scheduleResult.domains[1]&&(A.backupUrl="wss://".concat(this.scheduleResult.domains[1]))),A}getSignalInfo(){var A;return((A=this.signalChannel)==null?void 0:A.getSignalInfo())||{clientIp:"",relayIp:""}}reset(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];this.stopSyncUserListInterval(),this.stopHeartbeat(),this.closeConnections(),this.clearNetworkQuality(),this.closeUplink("you exitRoom"),this.signalChannel&&(A&&this.signalChannel.keepAlive&&this.signalChannel.isConnected?this.signalChannel.stopKeepAliveIn(3600):(this.signalChannel.close(),this.setSignalChannel(null))),this.localPublishFlag=0,this.heartbeatCount=0,this._stats.reset(),this.userManager.clear(),this.userManager.removeAllListeners(),this.singlePC&&(this.singlePC.close(),this.singlePC=null),this.scheduleResult={domains:null,iceServers:null,iceTransportPolicy:null,trtcAutoConf:null},this.clearPrelinkTimeout(),this.prelinkPromise=null}prelink(A,e,o,a,l,d){return WA(this,null,function*(){var h;if(this.isJoined)throw new gi({code:Ct.INVALID_OPERATION,message:"already joined room"});if(!l&&!d)throw new gi({code:Ct.INVALID_OPERATION,message:"roomId or strRoomId is required"});if((h=this.signalChannel)!=null&&h.prelink){if(this.signalChannel.isConnecting)return void this._log.warn("prelink is connecting, please wait");if(this.signalChannel.isConnected)return void this._log.warn("prelink is already connected")}return this.userId=e,this.sdkAppId=A,this.userSig=o,this.roomId=String(l||d),this.useStringRoomId=!(!d||l),this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.prelinkPromise=Promise.race([this.doPrelink(A,e,o,a,l,d),new Promise((y,S)=>{this.prelinkTimeoutId=setTimeout(()=>{S(new gi({code:Ct.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(y=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),y}),this.prelinkPromise})}doPrelink(A,e,o,a,l,d){return WA(this,null,function*(){var h,y,S;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Hd.getEnv()&&(yield this.schedule({sdkAppId:A,userId:e,userSig:o,roomId:l,strRoomId:d,role:20,privateMapKey:null,businessInfo:null,streamId:null,userDefineRecordId:null},a)),(h=this.scheduleResult.config)==null||!h.prelink)throw new gi({code:Ct.INVALID_OPERATION,message:"prelink failed: your sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it."});yield this.initialize({isPrelink:!0}),(y=this.signalChannel)==null||y.markPrelinkConnected({sdkAppId:A,userId:e,userSig:o}),(S=this.signalChannel)==null||S.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(k){throw this._log.error("prelink failed",k),k}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return WA(this,null,function*(){var A;if(this.isJoined)throw new gi({code:Ct.INVALID_OPERATION,message:"close prelink failed: has joined room"});if((A=this.signalChannel)!=null&&A.prelink){if(this.signalChannel.keepAlive)return void this._log.info("skip close prelink: use keepAlive");this.reset()}})}checkSubscribeBigSmallVideo(A){return WA(this,null,function*(){let{subscribeState:e,userId:o,muteState:{hasSmall:a,hasVideo:l}}=A;if(!a&&!l||!e.video&&!e.smallVideo)return;let d=this._changeBigSmallRecords.get(o);if(!d||d.isSubscribing||d.reSubscribeCount<=0)return;let{options:h,reSubscribeCount:y}=d;if(h.video&&e.video||h.smallVideo&&e.smallVideo&&a)return;let S={audio:A.remoteAudioTrack.isSubscribed||A.remoteAudioTrack.isSubscribing,auxiliary:A.remoteAuxiliaryTrack.isSubscribed||A.remoteAuxiliaryTrack.isSubscribing,video:h.video,smallVideo:h.smallVideo,datachannel:A.subscribeState.datachannel};try{if(!a&&S.smallVideo&&(S.video=!0,S.smallVideo=!1),S.smallVideo===e.smallVideo&&S.video===e.video)return;d.isSubscribing=!0,d.reSubscribeCount=y-1,yield A.subscribe(S,"main"),A.remoteVideoTrack.setMediaType(S.smallVideo?8:4),this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video successfully. count ").concat(eM-d.reSubscribeCount,".")),d.isSubscribing=!1,d.reSubscribeCount=eM}catch(k){this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video failed. count ").concat(eM-d.reSubscribeCount,". reason: ").concat(k)),d.isSubscribing=!1,d.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,e){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:eM};this._changeBigSmallRecords.set(e.userId,o),this._log.info("set [".concat(e.userId,"] video prefer type: ").concat(A?"small":"big")),this.emit("subscribe-small-video-changed",{userId:e.userId,isSmall:A});let a=this.remotePublishedUserMap.get(e.userId);a&&this.checkSubscribeBigSmallVideo(a)}get smallStreamConfig(){return this._smallStreamConfig}_initBusinessInfo(A){this._businessInfo=A.businessInfo;let e={};if(S8(A.businessInfo)&&(e=JSON.parse(A.businessInfo)),!iv(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_PURE_AUDIO})});this._pureAudioPushMode=A.pureAudioPushMode,e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.pure_audio_push_mod=this._pureAudioPushMode}if(!iv(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_USER_DEFINE_RECORDID})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!iv(A.userDefinePushArgs)){if(!(S8(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new gi({code:Ct.INVALID_PARAMETER,message:Xo({key:vo.INVALID_USER_DEFINE_PUSH_ARGS})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}BsA(e)||(this._businessInfo=JSON.stringify(e))}sendCustomMessage(A){var e;(e=this._customMessageManager)==null||e.send(A)}enableInsertableStreams(){return WA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&zp)return this.singlePC.enableInsertableStreams=!0,yield this.singlePC.waitForPeerConnectionConnected(),yield this.singlePC.startReconnection()})}sendSignalMessage(A){var e;return this.signalChannel?(e=this.signalChannel)==null?void 0:e.sendWaitForResponseWithRetry(A):Promise.reject(new gi({code:Ct.INVALID_OPERATION,message:"not join"}))}get enableCodecPipeline(){return this.videoManager.encodePipeline.length>0||this.videoManager.decodePipeline.length>0||this.audioManager.encodePipeline.length>0||this.audioManager.decodePipeline.length>0}get scriptTransformWorker(){var A;return(A=this.singlePC)==null?void 0:A.scriptTransformWorker}switchRoom(A){return WA(this,null,function*(){var e;if(!this.signalChannel||!this.singlePC)return;let{roomId:o,strRoomId:a,userSig:l,privateMapKey:d}=A,h=((e=this.scheduleResult.config)==null?void 0:e.autoSubscribeCount)||A?.autoSubscribeCount||1,y=String(this.useStringRoomId?a:o),S=[];for(let cA=0;cA{this.resolveSwitchRoomSubedReq=cA,OC(5e3).then(cA)}),F.emit(nA.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),V=yield this.signalChannel.sendWaitForResponse({command:LoA,responseCommand:ls.SEND_SWITCH_ROOM_RES,data:k});let{code:cA,message:CA}=V.data;if(cA!==0){this._log.error("switch room failed. result: ".concat(cA," error: ").concat(CA));let MA=new gi({code:Ct.SWITCH_ROOM_FAILED,extraCode:cA,message:CA});throw F.emit(nA.SWITCH_ROOM_FAILED,{room:this,error:MA}),MA}this.userSig=l,iv(d)||(this.privateMapKey=d),F.emit(nA.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:J,targetRoomId:y})}catch(cA){throw this.singlePC.autoSubscribedSsrcGroups.clear(),this.roomId=J,this.resolveSwitchRoomSubedReq(),cA}})}isSwitchRoomSupported(){var A;let e="unable to use switchRoom API, fallback to exitRoom and enterRoom.";return((A=this.scheduleResult.config)==null?void 0:A.switchRoom)!==!0?(this._log.warn("".concat(e," Reason: this sdkAppId is not supported, please contact us [https://trtc.io/contact] to enable it.")),!1):this.scene!=="live"?(this._log.warn("".concat(e," Reason: the scene is not 'live'.")),!1):this.role!=="audience"?(this._log.warn("".concat(e," Reason: the role is not 'audience'.")),!1):!!this.singlePC||(this._log.warn("".concat(e," Reason: is not using single peerConnection.")),!1)}requestRemoteFallbackToH264(){var A;(A=this.singlePC)==null||A.requestRemoteFallbackToH264()}startUpdateNTPTime(){if(!this.signalChannel)return;let A=[];for(let e=0;e<5;e++)A.push(this.updateNTPTime());return Promise.all(A).then(e=>{var o;let a=e[0].offset,l=e[0].offset;e.forEach(y=>{a=Math.min(y.offset,a),l=Math.max(y.offset,l)});let d=Math.floor(e.reduce((y,S)=>y+S.rtt,0)/e.length),h=Math.floor(e.reduce((y,S)=>y+S.offset,0)/e.length);(l-a>30||d>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),zB(h),(o=this.scriptTransformWorker)==null||o.postMessage({type:"ntp-offset",data:h}),this._log.debug("ntp updated offset: ".concat(h)),this.emit("ntp-time-updated")}).catch(e=>{this._log.warn("ntp updated failed: ".concat(e))})}updateNTPTime(){let A=Date.now();return this.signalChannel.sendWaitForResponse({command:UoA,responseCommand:ls.UPDATE_NETWORK_TIME_RESULT,addReceiveTime:!0,data:{clientSendTime:String(A)},enableLog:!1}).then(e=>{let o=Number(e.data.data.serverSendTime),a=Number(e.data.data.serverRecvTime),l=e.data.receiveTime||Date.now();return{rtt:l-A-(a-o),offset:(a-A+(o-l))/2}})}};return hi([lc(["left",Zs.INIT],"joined"),tB({settings:{retries:1,timeout:0},onRetrying(A){this._log.warn("join retry ".concat(A))},onRetryFailed(A){this._log.error("join failed",A)},onError(A,e){this._isUsingCachedSchedule&&!this.isDestroyed?(this._log.warn("is using cached schedule, retry join"),pQ(!0),this.reset(),e()):this.signalChannel&&this.signalChannel.isConnected&&this.signalChannel.keepAlive?(this._log.warn("is using keepAlive ws, retry join"),this.signalChannel.close(),this.reset(),e()):(this.reset(),e())}}),jr(A=>{let e=new loA;return function(o,a,l){return WA(this,null,function*(){let d=String(o.roomId||o.strRoomId);if(this.userId=o.userId,this.sdkAppId=o.sdkAppId,this.userSig=o.userSig,this._log.setSdkAppId(this.sdkAppId),this._log.setUserId(this.userId),this.scene=a,o.privateMapKey=o.privateMapKey||"",this.isJoined)throw new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.INVALID_JOIN})});if(this.checkDestroy(),e.isJoined({userId:this.userId,roomId:d,sdkAppId:this.sdkAppId,room:this}))throw new gi({code:Ct.INVALID_OPERATION,message:Xo({key:vo.REPEAT_JOIN,data:this.userId})});e.add({room:this,roomId:d}),this.role=o.role===21?"audience":"anchor",this._log.info("Join() => joining room: ".concat(d," useStringRoomId: ").concat(this.useStringRoomId," scene: ").concat(this.scene," role: ").concat(this.role)),F.emit(nA.JOIN_START,{room:this,roomId:d,params:o});let h=Hd.getEnv();h||(h=ZB.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(Pf.OLD_CLOUD_LADDER)?h=ZB.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(Pf.WEBRTC)&&(h=ZB.WEBRTC))),sn.setConfig({env:h,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:d}),re.checkSystemRequirementsInternal(l).then(y=>{this.checkSystemResult=y,IoA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!Hd.getEnv()&&(yield this.schedule(o,l));let y=yield A.call(this,o,a,l);return this.roomId=d,this._joinedTimestamp=Hd.performanceNow(),F.emit(nA.JOIN_SUCCESS,{room:this}),l===30&&!o.component&&sn.uploadEvent({log:"stat-conv-".concat(Number(Yp),"-").concat(location.hostname),userId:this.userId}),y}catch(y){throw e.delete({room:this,roomId:d}),F.emit(nA.JOIN_FAILED,{room:this,error:y}),y}})}})],Ny.prototype,"join"),hi([lc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;aA.mediaType),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.outMediaTrack&&d.state==="ready"),!o.length))return;F.emit("61",{room:this});let l=A.apply(this,o);return Promise.all(o.map(d=>d.publish(this,l)))})}),tB({settings:{retries:Jf,timeout:A=>Tp(A)},onError(A,e,o,a){let[l]=a;var d;(d=A.message)!=null&&d.includes("timeout")?(this._log.warn("publish ".concat(l.strMediaType," timeout"),A),e()):(this._log.error("publish ".concat(l.strMediaType," failed: ").concat(A)),o(A),F.emit(nA.PUBLISH_FAILED,{room:this}))}})],Ny.prototype,"publish"),hi([g_({fnName:"publish"}),Dy(A=>A.mediaType),jr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.unpublish()),l}),qM(function(){var A,e;this.localTracks.size===0&&UI()&&((e=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||e.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],Ny.prototype,"unpublish"),hi([_5(A=>{if(A.code!==Ct.API_CALL_ABORTED)throw A}),Dy(A=>A.userId)],Ny.prototype,"replaceTrack"),hi([Dy(function(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var e=arguments.length,o=new Array(e),a=0;a!d.isSubscribed&&d.subscribe(l)),l}),tB({settings:{retries:Jf,timeout:A=>Tp(A)},onError(A,e,o,a){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),e();else{let l=A?.code===Ct.API_CALL_ABORTED;this._log[l?"warn":"error"]("subscribe failed ".concat(a.map(d=>d.strMediaType).join(","),": ").concat(A)),o(A),F.emit(nA.SUBSCRIBE_FAILED,{room:this,remoteTracks:a})}}})],Ny.prototype,"subscribe"),hi([g_({fnName:"subscribe",callback(){for(var A=arguments.length,e=new Array(A),o=0;o{let l=this.remotePublishedUserMap.get(a.userId);l&&!l.isMainStreamSubscribed&&!l.isAuxStreamSubscribed&&l.close("you unsubscribed")})}}),Dy(function(){for(var A=arguments.length,e=new Array(A),o=0;oi in t?MV(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,daA=(t,i)=>{for(var n in i||(i={}))uX.call(i,n)&&AW(t,n,i[n]);if(QZ)for(var n of QZ(i))EaA.call(i,n)&&AW(t,n,i[n]);return t},CaA=(t,i)=>function(){return i||(0,t[IX(t)[0]])((i={exports:{}}).exports,i),i.exports},haA=(t,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of IX(i))uX.call(t,I)||I===n||MV(t,I,{get:()=>i[I],enumerable:!(c=lX(i,I))||c.enumerable});return t},BaA=(t,i,n)=>(n=t!=null?IaA(uaA(t)):{},haA(MV(n,"default",{value:t,enumerable:!0}),t)),V_=(t,i,n,c)=>{for(var I,C=lX(i,n),f=t.length-1;f>=0;f--)(I=t[f])&&(C=I(i,n,C)||C);return C&&MV(i,n,C),C},pn=(t,i,n)=>AW(t,typeof i!="symbol"?i+"":i,n),QaA=CaA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(N,L,q){this.fn=N,this.context=L,this.once=q||!1}function f(N,L,q,lA,tA){if(typeof q!="function")throw new TypeError("The listener must be a function");var BA=new C(q,lA||N,tA),IA=c?c+L:L;return N._events[IA]?N._events[IA].fn?N._events[IA]=[N._events[IA],BA]:N._events[IA].push(BA):(N._events[IA]=BA,N._eventsCount++),N}function w(N,L){--N._eventsCount===0?N._events=new I:delete N._events[L]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var N,L,q=[];if(this._eventsCount===0)return q;for(L in N=this._events)n.call(N,L)&&q.push(c?L.slice(1):L);return Object.getOwnPropertySymbols?q.concat(Object.getOwnPropertySymbols(N)):q},_.prototype.listeners=function(N){var L=c?c+N:N,q=this._events[L];if(!q)return[];if(q.fn)return[q.fn];for(var lA=0,tA=q.length,BA=new Array(tA);lA{if(!navigator.userAgent.includes("Firefox"))return t;const i=t.split(`\r +`),n=[],c=[];i.forEach(f=>{const w=f.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&n.push(f)}),n.length>1&&c.push(...n.slice(1));const I=c.map(f=>{const w=/a=rtpmap:(\d+)\s/.exec(f);return w&&w.length>1?w[1]:null}).filter(f=>f!==null),C=[];return i.forEach(f=>{let w=f;if(f.includes("a=setup")&&(w="a=setup:passive"),(f.includes("m=audio")||f.includes("m=video"))&&(w=f.split(" ").filter((_,N)=>N<3||!I.includes(_)).join(" ")),f.includes("a=fmtp")||f.includes("a=rtcp-fb")||f.includes("a=rtpmap")){const _=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(f);if(_&&_.length>1&&I.includes(_[1]))return}C.push(w)}),C.join(`\r +`)},pZ=t=>{const i=t.split(`\r +`),n=[];i.forEach(f=>{const w=f.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&n.push(f)});const c=n.map(f=>{const w=/a=rtpmap:(\d+)\s/.exec(f);return w&&w.length>1?w[1]:null}).filter(f=>f!==null),I=[];i.forEach(f=>{let w=f;if(f.includes("a=fmtp:111")&&(w=`${f};stereo=1`),f.includes("a=fmtp")){const _=/a=fmtp:(\d+)\s/.exec(f);_&&_.length>1&&c.includes(_[1])&&(w=`${f};sps-pps-idr-in-keyframe=1`)}I.push(w)});const C=I.join(`\r +`);return maA(C)},faA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",$j=(t=21)=>{let i="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)i+=faA[63&n[t]];return i},k_=t=>typeof t=="function",yaA=0,DaA=1,mZ=2;function SaA({retryFunction:t,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:f}){return function(...w){const{retries:_=5,timeout:N=1e3}=i;let L=0,q=-1,lA=yaA;const tA=async(BA,IA)=>{const gA=f||this;try{const RA=await t.apply(gA,w);L>0&&C&&C.call(this,L),L=0,BA(RA)}catch(RA){const HA=()=>{clearTimeout(q),L=0,lA=mZ,IA(RA)},ZA=()=>{lA!==mZ&&L<(k_(_)?_():_)?(L++,lA=DaA,k_(c)&&c.call(this,L,HA),q=window.setTimeout(()=>{q=-1,tA(BA,IA)},k_(N)?N(L):N)):(HA(),k_(I)&&I.call(this,RA))};k_(n)?n.call(this,{error:RA,retry:ZA,reject:IA,retryFuncArgs:w,retriedCount:L}):ZA()}};return new Promise(tA)}}var MaA=SaA,yQ=new WeakMap;function vaA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,f){const w=MaA({retryFunction:f.value,settings:t,onError({error:_,retry:N,reject:L,retryFuncArgs:q}){var lA;i?i.call(this,_,()=>{var tA;(tA=yQ.get(I))!=null&&tA.has(C)?N():L(_)},L,q):(lA=yQ.get(I))!=null&&lA.has(C)?N():L(_)},onRetrying(_,N){var L;k_(n)&&n.call(this,_,N),(L=yQ.get(I))!=null&&L.has(C)&&(yQ.get(I).get(C).stopRetry=N)},onRetryFailed:c});return f.value=function(..._){const N=yQ.get(I);return N?N.set(C,{args:_}):yQ.set(I,new Map([[C,{args:_}]])),w.apply(this,_).finally(()=>{var L;return(L=yQ.get(I))==null?void 0:L.delete(C)})},f}}function RaA({fnName:t,callback:i,validateArgs:n=!0}){return function(c,I,C){const f=C.value;return C.value=function(...w){var _,N;if((_=yQ.get(c))!=null&&_.has(t)){const{stopRetry:L,args:q}=yQ.get(c).get(t);let lA=!0;if(n){for(const tA of q)if(!w.find(BA=>BA===tA)){lA=!1;break}}lA&&(i&&i.apply(this,w),L&&L(),(N=yQ.get(c))==null||N.delete(t))}return f.apply(this,w)},C}}var waA=class{constructor(t,i){this.core=i,pn(this,"peerConnection"),pn(this,"audioTransceiver",null),pn(this,"videoTransceiver",null),pn(this,"timerId",null),pn(this,"callback",null),pn(this,"previousRawStats",null),pn(this,"_prevReportTime",0),pn(this,"_prevDecoderImplementation",""),pn(this,"_decodeMap",new Map),this.peerConnection=t,this.findTransceivers()}get statInterval(){return this._prevReportTime===0?2:(Date.now()-this._prevReportTime)/1e3}findTransceivers(){const t=this.peerConnection.getTransceivers();for(const i of t)if(i.receiver&&i.receiver.track){const{track:n}=i.receiver;n.kind==="audio"?this.audioTransceiver=i:n.kind==="video"&&(this.videoTransceiver=i)}}start(t,i=2e3){this.stop(),this.callback=t,this.collectStats(),this.timerId=window.setInterval(()=>{this.collectStats()},i)}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.callback=null,this.previousRawStats=null,this._prevReportTime=0}async collectStats(){if(this.callback)try{const t=await this.peerConnection.getStats(),i=new Set(["inbound-rtp","track","candidate-pair","media-source","codec"]),n=[];t.forEach(w=>i.has(w.type)&&n.push(w));const c=Date.now(),I=this.parseAudioStats(n),C=this.parseVideoStats(n),f=this.parseNetworkStats(n);this._prevReportTime=c,this.callback({audio:I,video:C,network:f})}catch(t){this.core.log.error("Failed to collect WebRTC stats:",t)}}getDifferenceValue(t,i){if(this.core.utils.isUndefined(t))return i;const n=(i||0)-t;return n<0?0:n}parseAudioStats(t){var i,n,c,I;const C={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const f of t){if(f.type==="inbound-rtp"&&(f.mediaType==="audio"||f.kind==="audio")){if(C.bytesReceived=f.bytesReceived||0,C.packetsReceived=f.packetsReceived||0,C.packetsLost=f.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const N=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,C.bytesReceived);C.bitrate=Math.round(8*N/this.statInterval/1e3)}const w=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,C.packetsLost),_=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.audio.packetsReceived,C.packetsReceived)+w;if(_>0&&(C.packetLossRate=Math.round(w/_*100)),this.core.utils.isUndefined(f.audioLevel)||(C.volume=f.audioLevel||0),f.jitterBufferDelay&&f.jitterBufferEmittedCount){let{jitterBufferEmittedCount:N}=f,{jitterBufferDelay:L}=f;(c=this.previousRawStats)!=null&&c.audio&&(N=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,f.jitterBufferEmittedCount),L=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,f.jitterBufferDelay)),N>0&&(C.jitterBufferDelay=Math.floor(L/N*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=f.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=f.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=C.bytesReceived,this.previousRawStats.audio.packetsReceived=C.packetsReceived,this.previousRawStats.audio.packetsLost=C.packetsLost}!this.core.utils.isUndefined(f.audioLevel)&&((I=this.audioTransceiver)!=null&&I.receiver.track)&&f.trackIdentifier===this.audioTransceiver.receiver.track.id&&(C.volume=f.audioLevel||0)}return C}parseVideoStats(t){var i,n,c,I,C;const f={bitrate:0,frameRate:0,width:0,height:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0,framesDecoded:0};for(const w of t){if(w.type==="codec"&&this._decodeMap.set(w.id,w),w.type==="inbound-rtp"&&(w.mediaType==="video"||w.kind==="video")){if(f.bytesReceived=w.bytesReceived||0,f.packetsReceived=w.packetsReceived||0,f.packetsLost=w.packetsLost||0,f.framesDecoded=w.framesDecoded||0,this.core.utils.isUndefined(w.framesPerSecond)||(f.frameRate=Math.round(w.framesPerSecond)),w.decoderImplementation&&this._prevDecoderImplementation!==w.decoderImplementation){const L=this._decodeMap.get(w.codecId),q=((i=L?.mimeType)==null?void 0:i.split("/")[1])||"unknown",lA=w.powerEfficientDecoder;this.core.log.info(`decoderImplementation change to ${w.decoderImplementation}(${q}) HWDecoder: ${lA}`),this._prevDecoderImplementation=w.decoderImplementation}if(this.previousRawStats&&this.previousRawStats.video){const L=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,f.bytesReceived);f.bitrate=Math.round(8*L/this.statInterval/1e3)}const _=this.getDifferenceValue((n=this.previousRawStats)==null?void 0:n.video.packetsLost,f.packetsLost),N=this.getDifferenceValue((c=this.previousRawStats)==null?void 0:c.video.packetsReceived,f.packetsReceived)+_;if(N>0&&(f.packetLossRate=Math.round(_/N*100)),w.jitterBufferDelay&&w.jitterBufferEmittedCount){let{jitterBufferEmittedCount:L}=w,{jitterBufferDelay:q}=w;(I=this.previousRawStats)!=null&&I.video&&(L=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,w.jitterBufferEmittedCount),q=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,w.jitterBufferDelay)),L>0&&(f.jitterBufferDelay=Math.floor(q/L*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.jitterBufferDelay=w.jitterBufferDelay,this.previousRawStats.video.jitterBufferEmittedCount=w.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.video.bytesReceived=f.bytesReceived,this.previousRawStats.video.packetsReceived=f.packetsReceived,this.previousRawStats.video.packetsLost=f.packetsLost}!this.core.utils.isUndefined(w.frameWidth)&&((C=this.videoTransceiver)!=null&&C.receiver.track)&&w.trackIdentifier===this.videoTransceiver.receiver.track.id&&(f.width=w.frameWidth,f.height=w.frameHeight)}return f}parseNetworkStats(t){const i={rtt:0};for(const n of t)if(n.type==="candidate-pair"&&(n.selected||n.state==="succeeded")&&this.core.utils.isNumber(n.currentRoundTripTime)){i.rtt=Math.floor(1e3*n.currentRoundTripTime);break}return i}initPreviousRawStats(){this.previousRawStats={timestamp:Date.now(),audio:{bytesReceived:0,packetsReceived:0,packetsLost:0},video:{bytesReceived:0,packetsReceived:0,packetsLost:0}}}},_aA=BaA(QaA()),fZ=Symbol("instance"),H1=Symbol("cacheResult"),A3=class{constructor(i,n,c){this.oldState=i,this.newState=n,this.action=c,this.aborted=!1}abort(i){this.aborted=!0,cU.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},e3=class extends Error{constructor(i,n,c){super(n),this.state=i,this.message=n,this.cause=c}};function TaA(t){return typeof t=="object"&&t&&"then"in t}var gU=new Map;function q1(t,i,n={}){return(c,I,C)=>{const f=n.action||I;if(!n.context){const _=gU.get(c)||[];gU.has(c)||gU.set(c,_),_.push({from:t,to:i,action:f})}const w=C.value;C.value=function(..._){let N=this;if(n.context&&(N=eh.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),N.state===i)return n.sync?N[H1]:Promise.resolve(N[H1]);N.state instanceof A3&&N.state.action==n.abortAction&&N.state.abort(N);let L=null;Array.isArray(t)?t.length==0?N.state instanceof A3&&N.state.abort(N):typeof N.state=="string"&&t.includes(N.state)||(L=new e3(N._state,`${N.name} ${f} to ${i} failed: current state ${N._state} not from ${t.join("|")}`)):t!==N.state&&(L=new e3(N._state,`${N.name} ${f} to ${i} failed: current state ${N._state} not from ${t}`));const q=gA=>{if(n.fail&&n.fail.call(this,gA),n.sync){if(n.ignoreError)return gA;throw gA}return n.ignoreError?Promise.resolve(gA):Promise.reject(gA)};if(L)return q(L);const lA=N.state,tA=new A3(lA,i,f);cU.call(N,tA);const BA=gA=>{var RA;return N[H1]=gA,tA.aborted||(cU.call(N,i),(RA=n.success)===null||RA===void 0||RA.call(this,N[H1])),gA},IA=gA=>(cU.call(N,lA,gA),q(gA));try{const gA=w.apply(this,_);return TaA(gA)?gA.then(BA).catch(IA):n.sync?BA(gA):Promise.resolve(BA(gA))}catch(gA){return IA(new e3(N._state,`${N.name} ${f} from ${t} to ${i} failed: ${gA}`,gA instanceof Error?gA:new Error(String(gA))))}}}}var NaA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function cU(t,i){const n=this._state;this._state=t;const c=t.toString();t&&this.emit(c,n),this.emit(eh.STATECHANGED,t,n,i),this.updateDevTools({value:t,old:n,err:i instanceof Error?i.message:String(i)})}var eh=class ZC extends _aA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=ZC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[fZ];I?this.name=I.name+"-"+I.count++:c[fZ]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=gU.get(i)||[];let c=new Set,I=[],C=[];const f=new Set,w=Object.getPrototypeOf(i);gU.has(w)&&(w.stateDiagram.forEach(N=>c.add(N)),w.allStates.forEach(N=>f.add(N))),n.forEach(({from:N,to:L,action:q})=>{typeof N=="string"?I.push({from:N,to:L,action:q}):N.length?N.forEach(lA=>{I.push({from:lA,to:L,action:q})}):C.push({to:L,action:q})}),I.forEach(({from:N,to:L,action:q})=>{f.add(N),f.add(L),f.add(q+"ing"),c.add(`${N} --> ${q}ing : ${q}`),c.add(`${q}ing --> ${L} : ${q} 🟢`),c.add(`${q}ing --> ${N} : ${q} 🔴`)}),C.forEach(({to:N,action:L})=>{c.add(`${L}ing --> ${N} : ${L} 🟢`),f.forEach(q=>{q!==N&&c.add(`${q} --> ${L}ing : ${L}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:f}}),_}static get(i){let n;return typeof i=="string"?(n=ZC.instances.get(i),n||ZC.instances.set(i,n=new ZC(i,void 0,Object.create(ZC.prototype)))):(n=ZC.instances2.get(i),n||ZC.instances2.set(i,n=new ZC(i.constructor.name,void 0,Object.create(ZC.prototype)))),n}static getState(i){var n;return(n=ZC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){NaA(ZC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){cU.call(this,i)}};eh.STATECHANGED="stateChanged",eh.UPDATEAFSM="updateAFSM",eh.INIT="[*]",eh.ON="on",eh.OFF="off",eh.instances=new Map,eh.instances2=new WeakMap;var YL=class extends eh{constructor(i,n){super(),this.core=i,pn(this,"audioPlayer"),pn(this,"videoPlayer"),pn(this,"callback"),pn(this,"avPlayerStateSyncManager"),pn(this,"_log"),pn(this,"_videoPlayerLog"),pn(this,"_audioPlayerLog"),pn(this,"lastPausedReason"),pn(this,"muted",!1),this._log=n,this._videoPlayerLog=this._log.createChild({id:"vp"}),this._audioPlayerLog=this._log.createChild({id:"ap"}),this.videoPlayer=new i.VideoPlayer({id:"vp",log:this._videoPlayerLog,track:null,muted:!1,container:null,enableLogTrackState:!0}),this.audioPlayer=new i.RemoteAudioPlayer({id:"ap",log:this._audioPlayerLog,track:null,muted:!1,container:null,enableVolumeControlInIOS:!0,enableLogTrackState:!0}),this.audioPlayer.on(i.PlayerEvent.AUTOPLAY_FAILED,c=>this.handleAutoPlayFailed(this.audioPlayer,c)),this.videoPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("video")),this.audioPlayer.on(i.PlayerEvent.LOAD_START,()=>this.handleLoadStart("audio")),this.videoPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.audioPlayer.on(i.PlayerEvent.PLAYER_STATE_CHANGED,this.handlePlayerStateChanged,this),this.videoPlayer.on(i.PlayerEvent.ENTER_PICTURE_IN_PICTURE,this.handleEnterPictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePictureInPicture,this),this.videoPlayer.on(i.PlayerEvent.ENTER_FULL_SCREEN,this.handleEnterFullScreen,this),this.videoPlayer.on(i.PlayerEvent.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.avPlayerStateSyncManager=new i.AVPlayerStateSyncManager({log:this._log,audioPlayer:this.audioPlayer,videoPlayer:this.videoPlayer})}get isPlaying(){return this.videoPlayer.isPlaying&&this.audioPlayer.isPlaying}get isPaused(){return this.videoPlayer.isPaused&&this.audioPlayer.isPaused}get isStopped(){return this.videoPlayer.isStopped&&this.audioPlayer.isStopped}setCallback(i){this.callback=i}updateLogConfig(i){this._audioPlayerLog.setSdkAppId(i.sdkAppId),this._audioPlayerLog.setUserId(i.userId),this._videoPlayerLog.setSdkAppId(i.sdkAppId),this._videoPlayerLog.setUserId(i.userId)}handleLoadStart(i){this.onLoadStart()}handlePlayerStateChanged(i){i.state==="PLAYING"&&this.isPlaying&&this.onPlaying(),i.state==="PAUSED"&&this.isPaused&&this.onPaused(i.reason),i.state==="STOPPED"&&this.isStopped&&this.onStopped()}async handleEnterPictureInPicture(){var i,n;await this.videoPlayer.enterPIPPromise,(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!0,pictureInPictureWindow:this.videoPlayer.pipWindow})}handleLeavePictureInPicture(){var i,n;(n=(i=this.callback)==null?void 0:i.onPictureInPictureStateChanged)==null||n.call(i,{isPictureInPicture:!1})}handleEnterFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!0})}handleLeaveFullScreen(){var i,n;(n=(i=this.callback)==null?void 0:i.onFullScreenStateChanged)==null||n.call(i,{isFullScreen:!1})}onLoadStart(){}onPlaying(){}onPaused(i){this.lastPausedReason=i}onStopped(){}setVideoContainer(i){if(this.core.utils.isString(i)){const n=document.getElementById(i);n&&this.videoPlayer.setContainer(n)}else this.videoPlayer.setContainer(i)}setVolume(i){this.core.utils.isUndefined(i)||this.audioPlayer.setVolume(i/100)}setMuted(i){this.core.utils.isUndefined(i)||(this.muted=i,this.audioPlayer.setMuted(i))}setFillMode(i){i&&this.videoPlayer.setObjectFit(i)}setAudioTrack(i){this.audioPlayer.setTrack(i)}setVideoTrack(i){this.videoPlayer.setTrack(i)}async play(){const i=this.videoPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.videoPlayer,c,"video")}),n=this.audioPlayer.play().catch(c=>{this.handleAutoPlayFailed(this.audioPlayer,c)});await Promise.all([i,n])}handleAutoPlayFailed(i,n,c="audio"){var I,C;this._log.warn("handleAutoPlayFailed",n);const f=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",f,!0)})};document.addEventListener("click",f,!0),(C=(I=this.callback)==null?void 0:I.onAutoPlayFailed)==null||C.call(I,{type:c,resume:()=>i.resume()})}pause(){this.videoPlayer.pause(!0),this.audioPlayer.setMuted(!0),this.audioPlayer.pause()}resume(){this.videoPlayer.resume(!0),this.audioPlayer.setMuted(this.muted),this.audioPlayer.resume()}async enterFullscreen(){await this.videoPlayer.enterFullscreen()}async exitFullscreen(){await this.videoPlayer.exitFullscreen()}async enterPictureInPicture(){await this.videoPlayer.enterPictureInPicture()}async exitPictureInPicture(){await this.videoPlayer.exitPictureInPicture()}stop(){this.videoPlayer&&this.videoPlayer.stop(),this.audioPlayer&&(this.audioPlayer.stop(),this.audioPlayer.setMuted(!1))}};V_([q1([eh.INIT,"PAUSED"],"LOADSTART",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onLoadStart)==null||i.call(t)},fail(t){this._log.warn("onLoadStart",t)}})],YL.prototype,"onLoadStart"),V_([q1(["LOADSTART","PAUSED"],"PLAYING",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPlaying)==null||i.call(t)},fail(t){this._log.warn("onPlaying",t)}})],YL.prototype,"onPlaying"),V_([q1("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onPaused)==null||i.call(t,{reason:this.lastPausedReason})},fail(t){this._log.warn("onPaused",t)}})],YL.prototype,"onPaused"),V_([q1([],eh.INIT,{ignoreError:!0,sync:!0,success(){var t,i;(i=(t=this.callback)==null?void 0:t.onStopped)==null||i.call(t)},fail(t){this._log.warn("onStopped",t)}})],YL.prototype,"onStopped");var yZ=YL,GaA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],hY=class EX{constructor(i){this.core=i,pn(this,"_sdkAppId"),pn(this,"_userId"),pn(this,"connectedRoomIdSet",new Set),pn(this,"updateSeq",0),pn(this,"_log"),pn(this,"player"),pn(this,"peerConnection"),pn(this,"svrSig"),pn(this,"streamURL"),pn(this,"signalURL"),pn(this,"insertableStreamsAbortMap",new Map),pn(this,"scriptTransformWorker"),pn(this,"connectionState","disconnected"),pn(this,"isStarted",!1),pn(this,"isStopped",!0),pn(this,"isReconnecting",!1),pn(this,"callback"),pn(this,"isFireWallErrorEmitted",!1),pn(this,"stat"),pn(this,"isH264DecodeSupported"),pn(this,"connectionTimeoutId"),pn(this,"streamHealthCheckTimeoutId"),pn(this,"streamHealthCheckReject"),i.loggerManager.startUpload(),this._log=this.core.log.createChild({id:`${this.getAlias()}`}),this.player=new yZ(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return EX.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return paA;case"update":case"stop":return{}}}get enableSEI(){return this.core.room.enableSEI&&(this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED||this.core.rtcDectection.IS_SCRIPT_TRANSFORM_SUPPORTED)}wrapCallback(i){if(!i)return;const n={},c=["onStats","onSEIMessage"];for(const I of Object.keys(i)){const C=i[I];typeof C=="function"&&(c.includes(I)?n[I]=C:n[I]=(...f)=>(this._log.debug(`callback ${I} called`,f.length>0?f[0]:""),C(...f)))}return n}async start(i){var n;this.isStopped=!1;const{view:c,url:I,volume:C,muted:f,fillMode:w,loggerConfig:_,callback:N}=i;this.callback=this.wrapCallback(N),this.player.setCallback(this.callback);const{errorModule:{RtcError:L,ErrorCode:q,ErrorCodeDictionary:lA},loggerManager:tA,rtcDectection:BA}=this.core;if(this._sdkAppId=_.sdkAppId,this._userId=_.userId,this._log.setSdkAppId(_.sdkAppId),this._log.setUserId(_.userId),this.player.updateLogConfig(_),tA.addJoinedUser(_),!BA.isWebRTCSupported()||!BA.isAddTransceiverSupported())throw new L({code:q.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_WEBRTC,message:"webrtc not supported"});if(!(await BA.decodeSupportStatus()).isH264DecodeSupported||this.isH264DecodeSupported===!1)throw this.isH264DecodeSupported=!1,new L({code:q.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!BA.IS_SEI_SUPPORTED&&N?.onSEIMessage&&((n=N.onError)==null||n.call(N,new L({code:q.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(c),this.player.setMuted(f),this.player.setFillMode(w);try{await this.connect(I),this.stat=new waA(this.peerConnection,this.core),this.stat.start(RA=>{var HA,ZA;return(ZA=(HA=this.callback)==null?void 0:HA.onStats)==null?void 0:ZA.call(HA,RA)});const IA=this.player.play();this.player.setVolume(C);const gA=this.createStreamHealthCheckPromise();await Promise.race([IA,gA]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(IA){throw this.stop(),IA}}async update(i){const{view:n,url:c,volume:I,muted:C,fillMode:f,action:w,fullScreen:_,pictureInPicture:N}=i;c&&c!==this.streamURL&&await this.switchStream(c),this.player.setMuted(C),this.player.setVolume(I),this.player.setFillMode(f),n&&this.player.videoPlayer.setContainer(this.core.utils.isString(n)?document.getElementById(n):n),w==="pause"?this.player.pause():w==="resume"&&this.player.resume(),this.core.utils.isBoolean(_)&&(_?await this.player.enterFullscreen():await this.player.exitFullscreen()),this.core.utils.isBoolean(N)&&(N?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const n=this.peerConnection,c=this.streamURL,I=this.signalURL,C=this.svrSig,f=new Map(this.insertableStreamsAbortMap),w=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const _=new yZ(this.core,this._log);_.setVideoContainer(w.videoPlayer.container),_.setFillMode(w.videoPlayer.objectFit),_.setMuted(w.muted),_.setCallback(this.callback);const N=L=>{const{track:q}=L;this.createEncodedStreams(L.receiver),this.initReceiverTransform(L.receiver,q.kind==="audio"),q.kind==="audio"?_.setAudioTrack(q):_.setVideoTrack(q)};try{await this.connectForSwitch(i,N),this._log.info("switchStream: new connection established"),await this.waitForNewPlayerFirstFrame(_),this._log.info("switchStream: new stream first frame received"),w.audioPlayer.setMuted(!0),w.stop(),this.player=_,n&&(clearTimeout(this.connectionTimeoutId),n.close(),n.getReceivers().forEach(L=>f.delete(L)),c&&C&&I&&this.fetchStopStreamWithParams(c,I,C).catch(L=>{this._log.warn("switchStream: stop old stream failed",L)})),this._log.info("switchStream: switch completed successfully")}catch(L){this._log.error("switchStream failed",L),_.stop();const q=this.peerConnection;throw q&&(q.close(),q.getReceivers().forEach(lA=>this.insertableStreamsAbortMap.delete(lA))),this.peerConnection=n,this.streamURL=c,this.signalURL=I,this.svrSig=C,this.insertableStreamsAbortMap=f,this.player=w,w.audioPlayer.setMuted(w.muted),L}}waitForNewPlayerFirstFrame(i){return new Promise((n,c)=>{let I=0,C=!1;const f=i.videoPlayer.getElement();if(!f)return void c(new Error("VideoPlayer has no video element"));const w=()=>{C=!0,clearInterval(L),f.removeEventListener("loadeddata",_),f.removeEventListener("playing",N)},_=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),w(),n())},N=()=>{C||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),w(),n())};f.addEventListener("loadeddata",_,{once:!0}),f.addEventListener("playing",N,{once:!0}),i.play().catch(q=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",q)});const L=setInterval(()=>{if(!C){if(I+=100,f.videoWidth>0&&f.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${f.videoWidth}x${f.videoHeight}`),w(),void n();I>=1e4&&(w(),c(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,n){return new Promise((c,I)=>{try{this.initScriptTransformWorker();const C={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},f=new RTCPeerConnection(C);this.peerConnection=f,f.onconnectionstatechange=()=>{this.connectionState=f.connectionState,this._log.info("connectForSwitch connectionState",f.connectionState),f.connectionState!=="failed"&&f.connectionState!=="closed"||I(new Error(`connection is ${f.connectionState}`)),f.connectionState==="connected"&&(this.logSelectedCandidate(),c())},f.ontrack=n,f.addTransceiver("audio",{direction:"recvonly"}),f.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),f.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(w=>(w.sdp=pZ(w.sdp),this._log.info("connectForSwitch setOffer"),f.setLocalDescription(w))).then(()=>{const w={sessionId:$j(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:f.localDescription};return this.exchangeSDP(i,w)}).then(w=>(this._log.info("connectForSwitch setAnswer"),f.setRemoteDescription(w))).catch(I)}catch(C){I(C)}this.connectionTimeoutId=setTimeout(()=>I(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,n,c){try{const I=`${n}/webrtc/v1/stopstream`,C=await K1(I,{streamurl:i,svrsig:c},{timeout:3}),{errcode:f,errmsg:w}=C;if(f!==0)throw new Error(`errCode:${f}, errmsg:${w}`);return C}catch(I){this._log.error("fetchStopStreamWithParams error",I)}}async stop(){this.isStopped=!0,this.clearStreamHealthCheck(),this.player.stop(),this.peerConnection&&(clearTimeout(this.connectionTimeoutId),this.peerConnection.close(),this.peerConnection.getReceivers().forEach(i=>this.insertableStreamsAbortMap.delete(i)),delete this.peerConnection,await this.fetchStopStream(),delete this.streamURL,delete this.signalURL,delete this.svrSig),this.stat&&(this.stat.stop(),delete this.stat),this.core.room.keyPointManager.uploadKVStat(this.core.kvStatManager,this._sdkAppId)}destroy(){this.stop(),this.core.innerEmitter.off(this.core.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}createStreamHealthCheckPromise(){return new Promise((i,n)=>{this.streamHealthCheckReject=n,this.streamHealthCheckTimeoutId=window.setTimeout(()=>this.checkStreamHealth(n),5e3)})}clearStreamHealthCheck(){this.streamHealthCheckTimeoutId&&(clearTimeout(this.streamHealthCheckTimeoutId),delete this.streamHealthCheckTimeoutId),delete this.streamHealthCheckReject}async checkStreamHealth(i){if(!this.isStopped&&this.peerConnection)try{const n=this.peerConnection.getReceivers().find(q=>{var lA;return((lA=q.track)==null?void 0:lA.kind)==="video"});if(!n)return void this._log.warn("checkStreamHealth: no video receiver found");const c=await n.getStats();let I=0,C=0;c.forEach(q=>{q.type==="inbound-rtp"&&(q.mediaType==="video"||q.kind==="video")&&(I=q.bytesReceived||0,C=q.framesDecoded||0)});const{isPlaying:f}=this.player,w=f||C>0;this._log.info(`checkStreamHealth: bytesReceived=${I}, framesDecoded=${C}, isPlaying=${f}`);const{RtcError:_,ErrorCode:N,ErrorCodeDictionary:L}=this.core.errorModule;I===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new _({code:N.OPERATION_FAILED,message:"no stream data received"}))):w||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new _({code:N.ENV_NOT_SUPPORTED,extraCode:L.NOT_SUPPORTED_H264_DECODE,message:"h264 decode failed"})))}catch(n){this._log.warn("checkStreamHealth error",n)}}connect(i){return new Promise((n,c)=>{try{this.initScriptTransformWorker();const I={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},C=new RTCPeerConnection(I);this.peerConnection=C,C.onconnectionstatechange=()=>{this.connectionState=C.connectionState,this._log.info("connectionState",C.connectionState),C.connectionState!=="failed"&&C.connectionState!=="closed"||(this.isStarted?this.reconnect(i):c(new Error(`connection is ${C.connectionState}`))),C.connectionState==="connected"&&(this.logSelectedCandidate(),n())},C.ontrack=f=>this.onTrack(f),C.addTransceiver("audio",{direction:"recvonly"}),C.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),C.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(f=>(f.sdp=pZ(f.sdp),this._log.info("setOffer"),C.setLocalDescription(f))).then(()=>{const f={sessionId:$j(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:C.localDescription};return this.exchangeSDP(i,f)}).then(f=>(this._log.info("setAnswer"),C.setRemoteDescription(f))).catch(c)}catch(I){c(I)}this.connectionTimeoutId=setTimeout(()=>c(new Error("connection timeout")),1e4)})}async exchangeSDP(i,n){let c,I,C;try{this._log.info("exchangeSDP");const f=baA(i);if(!f)throw new Error("streamDomain is empty");const{signalDomain:w,cached:_}=await this.fetchSignalDomain(f);if(!w)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",w,_);const N=await this.doExchangeSDP(`https://${w}`,n,3);c=N.url,I=N.remoteSdp,C=N.svrSig}}catch(f){this._log.warn("exchangeSDP failed, fallback",f);try{const w=await this.core.utils.promiseAny(GaA.map(_=>this.doExchangeSDP(`https://${_}`,n,3)));c=w.url,I=w.remoteSdp,C=w.svrSig}catch(w){throw this._log.error("exchangeSDP failed",w),w[0]||w}}return this.streamURL=i,this.signalURL=c,this.svrSig=C,I}async reconnect(i){var n,c;if(!this.isReconnecting){this.isReconnecting=!0;try{this._log.warn("start reconnect"),await this.connect(i),this._log.warn("reconnect success")}catch(I){this._log.error("reconnect error",I);const{RtcError:C,ErrorCode:f}=this.core.errorModule;(c=(n=this.callback)==null?void 0:n.onError)==null||c.call(n,new C({code:f.OPERATION_FAILED,message:"reconnect failed"}))}finally{this.isReconnecting=!1}}}async logSelectedCandidate(){if(!this.peerConnection)return;const i=await this.peerConnection.getStats();for(const[n,c]of i)if(this.core.rtcDectection.isSelectedCandidatePair(c)){const I=i.get(c.localCandidateId),C=i.get(c.remoteCandidateId);I&&this._log.info(`local candidate: ${I.candidateType} ${I.protocol}:${I.ip||I.address}:${I.port} ${I.networkType||""} ${I.relayProtocol?`relayProtocol:${I.relayProtocol} url: ${I.url}`:""}`),C&&this._log.info(`remote candidate: ${C.candidateType} ${C.protocol}:${C.ip||C.address}:${C.port}`);break}}async doExchangeSDP(i,n,c){const I=`${i}/webrtc/v1/pullstream`,C=await K1(I,n,{timeout:c}),{errcode:f,errmsg:w,remotesdp:_,svrsig:N}=C;if(f!==0){const L=new Error(`errCode:${f}, errMsg:${w}`);throw L.name="RequestSignalError",L}return{url:i,remoteSdp:_,svrSig:N}}createEncodedStreams(i){var n;if(this.enableSEI&&this.core.rtcDectection.IS_INSERTABLE_STREAM_SUPPORTED)try{if(this._log.warn("enableSEI",this.enableSEI),!this.insertableStreamsAbortMap.has(i)){const c=i.createEncodedStreams(),I=new AbortController,C={abortController:I,enqueue:f=>i.track.kind==="audio"?f:this.decodeVideoFrame(f)};c.readable.pipeThrough(new TransformStream({transform:(f,w)=>{const _=C.enqueue(f);_&&w.enqueue(_)}})).pipeTo(c.writable,I).catch(f=>{f!=="destroy"&&this._log.warn(f)}),(n=this.insertableStreamsAbortMap.get(i))==null||n.abort("destroy"),this.insertableStreamsAbortMap.set(i,I)}}catch(c){this._log.warn(`createEncodedStreams ${i.track.kind} failed`,c)}}initReceiverTransform(i,n){this.peerConnection&&this.enableSEI&&this.scriptTransformWorker&&!i.transform&&(i.transform=new RTCRtpScriptTransform(this.scriptTransformWorker,{isReceiver:!0,isAudio:n,userId:"",streamType:this.core.enums.RemoteStreamType.Main}))}initScriptTransformWorker(){const{room:i,rtcDectection:n,createScriptTransformWorker:c,trtc:I,TRTC:C}=this.core;!this.enableSEI||n.IS_INSERTABLE_STREAM_SUPPORTED||this.scriptTransformWorker||n.IS_SCRIPT_TRANSFORM_SUPPORTED&&(this._log.info("initScriptTransformWorker"),this.scriptTransformWorker=c({videoEncodePipeline:i.videoManager.encodePipeline,videoDecodePipeline:i.videoManager.decodePipeline,audioEncodePipeline:i.audioManager.encodePipeline,audioDecodePipeline:i.audioManager.decodePipeline}),this.scriptTransformWorker.onmessage=f=>{var w,_;f.data.type==="sei"&&((_=(w=this.callback)==null?void 0:w.onSEIMessage)==null||_.call(w,{data:f.data.data,seiPayloadType:f.data.seiPayloadType}))},this.scriptTransformWorker.onerror=f=>{this._log.error("scriptTransformWorker error: ",f.message)})}decodeVideoFrame(i){if(!this.core.room.videoManager)return i;for(const n of this.core.room.videoManager.decodePipeline)if(n&&!(i=n({frame:i})))return;return i}async fetchStopStream(){if(this.streamURL&&this.svrSig&&this.signalURL)try{const i=`${this.signalURL}/webrtc/v1/stopstream`,n=await K1(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:c,errmsg:I}=n;if(c!==0)throw new Error(`errCode:${c}, errmsg:${I}`);return n}catch(i){this._log.error("fetchStopStream error",i)}}onTrack(i){const{track:n}=i;this.createEncodedStreams(i.receiver),this.initReceiverTransform(i.receiver,n.kind==="audio"),n.kind==="audio"?this.player.setAudioTrack(n):this.player.setVideoTrack(n)}onSEIMessage({room:i,nalu:n}){var c,I;i===this.core.room&&((I=(c=this.callback)==null?void 0:c.onSEIMessage)==null||I.call(c,{data:n.seiPayload.buffer,seiPayloadType:n.seiPayloadType}))}async fetchSignalDomain(i,n=j1[0]){var c;const I=`https://${n}/signal_query`;try{const C=window.localStorage.getItem(t3);if(C){const L=JSON.parse(C);if(((c=L[i])==null?void 0:c.expire)-new Date().getTime()>0)return{signalDomain:L[i].signal,cached:!0}}const f=await K1(I,{domain:i,requestid:$j(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:w,errmsg:_,data:N}=f;if(w===0){const{signal_domain:L,cache_time:q}=N;let lA={};const tA=window.localStorage.getItem(t3);tA&&(lA=JSON.parse(tA)),lA[i]={signal:L,expire:new Date().getTime()+1e3*q};try{window.localStorage.setItem(t3,JSON.stringify(lA))}catch{}return{signalDomain:L,cached:!1}}throw new Error(`errCode:${w} errmsg:${_}`)}catch(C){return this._log.error("fetchSignalDomain error",C),j1[1]&&n!==j1[1]?this.fetchSignalDomain(i,j1[1]):{signalDomain:"",cached:!1}}}};pn(hY,"Name","LEBPlayer"),V_([RaA({fnName:"connect"})],hY.prototype,"stop"),V_([vaA({settings:{retries:1/0,timeout:2e3},onRetrying(t){var i;if(this._log.warn(`retry connect ${t}`),t>=3&&((i=this.callback)==null?void 0:i.onError)&&!this.isFireWallErrorEmitted){const{RtcError:n,ErrorCode:c,ErrorCodeDictionary:I}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new n({code:c.OPERATION_FAILED,extraCode:I.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(t,i,n,c){var I;if(this._log.warn("connect failed",t),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((I=t.message||t)==null?void 0:I.includes("connection")))i();else{const{RtcError:C,ErrorCode:f}=this.core.errorModule;n(new C({code:f.UNKNOWN_ERROR,message:t.message}))}}})],hY.prototype,"connect");var dX=hY,K1=async(t,i,n={})=>{const{timeout:c=10}=n;let I,C=0,f={};window.AbortController&&(I=new window.AbortController,f={signal:I.signal},C=window.setTimeout(()=>I.abort(),1e3*c));const w=await fetch(t,daA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},f));if(C&&window.clearTimeout(C),w.status!==200)throw new Error(`Network Error, status code:${w.status}`);return w.json()},j1=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],t3="LEB_PLAYER_STORAGE_KEY",baA=t=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(t);return i?i[1]:""},kaA=dX;const LaA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:dX,default:kaA},Symbol.toStringTag,{value:"Module"})),UaA=HU(LaA);var CX=Object.defineProperty,FaA=Object.defineProperties,OaA=Object.getOwnPropertyDescriptors,DZ=Object.getOwnPropertySymbols,PaA=Object.prototype.hasOwnProperty,xaA=Object.prototype.propertyIsEnumerable,eW=(t,i,n)=>i in t?CX(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,YaA=(t,i)=>{for(var n in i||(i={}))PaA.call(i,n)&&eW(t,n,i[n]);if(DZ)for(var n of DZ(i))xaA.call(i,n)&&eW(t,n,i[n]);return t},VaA=(t,i)=>FaA(t,OaA(i)),JaA=(t,i)=>{for(var n in i)CX(t,n,{get:i[n],enumerable:!0})},Hg=(t,i,n)=>eW(t,typeof i!="symbol"?i+"":i,n);async function HaA({sdkAppId:t,userId:i,userSig:n,core:c}){var I;const C=Math.round(new Date().getTime()/1e3);try{const f=await c.schedule.getAbilityConfig(t,c.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:t,userId:i,userSig:n,timestamp:C});c.log.info(`virtual background ability response: ${JSON.stringify(f)}`);const{data:w}=f;return(I=w?.trtcAutoConf)!=null&&I.web_ar?{auth:!0,timestamp:C}:{auth:!1}}catch(f){return c.log.error("virtual background fetch error",f),{auth:!1}}}var qaA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function KaA(t){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:VaA(YaA({},qaA),{type:{required:!1,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},onAbort:{required:!1},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}}),validate(i,n,c,I){var C;const{RtcError:f,ErrorCode:w,ErrorCodeDictionary:_}=t.errorModule;if(!i)return;const{type:N,src:L,onAbort:q}=i;if(N==="image"&&!L)throw new f({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}});if(q&&!t.utils.isFunction(q))throw new f({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onAbort",value:typeof q,rule:{type:"Function"}}});if(!((C=t.room.videoManager.cameraTrack)!=null&&C.mediaTrack))throw new f({code:w.INVALID_OPERATION,extraCode:_.INVALID_OPERATION_NEED_VIDEO,fnName:c})}}}function jaA(t){return{name:"UpdateVirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:{type:{required:!0,type:"string",values:["image","blur","color"]},src:{required:!1,type:"string"},blurLevel:{required:!1,type:"number",min:1,max:10},color:{required:!1,type:["array","string"]},enableFaceCentering:{required:!1,type:"boolean"},enableEffectOptimization:{required:!1,type:"boolean"}},validate(i,n,c,I){if(!i)return;const{RtcError:C,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule,{type:_,src:N}=i;if(_==="image"&&!N)throw new C({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_REQUIRED,fnName:c,messageParams:{key:"src"}})}}}function WaA(t){return{name:"StopVirtualBackgroundOptions",required:!1}}var zaA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),f="";typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),t&&(f=t),f=f.indexOf("blob:")!==0?f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,N=I.print||console.log.bind(console),L=I.printErr||console.error.bind(console);function q($){if(ti($))return function(j){for(var vA=atob(j),jA=new Uint8Array(vA.length),oe=0;oe$.startsWith(Dt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ce&&w)return new Uint8Array(w);var vA=q(j);if(vA)return vA;throw"both async and sync fetching of the wasm failed"}($))}function oi($,j,vA,jA){return function(oe,ye,He){return Pt(oe).then(Pe=>WebAssembly.instantiate(Pe,ye)).then(Pe=>Pe).then(He,Pe=>{L(`failed to asynchronously prepare wasm: ${Pe}`),ct(Pe)})}(j,vA,jA)}ti(ce="data:application/octet-stream;base64,AGFzbQEAAAAB8gEfYAJ/fwBgAX8Bf2ADf39/AX9gAX8AYAN/f38AYAJ/fwF/YAR/f39/AGAAAGAFf39/f38AYAZ/f39/f38AYAR/f39/AX9gB39/f39/f38AYAN/fn8BfmAFf3x8fHwAYAZ/fHx8fHwAYAV/f39/fwF8YAl/f39/f39/f38AYAN/f38BfGAKf39/f39/f39/fwBgDX9/f39/f39/f39/f38AYAJ/fABgAn5/AX9gAn99AGABfAF8YAZ/fH9/f38Bf2AGf39/f39/AX9gAnx/AXxgBH9/fn4AYAZ/f3x8fHwAYAd/f3x8fHx8AGAFf39/f38BfwKXARkBYQFhAAQBYQFiAAMBYQFjAAMBYQFkAAMBYQFlAA8BYQFmAAIBYQFnAAgBYQFoAAUBYQFpABABYQFqABEBYQFrABIBYQFsAAQBYQFtAAcBYQFuAAoBYQFvAAABYQFwAAQBYQFxAAsBYQFyAAEBYQFzAAQBYQF0AAABYQF1AAYBYQF2AAABYQF3AAQBYQF4AAkBYQF5ABMDZmUDBQIBBAIIBRQCBAUFAgcBFQEAAwEWAAQABAUFBRcHBwMBBgUEBQMAAwIECwQCAQUYBgEZChoBAwcDBhsHAQEBCQkICAQCBgYCAgAAAgEABQwBAgMBAAMAAwEcDR0OAAAAAAAeAAQFAXABNzcFBgEBgAKAAgYNAn8BQeDiBAt/AUEACwchCAF6AgABQQA4AUIALQFDAQABRABtAUUAGQFGAFgBRwB8CTwBAEEBCzZybGhmZGM+XX17enl4d3Z1dHNxcG9uPjpVUWpraUlnZUcsUFBiLGFZW2AsWlxfLF5HLFc5VjkK/pQCZfULAQd/AkAgAEUNACAAQQhrIgIgAEEEaygCACIBQXhxIgBqIQUCQCABQQFxDQAgAUEDcUUNASACIAIoAgAiAWsiAkH83gAoAgBJDQEgACABaiEAAkACQEGA3wAoAgAgAkcEQCABQf8BTQRAIAFBA3YhBCACKAIMIgEgAigCCCIDRgRAQezeAEHs3gAoAgBBfiAEd3E2AgAMBQsgAyABNgIMIAEgAzYCCAwECyACKAIYIQYgAiACKAIMIgFHBEAgAigCCCIDIAE2AgwgASADNgIIDAMLIAJBFGoiBCgCACIDRQRAIAIoAhAiA0UNAiACQRBqIQQLA0AgBCEHIAMiAUEUaiIEKAIAIgMNACABQRBqIQQgASgCECIDDQALIAdBADYCAAwCCyAFKAIEIgFBA3FBA0cNAkH03gAgADYCACAFIAFBfnE2AgQgAiAAQQFyNgIEIAUgADYCAA8LQQAhAQsgBkUNAAJAIAIoAhwiA0ECdEGc4QBqIgQoAgAgAkYEQCAEIAE2AgAgAQ0BQfDeAEHw3gAoAgBBfiADd3E2AgAMAgsgBkEQQRQgBigCECACRhtqIAE2AgAgAUUNAQsgASAGNgIYIAIoAhAiAwRAIAEgAzYCECADIAE2AhgLIAIoAhQiA0UNACABIAM2AhQgAyABNgIYCyACIAVPDQAgBSgCBCIBQQFxRQ0AAkACQAJAAkAgAUECcUUEQEGE3wAoAgAgBUYEQEGE3wAgAjYCAEH43gBB+N4AKAIAIABqIgA2AgAgAiAAQQFyNgIEIAJBgN8AKAIARw0GQfTeAEEANgIAQYDfAEEANgIADwtBgN8AKAIAIAVGBEBBgN8AIAI2AgBB9N4AQfTeACgCACAAaiIANgIAIAIgAEEBcjYCBCAAIAJqIAA2AgAPCyABQXhxIABqIQAgAUH/AU0EQCABQQN2IQQgBSgCDCIBIAUoAggiA0YEQEHs3gBB7N4AKAIAQX4gBHdxNgIADAULIAMgATYCDCABIAM2AggMBAsgBSgCGCEGIAUgBSgCDCIBRwRAQfzeACgCABogBSgCCCIDIAE2AgwgASADNgIIDAMLIAVBFGoiBCgCACIDRQRAIAUoAhAiA0UNAiAFQRBqIQQLA0AgBCEHIAMiAUEUaiIEKAIAIgMNACABQRBqIQQgASgCECIDDQALIAdBADYCAAwCCyAFIAFBfnE2AgQgAiAAQQFyNgIEIAAgAmogADYCAAwDC0EAIQELIAZFDQACQCAFKAIcIgNBAnRBnOEAaiIEKAIAIAVGBEAgBCABNgIAIAENAUHw3gBB8N4AKAIAQX4gA3dxNgIADAILIAZBEEEUIAYoAhAgBUYbaiABNgIAIAFFDQELIAEgBjYCGCAFKAIQIgMEQCABIAM2AhAgAyABNgIYCyAFKAIUIgNFDQAgASADNgIUIAMgATYCGAsgAiAAQQFyNgIEIAAgAmogADYCACACQYDfACgCAEcNAEH03gAgADYCAA8LIABB/wFNBEAgAEF4cUGU3wBqIQECf0Hs3gAoAgAiA0EBIABBA3Z0IgBxRQRAQezeACAAIANyNgIAIAEMAQsgASgCCAshACABIAI2AgggACACNgIMIAIgATYCDCACIAA2AggPC0EfIQMgAEH///8HTQRAIABBJiAAQQh2ZyIBa3ZBAXEgAUEBdGtBPmohAwsgAiADNgIcIAJCADcCECADQQJ0QZzhAGohAQJAAkACQEHw3gAoAgAiBEEBIAN0IgdxRQRAQfDeACAEIAdyNgIAIAEgAjYCACACIAE2AhgMAQsgAEEZIANBAXZrQQAgA0EfRxt0IQMgASgCACEBA0AgASIEKAIEQXhxIABGDQIgA0EddiEBIANBAXQhAyAEIAFBBHFqIgdBEGooAgAiAQ0ACyAHIAI2AhAgAiAENgIYCyACIAI2AgwgAiACNgIIDAELIAQoAggiACACNgIMIAQgAjYCCCACQQA2AhggAiAENgIMIAIgADYCCAtBjN8AQYzfACgCAEEBayIAQX8gABs2AgALCwwAIAAgASABECoQGwu9AQEDfyMAQRBrIgUkAAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIEAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgNrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIEIANqIAEgAhAjIAAgAiADaiIBEDEgBUEAOgAPIAEgBGogBS0ADzoAAAwBCyAAIAQgAiAEayADaiADIAMgAiABEEQLIAVBEGokACAACzYBAX9BASAAIABBAU0bIQACQANAIAAQLSIBDQFB3OIAKAIAIgEEQCABEQcADAELCxAMAAsgAQvBAQEDfyAALQAAQSBxRQRAAkAgAiAAKAIQIgMEfyADBSAAEE8NASAAKAIQCyAAKAIUIgRrSwRAIAAgASACIAAoAiQRAgAaDAELAkACQCAAKAJQQQBIDQAgAkUNACACIQMDQCABIANqIgVBAWstAABBCkcEQCADQQFrIgMNAQwCCwsgACABIAMgACgCJBECACADSQ0CIAIgA2shAiAAKAIUIQQMAQsgASEFCyAEIAUgAhAiGiAAIAAoAhQgAmo2AhQLCwt0AQF/IAJFBEAgACgCBCABKAIERg8LIAAgAUYEQEEBDwsgASgCBCICLQAAIQECQCAAKAIEIgMtAAAiAEUNACAAIAFHDQADQCACLQABIQEgAy0AASIARQ0BIAJBAWohAiADQQFqIQMgACABRg0ACwsgACABRgtvAQF/IwBBgAJrIgUkAAJAIAIgA0wNACAEQYDABHENACAFIAFB/wFxIAIgA2siA0GAAiADQYACSSIBGxAmGiABRQRAA0AgACAFQYACEB0gA0GAAmsiA0H/AUsNAAsLIAAgBSADEB0LIAVBgAJqJAALgQMBBH8jAEHwAGsiAiQAIAAoAgAiA0EEaygCACEEIANBCGsoAgAhBSACQgA3AlAgAkIANwJYIAJCADcCYCACQgA3AGcgAkIANwJIIAJBADYCRCACQdzMADYCQCACIAA2AjwgAiABNgI4IAAgBWohAwJAIAQgAUEAEB4EQEEAIAMgBRshAAwBCyAAIANOBEAgAkIANwAvIAJCADcCGCACQgA3AiAgAkIANwIoIAJCADcCECACQQA2AgwgAiABNgIIIAIgADYCBCACIAQ2AgAgAkEBNgIwIAQgAiADIANBAUEAIAQoAgAoAhQRCQAgAigCGA0BC0EAIQAgBCACQThqIANBAUEAIAQoAgAoAhgRCAACQAJAIAIoAlwOAgABAgsgAigCTEEAIAIoAlhBAUYbQQAgAigCVEEBRhtBACACKAJgQQFGGyEADAELIAIoAlBBAUcEQCACKAJgDQEgAigCVEEBRw0BIAIoAlhBAUcNAQsgAigCSCEACyACQfAAaiQAIAAL0AEBBX8jAEEQayIGJAAgBkEEaiICED8jAEEQayIFJAACfyACLQALQQd2BEAgAigCBAwBCyACLQALQf8AcQshBANAAkACfyACLQALQQd2BEAgAigCAAwBCyACCyEDIAUgATkDACACAn8gAyAEQQFqIAUQRiIDQQBOBEAgAyAETQ0CIAMMAQsgBEEBdEEBcgsiBBArDAELCyACIAMQKyAAIAIpAgA3AgAgACACKAIINgIIIAJCADcCACACQQA2AgggBUEQaiQAIAIQQSAGQRBqJAALgAQBA38gAkGABE8EQCAAIAEgAhASIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAEEDcUUEQCAAIQIMAQsgAkUEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAFBAWohASACQQFqIgJBA3FFDQEgAiADSQ0ACwsCQCADQXxxIgRBwABJDQAgAiAEQUBqIgVLDQADQCACIAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRrIAE2AgAgAkEYayABNgIAIAJBHGsgATYCACAEIANBBHFBGHIiBGsiAkEgSQ0AIAGtQoGAgIAQfiEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkEgayICQR9LDQALCyAACwUAEAwAC1IBAn9B2NQAKAIAIgEgAEEHakF4cSICaiEAAkAgAkEAIAAgAU0bDQAgAD8AQRB0SwRAIAAQEUUNAQtB2NQAIAA2AgAgAQ8LQejeAEEwNgIAQX8LgwECBX8BfgJAIABCgICAgBBUBEAgACEHDAELA0AgAUEBayIBIAAgAEIKgCIHQgp+fadBMHI6AAAgAEL/////nwFWIQUgByEAIAUNAAsLIAenIgIEQANAIAFBAWsiASACIAJBCm4iA0EKbGtBMHI6AAAgAkEJSyEGIAMhAiAGDQALCyABC3oBA38CQAJAIAAiAUEDcUUNACABLQAARQRAQQAPCwNAIAFBAWoiAUEDcUUNASABLQAADQALDAELA0AgASICQQRqIQEgAigCACIDQX9zIANBgYKECGtxQYCBgoR4cUUNAAsDQCACIgFBAWohAiABLQAADQALCyABIABrC78EAQl/AkACfyAALQALQQd2BEAgACgCBAwBCyAALQALQf8AcQsiAiABSQRAIwBBEGsiBiQAIAEgAmsiBQRAIAUgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyICAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgFrSwRAIwBBEGsiBCQAAkAgBSACayABaiIDQe////8HIAJrTQRAAn8gAC0AC0EHdgRAIAAoAgAMAQsgAAshByAEQQRqIgggACACQef///8DSQR/IAQgAkEBdDYCDCAEIAIgA2o2AgQjAEEQayIDJAAgCCgCACAEQQxqIgkoAgBJIQogA0EQaiQAIAkgCCAKGygCACIDQQtPBH8gA0EQakFwcSIDIANBAWsiAyADQQtGGwVBCgtBAWoFQe////8HCxAwIAQoAgQhAyAEKAIIGiABBEAgAyAHIAEQIwsgAkEKRwRAIAcQGQsgACADNgIAIAAgACgCCEGAgICAeHEgBCgCCEH/////B3FyNgIIIAAgACgCCEGAgICAeHI2AgggBEEQaiQADAELECcACyAAIAE2AgQLIAECfyAALQALQQd2BEAgACgCAAwBCyAACyICaiAFEEAgACABIAVqIgAQMSAGQQA6AA8gACACaiAGLQAPOgAACyAGQRBqJAAMAQsCfyAALQALQQd2BEAgACgCAAwBCyAACyEEIwBBEGsiAiQAIAAgARAxIAJBADoADyABIARqIAItAA86AAAgAkEQaiQACwsGACAAEBkL0igBDH8jAEEQayIKJAACQAJAAkACQAJAAkACQAJAAkAgAEH0AU0EQEHs3gAoAgAiBkEQIABBC2pBeHEgAEELSRsiBUEDdiIAdiIBQQNxBEACQCABQX9zQQFxIABqIgJBA3QiAUGU3wBqIgAgAUGc3wBqKAIAIgEoAggiA0YEQEHs3gAgBkF+IAJ3cTYCAAwBCyADIAA2AgwgACADNgIICyABQQhqIQAgASACQQN0IgJBA3I2AgQgASACaiIBIAEoAgRBAXI2AgQMCgsgBUH03gAoAgAiB00NASABBEACQEECIAB0IgJBACACa3IgASAAdHFoIgFBA3QiAEGU3wBqIgIgAEGc3wBqKAIAIgAoAggiA0YEQEHs3gAgBkF+IAF3cSIGNgIADAELIAMgAjYCDCACIAM2AggLIAAgBUEDcjYCBCAAIAVqIgQgAUEDdCIBIAVrIgNBAXI2AgQgACABaiADNgIAIAcEQCAHQXhxQZTfAGohAUGA3wAoAgAhAgJ/IAZBASAHQQN2dCIFcUUEQEHs3gAgBSAGcjYCACABDAELIAEoAggLIQUgASACNgIIIAUgAjYCDCACIAE2AgwgAiAFNgIICyAAQQhqIQBBgN8AIAQ2AgBB9N4AIAM2AgAMCgtB8N4AKAIAIgtFDQEgC2hBAnRBnOEAaigCACICKAIEQXhxIAVrIQQgAiEBA0ACQCABKAIQIgBFBEAgASgCFCIARQ0BCyAAKAIEQXhxIAVrIgEgBCABIARJIgEbIQQgACACIAEbIQIgACEBDAELCyACKAIYIQkgAiACKAIMIgNHBEBB/N4AKAIAGiACKAIIIgAgAzYCDCADIAA2AggMCQsgAkEUaiIBKAIAIgBFBEAgAigCECIARQ0DIAJBEGohAQsDQCABIQggACIDQRRqIgEoAgAiAA0AIANBEGohASADKAIQIgANAAsgCEEANgIADAgLQX8hBSAAQb9/Sw0AIABBC2oiAEF4cSEFQfDeACgCACIIRQ0AQQAgBWshBAJAAkACQAJ/QQAgBUGAAkkNABpBHyAFQf///wdLDQAaIAVBJiAAQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgdBAnRBnOEAaigCACIBRQRAQQAhAAwBC0EAIQAgBUEZIAdBAXZrQQAgB0EfRxt0IQIDQAJAIAEoAgRBeHEgBWsiBiAETw0AIAEhAyAGIgQNAEEAIQQgASEADAMLIAAgASgCFCIGIAYgASACQR12QQRxaigCECIBRhsgACAGGyEAIAJBAXQhAiABDQALCyAAIANyRQRAQQAhA0ECIAd0IgBBACAAa3IgCHEiAEUNAyAAaEECdEGc4QBqKAIAIQALIABFDQELA0AgACgCBEF4cSAFayICIARJIQEgAiAEIAEbIQQgACADIAEbIQMgACgCECIBBH8gAQUgACgCFAsiAA0ACwsgA0UNACAEQfTeACgCACAFa08NACADKAIYIQcgAyADKAIMIgJHBEBB/N4AKAIAGiADKAIIIgAgAjYCDCACIAA2AggMBwsgA0EUaiIBKAIAIgBFBEAgAygCECIARQ0DIANBEGohAQsDQCABIQYgACICQRRqIgEoAgAiAA0AIAJBEGohASACKAIQIgANAAsgBkEANgIADAYLIAVB9N4AKAIAIgNNBEBBgN8AKAIAIQACQCADIAVrIgFBEE8EQCAAIAVqIgIgAUEBcjYCBCAAIANqIAE2AgAgACAFQQNyNgIEDAELIAAgA0EDcjYCBCAAIANqIgEgASgCBEEBcjYCBEEAIQJBACEBC0H03gAgATYCAEGA3wAgAjYCACAAQQhqIQAMCAsgBUH43gAoAgAiAkkEQEH43gAgAiAFayIBNgIAQYTfAEGE3wAoAgAiACAFaiICNgIAIAIgAUEBcjYCBCAAIAVBA3I2AgQgAEEIaiEADAgLQQAhACAFQS9qIgQCf0HE4gAoAgAEQEHM4gAoAgAMAQtB0OIAQn83AgBByOIAQoCggICAgAQ3AgBBxOIAIApBDGpBcHFB2KrVqgVzNgIAQdjiAEEANgIAQajiAEEANgIAQYAgCyIBaiIGQQAgAWsiCHEiASAFTQ0HQaTiACgCACIDBEBBnOIAKAIAIgcgAWoiCSAHTQ0IIAMgCUkNCAsCQEGo4gAtAABBBHFFBEACQAJAAkACQEGE3wAoAgAiAwRAQaziACEAA0AgAyAAKAIAIgdPBEAgByAAKAIEaiADSw0DCyAAKAIIIgANAAsLQQAQKCICQX9GDQMgASEGQcjiACgCACIAQQFrIgMgAnEEQCABIAJrIAIgA2pBACAAa3FqIQYLIAUgBk8NA0Gk4gAoAgAiAARAQZziACgCACIDIAZqIgggA00NBCAAIAhJDQQLIAYQKCIAIAJHDQEMBQsgBiACayAIcSIGECgiAiAAKAIAIAAoAgRqRg0BIAIhAAsgAEF/Rg0BIAVBMGogBk0EQCAAIQIMBAtBzOIAKAIAIgIgBCAGa2pBACACa3EiAhAoQX9GDQEgAiAGaiEGIAAhAgwDCyACQX9HDQILQajiAEGo4gAoAgBBBHI2AgALIAEQKCECQQAQKCEAIAJBf0YNBSAAQX9GDQUgACACTQ0FIAAgAmsiBiAFQShqTQ0FC0Gc4gBBnOIAKAIAIAZqIgA2AgBBoOIAKAIAIABJBEBBoOIAIAA2AgALAkBBhN8AKAIAIgQEQEGs4gAhAANAIAIgACgCACIBIAAoAgQiA2pGDQIgACgCCCIADQALDAQLQfzeACgCACIAQQAgACACTRtFBEBB/N4AIAI2AgALQQAhAEGw4gAgBjYCAEGs4gAgAjYCAEGM3wBBfzYCAEGQ3wBBxOIAKAIANgIAQbjiAEEANgIAA0AgAEEDdCIBQZzfAGogAUGU3wBqIgM2AgAgAUGg3wBqIAM2AgAgAEEBaiIAQSBHDQALQfjeACAGQShrIgBBeCACa0EHcSIBayIDNgIAQYTfACABIAJqIgE2AgAgASADQQFyNgIEIAAgAmpBKDYCBEGI3wBB1OIAKAIANgIADAQLIAIgBE0NAiABIARLDQIgACgCDEEIcQ0CIAAgAyAGajYCBEGE3wAgBEF4IARrQQdxIgBqIgE2AgBB+N4AQfjeACgCACAGaiICIABrIgA2AgAgASAAQQFyNgIEIAIgBGpBKDYCBEGI3wBB1OIAKAIANgIADAMLQQAhAwwFC0EAIQIMAwtB/N4AKAIAIAJLBEBB/N4AIAI2AgALIAIgBmohAUGs4gAhAAJAAkACQANAIAEgACgCAEcEQCAAKAIIIgANAQwCCwsgAC0ADEEIcUUNAQtBrOIAIQADQAJAIAQgACgCACIBTwRAIAEgACgCBGoiAyAESw0BCyAAKAIIIQAMAQsLQfjeACAGQShrIgBBeCACa0EHcSIBayIINgIAQYTfACABIAJqIgE2AgAgASAIQQFyNgIEIAAgAmpBKDYCBEGI3wBB1OIAKAIANgIAIAQgA0EnIANrQQdxakEvayIAIAAgBEEQakkbIgFBGzYCBCABQbTiACkCADcCECABQaziACkCADcCCEG04gAgAUEIajYCAEGw4gAgBjYCAEGs4gAgAjYCAEG44gBBADYCACABQRhqIQADQCAAQQc2AgQgAEEIaiEMIABBBGohACAMIANJDQALIAEgBEYNAiABIAEoAgRBfnE2AgQgBCABIARrIgJBAXI2AgQgASACNgIAIAJB/wFNBEAgAkF4cUGU3wBqIQACf0Hs3gAoAgAiAUEBIAJBA3Z0IgJxRQRAQezeACABIAJyNgIAIAAMAQsgACgCCAshASAAIAQ2AgggASAENgIMIAQgADYCDCAEIAE2AggMAwtBHyEAIAJB////B00EQCACQSYgAkEIdmciAGt2QQFxIABBAXRrQT5qIQALIAQgADYCHCAEQgA3AhAgAEECdEGc4QBqIQECQEHw3gAoAgAiA0EBIAB0IgZxRQRAQfDeACADIAZyNgIAIAEgBDYCAAwBCyACQRkgAEEBdmtBACAAQR9HG3QhACABKAIAIQMDQCADIgEoAgRBeHEgAkYNAyAAQR12IQMgAEEBdCEAIAEgA0EEcWoiBigCECIDDQALIAYgBDYCEAsgBCABNgIYIAQgBDYCDCAEIAQ2AggMAgsgACACNgIAIAAgACgCBCAGajYCBCACQXggAmtBB3FqIgcgBUEDcjYCBCABQXggAWtBB3FqIgQgBSAHaiIFayEGAkBBhN8AKAIAIARGBEBBhN8AIAU2AgBB+N4AQfjeACgCACAGaiIANgIAIAUgAEEBcjYCBAwBC0GA3wAoAgAgBEYEQEGA3wAgBTYCAEH03gBB9N4AKAIAIAZqIgA2AgAgBSAAQQFyNgIEIAAgBWogADYCAAwBCyAEKAIEIgJBA3FBAUYEQCACQXhxIQkCQCACQf8BTQRAIAQoAgwiACAEKAIIIgFGBEBB7N4AQezeACgCAEF+IAJBA3Z3cTYCAAwCCyABIAA2AgwgACABNgIIDAELIAQoAhghCAJAIAQgBCgCDCIARwRAQfzeACgCABogBCgCCCIBIAA2AgwgACABNgIIDAELAkAgBEEUaiIBKAIAIgJFBEAgBCgCECICRQ0BIARBEGohAQsDQCABIQMgAiIAQRRqIgEoAgAiAg0AIABBEGohASAAKAIQIgINAAsgA0EANgIADAELQQAhAAsgCEUNAAJAIAQoAhwiAUECdEGc4QBqIgIoAgAgBEYEQCACIAA2AgAgAA0BQfDeAEHw3gAoAgBBfiABd3E2AgAMAgsgCEEQQRQgCCgCECAERhtqIAA2AgAgAEUNAQsgACAINgIYIAQoAhAiAQRAIAAgATYCECABIAA2AhgLIAQoAhQiAUUNACAAIAE2AhQgASAANgIYCyAGIAlqIQYgBCAJaiIEKAIEIQILIAQgAkF+cTYCBCAFIAZBAXI2AgQgBSAGaiAGNgIAIAZB/wFNBEAgBkF4cUGU3wBqIQACf0Hs3gAoAgAiAUEBIAZBA3Z0IgJxRQRAQezeACABIAJyNgIAIAAMAQsgACgCCAshASAAIAU2AgggASAFNgIMIAUgADYCDCAFIAE2AggMAQtBHyECIAZB////B00EQCAGQSYgBkEIdmciAGt2QQFxIABBAXRrQT5qIQILIAUgAjYCHCAFQgA3AhAgAkECdEGc4QBqIQECQAJAQfDeACgCACIAQQEgAnQiA3FFBEBB8N4AIAAgA3I2AgAgASAFNgIADAELIAZBGSACQQF2a0EAIAJBH0cbdCECIAEoAgAhAANAIAAiASgCBEF4cSAGRg0CIAJBHXYhACACQQF0IQIgASAAQQRxaiIDKAIQIgANAAsgAyAFNgIQCyAFIAE2AhggBSAFNgIMIAUgBTYCCAwBCyABKAIIIgAgBTYCDCABIAU2AgggBUEANgIYIAUgATYCDCAFIAA2AggLIAdBCGohAAwFCyABKAIIIgAgBDYCDCABIAQ2AgggBEEANgIYIAQgATYCDCAEIAA2AggLQfjeACgCACIAIAVNDQBB+N4AIAAgBWsiATYCAEGE3wBBhN8AKAIAIgAgBWoiAjYCACACIAFBAXI2AgQgACAFQQNyNgIEIABBCGohAAwDC0Ho3gBBMDYCAEEAIQAMAgsCQCAHRQ0AAkAgAygCHCIAQQJ0QZzhAGoiASgCACADRgRAIAEgAjYCACACDQFB8N4AIAhBfiAAd3EiCDYCAAwCCyAHQRBBFCAHKAIQIANGG2ogAjYCACACRQ0BCyACIAc2AhggAygCECIABEAgAiAANgIQIAAgAjYCGAsgAygCFCIARQ0AIAIgADYCFCAAIAI2AhgLAkAgBEEPTQRAIAMgBCAFaiIAQQNyNgIEIAAgA2oiACAAKAIEQQFyNgIEDAELIAMgBUEDcjYCBCADIAVqIgIgBEEBcjYCBCACIARqIAQ2AgAgBEH/AU0EQCAEQXhxQZTfAGohAAJ/QezeACgCACIBQQEgBEEDdnQiBXFFBEBB7N4AIAEgBXI2AgAgAAwBCyAAKAIICyEBIAAgAjYCCCABIAI2AgwgAiAANgIMIAIgATYCCAwBC0EfIQAgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAAsgAiAANgIcIAJCADcCECAAQQJ0QZzhAGohAQJAAkAgCEEBIAB0IgVxRQRAQfDeACAFIAhyNgIAIAEgAjYCAAwBCyAEQRkgAEEBdmtBACAAQR9HG3QhACABKAIAIQUDQCAFIgEoAgRBeHEgBEYNAiAAQR12IQUgAEEBdCEAIAEgBUEEcWoiBigCECIFDQALIAYgAjYCEAsgAiABNgIYIAIgAjYCDCACIAI2AggMAQsgASgCCCIAIAI2AgwgASACNgIIIAJBADYCGCACIAE2AgwgAiAANgIICyADQQhqIQAMAQsCQCAJRQ0AAkAgAigCHCIAQQJ0QZzhAGoiASgCACACRgRAIAEgAzYCACADDQFB8N4AIAtBfiAAd3E2AgAMAgsgCUEQQRQgCSgCECACRhtqIAM2AgAgA0UNAQsgAyAJNgIYIAIoAhAiAARAIAMgADYCECAAIAM2AhgLIAIoAhQiAEUNACADIAA2AhQgACADNgIYCwJAIARBD00EQCACIAQgBWoiAEEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwBCyACIAVBA3I2AgQgAiAFaiIDIARBAXI2AgQgAyAEaiAENgIAIAcEQCAHQXhxQZTfAGohAEGA3wAoAgAhAQJ/QQEgB0EDdnQiBSAGcUUEQEHs3gAgBSAGcjYCACAADAELIAAoAggLIQUgACABNgIIIAUgATYCDCABIAA2AgwgASAFNgIIC0GA3wAgAzYCAEH03gAgBDYCAAsgAkEIaiEACyAKQRBqJAAgAAvXAQIFfwF8IwBBEGsiBiQAIAZBBGoiAhA/IwBBEGsiBSQAIAG7IQcCfyACLQALQQd2BEAgAigCBAwBCyACLQALQf8AcQshBANAAkACfyACLQALQQd2BEAgAigCAAwBCyACCyEDIAUgBzkDACACAn8gAyAEQQFqIAUQRiIDQQBOBEAgAyAETQ0CIAMMAQsgBEEBdEEBcgsiBBArDAELCyACIAMQKyAAIAIpAgA3AgAgACACKAIINgIIIAJCADcCACACQQA2AgggBUEQaiQAIAIQQSAGQRBqJAAL9gUBCH8jAEEgayIHJAAgB0EMaiEEAkAgB0EVaiIGIgIgB0EgaiIJRg0AIAFBAE4NACACQS06AAAgAkEBaiECQQAgAWshAQsgBAJ/IAkiAyACayIFQQlMBEBBPSAFQSAgAUEBcmdrQdEJbEEMdSIIIAhBAnRBwMoAaigCACABTWpIDQEaCwJ/IAFBv4Q9TQRAIAFBj84ATQRAIAFB4wBNBEAgAUEJTQRAIAIgAUEwajoAACACQQFqDAQLIAIgARAkDAMLIAFB5wdNBEAgAiABQeQAbiIDQTBqOgAAIAJBAWogASADQeQAbGsQJAwDCyACIAEQNQwCCyABQZ+NBk0EQCACIAFBkM4AbiIDQTBqOgAAIAJBAWogASADQZDOAGxrEDUMAgsgAiABEDQMAQsgAUH/wdcvTQRAIAFB/6ziBE0EQCACIAFBwIQ9biIDQTBqOgAAIAJBAWogASADQcCEPWxrEDQMAgsgAiABEDMMAQsgAUH/k+vcA00EQCACIAFBgMLXL24iA0EwajoAACACQQFqIAEgA0GAwtcvbGsQMwwBCyACIAFBgMLXL24iAxAkIAEgA0GAwtcvbGsQMwshA0EACzYCBCAEIAM2AgAgBygCDCEIIwBBEGsiAyQAIwBBEGsiBSQAIAAhAQJAIAggBiIAayIGQe////8HTQRAAkAgBkELSQRAIAEgAS0AC0GAAXEgBkH/AHFyOgALIAEgAS0AC0H/AHE6AAsgASEEDAELIAVBCGogASAGQQtPBH8gBkEQakFwcSIEIARBAWsiBCAEQQtGGwVBCgtBAWoQMCAFKAIMGiABIAUoAggiBDYCACABIAEoAghBgICAgHhxIAUoAgxB/////wdxcjYCCCABIAEoAghBgICAgHhyNgIIIAEgBjYCBAsDQCAAIAhHBEAgBCAALQAAOgAAIARBAWohBCAAQQFqIQAMAQsLIAVBADoAByAEIAUtAAc6AAAgBUEQaiQADAELECcACyADQRBqJAAgCSQACxYAIAIQHCEBIAAgAjYCBCAAIAE2AgALOAAgAC0AC0EHdgRAIAAgATYCBA8LIAAgAC0AC0GAAXEgAUH/AHFyOgALIAAgAC0AC0H/AHE6AAsL1QIBAn8CQCAAIAFGDQAgASAAIAJqIgRrQQAgAkEBdGtNBEAgACABIAIQIhoPCyAAIAFzQQNxIQMCQAJAIAAgAUkEQCADDQIgAEEDcUUNAQNAIAJFDQQgACABLQAAOgAAIAFBAWohASACQQFrIQIgAEEBaiIAQQNxDQALDAELAkAgAw0AIARBA3EEQANAIAJFDQUgACACQQFrIgJqIgMgASACai0AADoAACADQQNxDQALCyACQQNNDQADQCAAIAJBBGsiAmogASACaigCADYCACACQQNLDQALCyACRQ0CA0AgACACQQFrIgJqIAEgAmotAAA6AAAgAg0ACwwCCyACQQNNDQADQCAAIAEoAgA2AgAgAUEEaiEBIABBBGohACACQQRrIgJBA0sNAAsLIAJFDQADQCAAIAEtAAA6AAAgAEEBaiEAIAFBAWohASACQQFrIgINAAsLCxsAIAAgAUHAhD1uIgAQJCABIABBwIQ9bGsQNAsbACAAIAFBkM4AbiIAECQgASAAQZDOAGxrEDULGQAgACABQeQAbiIAECQgASAAQeQAbGsQJAu9BAMDfAN/An4CfAJAIAC9QjSIp0H/D3EiBUHJB2tBP0kEQCAFIQQMAQsgBUHJB0kEQCAARAAAAAAAAPA/oA8LIAVBiQhJDQBEAAAAAAAAAAAgAL0iB0KAgICAgICAeFENARogBUH/D08EQCAARAAAAAAAAPA/oA8LIAdCAFMEQCMAQRBrIgREAAAAAAAAABA5AwggBCsDCEQAAAAAAAAAEKIPCyMAQRBrIgREAAAAAAAAAHA5AwggBCsDCEQAAAAAAAAAcKIPC0HoNSsDACAAokHwNSsDACIBoCICIAGhIgFBgDYrAwCiIAFB+DUrAwCiIACgoCIBIAGiIgAgAKIgAUGgNisDAKJBmDYrAwCgoiAAIAFBkDYrAwCiQYg2KwMAoKIgAr0iB6dBBHRB8A9xIgVB2DZqKwMAIAGgoKAhASAFQeA2aikDACAHQi2GfCEIIARFBEACfCAHQoCAgIAIg1AEQCAIQoCAgICAgICIP32/IgAgAaIgAKBEAAAAAAAAAH+iDAELIAhCgICAgICAgPA/fL8iAiABoiIBIAKgIgNEAAAAAAAA8D9jBHwjAEEQayIEIQYgBEKAgICAgICACDcDCCAGIAQrAwhEAAAAAAAAEACiOQMIRAAAAAAAAAAAIANEAAAAAAAA8D+gIgAgASACIAOhoCADRAAAAAAAAPA/IAChoKCgRAAAAAAAAPC/oCIAIABEAAAAAAAAAABhGwUgAwtEAAAAAAAAEACiCw8LIAi/IgAgAaIgAKALCwgAQcIKEFIAC3AAQeDUAEEZNgIAQeTUAEEANgIAEFVB5NQAQZDVACgCADYCAEGQ1QBB4NQANgIAQZTVAEEaNgIAQZjVAEEANgIAEFFBmNUAQZDVACgCADYCAEGQ1QBBlNUANgIAQbTWAEG81QA2AgBB7NUAQSo2AgALCwAgABA6GiAAEBkLMgECfyAAQczSADYCACAAKAIEQQxrIgEgASgCCEEBayICNgIIIAJBAEgEQCABEBkLIAALmgEAIABBAToANQJAIAAoAgQgAkcNACAAQQE6ADQCQCAAKAIQIgJFBEAgAEEBNgIkIAAgAzYCGCAAIAE2AhAgA0EBRw0CIAAoAjBBAUYNAQwCCyABIAJGBEAgACgCGCICQQJGBEAgACADNgIYIAMhAgsgACgCMEEBRw0CIAJBAUYNAQwCCyAAIAAoAiRBAWo2AiQLIABBAToANgsLTAEBfwJAIAFFDQAgAUHczgAQICIBRQ0AIAEoAgggACgCCEF/c3ENACAAKAIMIAEoAgxBABAeRQ0AIAAoAhAgASgCEEEAEB4hAgsgAgtdAQF/IAAoAhAiA0UEQCAAQQE2AiQgACACNgIYIAAgATYCEA8LAkAgASADRgRAIAAoAhhBAkcNASAAIAI2AhgPCyAAQQE6ADYgAEECNgIYIAAgACgCJEEBajYCJAsLYwECfyMAQRBrIgIkACABIAAoAgQiA0EBdWohASAAKAIAIQAgAkEIaiABIANBAXEEfyABKAIAIABqKAIABSAACxEAACACKAIMIgAQAiACKAIMIgEEQCABEAMLIAJBEGokACAAC0MBAX8jAEEQayIBJAAgAEIANwIAIABBADYCCCABQRBqJAAgACAALQALQQd2BH8gACgCCEH/////B3FBAWsFQQoLECsLPQEBfyMAQRBrIgIkACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2AhwgAEIANwMQIAAgACgCAEEgcjYCAEEAIAdBAkYNABogAiAEKAIEawshCiADQSBqJAAgCgt+AQF/IAAEQCAALAA3QQBIBEAgACgCLBAZCyAALAArQQBIBEAgACgCIBAZCyAAKAIcIgEEQCABEAMgAEEANgIcCyAAKAIUIgEEQCABEAMgAEEANgIUCyAAKAIMIgEEQCABEAMgAEEANgIMCyAAKAIEIgEEQCABEAMLIAAQGQsLJAECfyAAKAIEIgAQKkEBaiIBEC0iAgR/IAIgACABECIFQQALC/AeAw1/AnwBfSMAQUBqIgMkACADQaADEBwiAjYCHCADQp2DgICAtICAgH83AiAgAkGuHkGdAxAiQQA6AJ0DIANBHGoiAkGVEUGAESABLQA4GxAaGgJAIAICf0GAEiABKAJEIgJB2gBGDQAaIAJBjgJHBEAgAkG0AUcNAkHGEQwBC0HmEQsQGhoLIANBHGpBtyYQGhoCQAJAAkACQAJAIAEoAjxBAWsOAwABAgMLIANBKGohDSABKAJAIQwjAEGgAWsiBiQAIwBBEGsiBCQAIARBADYCDCAEQgA3AgQgBEE4EBwiAjYCBCAEIAJBOGoiBTYCDCACQQBBOBAmGiAEIAU2AggCfyAGQZQBaiIFQQA2AgggBUIANwIAIAVB1AAQHCICNgIEIAUgAjYCACAFIAJB1ABqIgg2AggCQAJAIAQoAggiByAEKAIEIglGBEAgAkEAQdQAECYaDAELIAcgCWsiCkEDdSIHQYCAgIACTw0BIAdBA3QhCwNAIAJBADYCCCACQgA3AgAgAiAKEBwiBzYCBCACIAc2AgAgAiAHIAtqIg42AgggByAJIAoQIhogAiAONgIEIAJBDGoiAiAIRw0ACwsgBSAINgIEIAUMAQsgAkEANgIIIAJCADcCAEHiCBBSAAshCSAEKAIEIgIEQCAEIAI2AgggAhAZC0EAIQIDQCAJKAIAIAJBDGxqIQcgAiACbCEIAkAgAkUEQEEAIQUDQCAFIAVsIAhqt58iD0QAAAAAAAAcQGUEQCAHKAIAIAVBA3RqIA8gD5qiRAAAAAAAADJAoxA2RAMkJUW5G5I/oiIPOQMAIA8gEKAhEAsgBUEBaiIFQQdHDQALDAELIAi3nyIPRAAAAAAAABxAZQRAIA8gD5qiRAAAAAAAADJAoxA2IQ8gBygCACAPRAMkJUW5G5I/oiIPOQMAIA8gEKAhEAtBASEFA0AgBSAFbCAIarefIg9EAAAAAAAAHEBlBEAgBygCACAFQQN0aiAPIA+aokQAAAAAAAAyQKMQNkQDJCVFuRuSP6IiDzkDACAPRAAAAAAAABBAoiAQoCEQCyAFQQFqIgVBB0cNAAsLIAJBAWoiAkEHRw0ACyAJKAIAIQlBACECA0AgCSACQQxsaigCACEHQQAhBUEAIQgDQCAHIAVBA3QiCmoiCyALKwMAIBCjOQMAIAcgCkEIcmoiCiAKKwMAIBCjOQMAIAVBAmohBSAIQQJqIghBBkcNAAsgByAFQQN0aiIFIAUrAwAgEKM5AwAgAkEBaiICQQdHDQALIARBEGokACAGQQA6AIgBIAZBADoAkwFBeiEFA0AgBSAMbCEHIAUgBUEfdSICcyACa0EMbCEIQXohAgNAAkAgBigClAEgCGooAgAgAiACQR91IgRzIARrQQN0aisDALYiEUMAAAAAXkUNACAGQRxqIgQgBxAvIAYgBEHNFhAlIgQoAgg2AjAgBiAEKQIANwMoIARCADcCACAEQQA2AgggBkFAayAGQShqQaMSEBoiBCgCCDYCACAGIAQpAgA3AzggBEIANwIAIARBADYCCCAGQRBqIgQgAiAMbBAvIAYgBkE4aiAGKAIQIAQgBi0AGyIEwEEASCIJGyAGKAIUIAQgCRsQGyIEKAIINgJQIAYgBCkCADcDSCAEQgA3AgAgBEEANgIIIAYgBkHIAGpBpxIQGiIEKAIINgJgIAYgBCkCADcDWCAEQgA3AgAgBEEANgIIIAZBBGoiBCAREC4gBiAGQdgAaiAGKAIEIAQgBi0ADyIEwEEASCIJGyAGKAIIIAQgCRsQGyIEKAIINgJwIAYgBCkCADcDaCAEQgA3AgAgBEEANgIIIAYgBkHoAGpBmBIQGiIEKAIINgKAASAGIAQpAgA3A3ggBEIANwIAIARBADYCCCAGQYgBaiAGKAJ4IAZB+ABqIAYtAIMBIgTAQQBIIgkbIAYoAnwgBCAJGxAbGiAGLACDAUEASARAIAYoAngQGQsgBiwAc0EASARAIAYoAmgQGQsgBiwAD0EASARAIAYoAgQQGQsgBiwAY0EASARAIAYoAlgQGQsgBiwAU0EASARAIAYoAkgQGQsgBiwAG0EASARAIAYoAhAQGQsgBiwAQ0EASARAIAYoAjgQGQsgBiwAM0EASARAIAYoAigQGQsgBiwAJ0EATg0AIAYoAhwQGQsgAkEBaiICQQdHDQALIAVBAWoiBUEHRw0ACyMAQRBrIgwkAEGZJhAqIQcCfyAGQYgBaiIFLQALQQd2BEAgBSgCBAwBCyAFLQALQf8AcQshCAJ/An8jAEEQayIJJAAgBkH4AGohAiAHIAhqIgRB7////wdNBEACQCAEQQtJBEAgAkIANwIAIAJBADYCCCACIAItAAtBgAFxIARB/wBxcjoACyACIAItAAtB/wBxOgALDAELIARBC08EfyAEQRBqQXBxIgogCkEBayIKIApBC0YbBUEKC0EBaiIKEBwhCyACIAIoAghBgICAgHhxIApB/////wdxcjYCCCACIAIoAghBgICAgHhyNgIIIAIgCzYCACACIAQ2AgQLIAlBEGokACACDAELECcACyIELQALQQd2BEAgBCgCAAwBCyAECyIEQZkmIAcQIyAEIAdqIgQCfyAFLQALQQd2BEAgBSgCAAwBCyAFCyAIECMgBCAIakEBEEAgDEEQaiQAIA0gAkHzKRAaIgIpAgA3AgAgDSACKAIINgIIIAJCADcCACACQQA2AgggBiwAgwFBAEgEQCAGKAJ4EBkLIAYsAJMBQQBIBEAgBigCiAEQGQsgBigClAEiBQRAIAYoApgBIgQgBSICRwRAA0AgBEEMayICKAIAIgcEQCAEQQhrIAc2AgAgBxAZCyACIgQgBUcNAAsgBigClAEhAgsgBiAFNgKYASACEBkLIAZBoAFqJAAgA0EcaiADKAIoIA0gAy0AMyICwEEASCIFGyADKAIsIAIgBRsQGxogAywAM0EATg0DIAMoAigQGQwDCyADQRxqQcwhEBoaDAILIANBHGpBrywQGhoMAQsgA0EcakGYLBAaGgsCQAJAIAEoAjAgAS0ANyICIALAIgZBAEgbIgRBAWoiBUHw////B0kEQAJAAkAgBUELTwRAIAVBD3JBAWoiBxAcIQIgAyAFNgIsIAMgAjYCKCADIAdBgICAgHhyNgIwDAELIANBADYCMCADQgA3AyggAyAFOgAzIANBKGohAiAERQ0BCyACIAFBLGoiBSgCACAFIAZBAEgbIAQQMgsgAiAEakEKOwAAIANBHGogAygCKCADQShqIAMtADMiAsBBAEgiBRsgAygCLCACIAUbEBsaIAMsADNBAEgEQCADKAIoEBkLIAEoAiQgAS0AKyICIALAIgZBAEgbIgRBAmoiBUHw////B08NAQJAAkAgBUELTwRAIAVBD3JBAWoiBxAcIQIgAyAFNgIsIAMgAjYCKCADIAdBgICAgHhyNgIwDAELIANBADYCMCADQgA3AyggAyAFOgAzIANBKGohAiAERQ0BCyACIAFBIGoiBSgCACAFIAZBAEgbIAQQMgsgAiAEaiICQQA6AAIgAkH9FDsAACADQRxqIAMoAiggA0EoaiADLQAzIgLAQQBIIgUbIAMoAiwgAiAFGxAbGiADLAAzQQBIBEAgAygCKBAZC0HA0wAoAgAiBBAqIgJB8P///wdPDQICQAJAIAJBC08EQCACQQ9yQQFqIgYQHCEFIAMgBkGAgICAeHI2AhggAyAFNgIQIAMgAjYCFAwBCyADIAI6ABsgA0EQaiEFIAJFDQELIAUgBCACEDILIAIgBWpBADoAACADQShqIAFBsZYCIANBEGoQUyADKAIsIQIgA0EANgIsIAMoAighBQJAIAEoAhQiBEUEQCABIAI2AhQgASAFNgIQDAELIAQQAyADKAIsIQQgASACNgIUIAEgBTYCECAERQ0AIAQQAyADQQA2AiwLIAMsABtBAEgEQCADKAIQEBkLAkAgAywAJ0EATgRAIAMgAygCJDYCCCADIAMpAhw3AwAMAQsgAygCHCEGIAMoAiAhBSMAQRBrIgQkAAJAAkACQCAFQQtJBEAgAyECIAMgAy0AC0GAAXEgBUH/AHFyOgALIAMgAy0AC0H/AHE6AAsMAQsgBUHv////B0sNASAEQQhqIAMgBUELTwR/IAVBEGpBcHEiAiACQQFrIgIgAkELRhsFQQoLQQFqEDAgBCgCDBogAyAEKAIIIgI2AgAgAyADKAIIQYCAgIB4cSAEKAIMQf////8HcXI2AgggAyADKAIIQYCAgIB4cjYCCCADIAU2AgQLIAIgBiAFQQFqECMgBEEQaiQADAELECcACwsgA0EoaiABQbCWAiADEFMgAygCLCECIANBADYCLCADKAIoIQUCQCABKAIMIgRFBEAgASACNgIMIAEgBTYCCAwBCyAEEAMgAygCLCEEIAEgAjYCDCABIAU2AgggBEUNACAEEAMgA0EANgIsCyADLAALQQBIBEAgAygCABAZCyADQQA2AihBhNUALQAAQQFxRQRAQQFBqC9BABAFIQJBhNUAQQE6AABBgNUAIAI2AgALAn9BgNUAKAIAIAEoAgRB6QkgA0EoakEAEAQiEEQAAAAAAADwQWMgEEQAAAAAAAAAAGZxBEAgEKsMAQtBAAshAiADKAIoIgUEQCAFEAELIAEoAhwiBQRAIAUQAwsgASACNgIcIAFB1NUANgIYIAIQAiADIAI2AiggASgCFCICEAIgAyACNgIwIANBADYCPEGM1QAtAABBAXFFBEBBA0GsL0EAEAUhAkGM1QBBAToAAEGI1QAgAjYCAAtBiNUAKAIAIAEoAgRB8AggA0E8aiADQShqEAQaIAMoAjwiAgRAIAIQAQsgASgCHCICEAIgAyACNgIoIAEoAgwiAhACIAMgAjYCMCADQQA2AjxBjNUALQAAQQFxRQRAQQNBrC9BABAFIQJBjNUAQQE6AABBiNUAIAI2AgALQYjVACgCACABKAIEQfAIIANBPGogA0EoahAEGiADKAI8IgIEQCACEAELIAEoAhwiAhACIAMgAjYCKCADQQA2AjxB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACABKAIEQc8JIANBPGogA0EoahAEGiADKAI8IgIEQCACEAELIAAgASgCHCIBNgIEIABB1NUANgIAIAEQAiADLAAnQQBIBEAgAygCHBAZCyADQUBrJAAPCxA3AAsQNwALEDcAC9gCAQJ/IwBBEGsiASQAIAAoAhQiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQf0IIAFBBGogAUEIahAEGiABKAIEIgIEQCACEAELIAAoAgwiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQf0IIAFBBGogAUEIahAEGiABKAIEIgIEQCACEAELIAAoAhwiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQdsJIAFBBGogAUEIahAEGiABKAIEIgAEQCAAEAELIAFBEGokAAs1AQF/IAEgACgCBCICQQF1aiEBIAAoAgAhACABIAJBAXEEfyABKAIAIABqKAIABSAACxEDAAsvAAJ/IAAsACtBAEgEQCAAQQA2AiQgACgCIAwBCyAAQQA6ACsgAEEgagtBADoAAAsFAEHoLAs9AQF/IAEgACgCBCIGQQF1aiEBIAAoAgAhACABIAIgAyAEIAUgBkEBcQR/IAEoAgAgAGooAgAFIAALEQ0AC7wJAgR/AXwjAEEQayIIJAAgASEJIAAoAkQhBiMAQYACayIFJAACQAJAIAZBjgJGDQAgBkHaAEYNACADIQEgBCEDDAELIAQhAQsgBUHEAGoiBiAJECEgBSAGQdsSECUiBigCCDYCWCAFIAYpAgA3A1AgBkIANwIAIAZBADYCCCAFIAVB0ABqQfEUEBoiBigCCDYCaCAFIAYpAgA3A2AgBkIANwIAIAZBADYCCCAFQThqIgYgAhAhIAUgBUHgAGogBSgCOCAGIAUtAEMiBsBBAEgiBxsgBSgCPCAGIAcbEBsiBigCCDYCeCAFIAYpAgA3A3AgBkIANwIAIAZBADYCCCAFIAVB8ABqQbYSEBoiBigCCDYCiAEgBSAGKQIANwOAASAGQgA3AgAgBkEANgIIIAVBLGoiBiABIAmgECEgBSAFQYABaiAFKAIsIAYgBS0ANyIGwEEASCIHGyAFKAIwIAYgBxsQGyIGKAIINgKYASAFIAYpAgA3A5ABIAZCADcCACAGQQA2AgggBSAFQZABakHxFBAaIgYoAgg2AqgBIAUgBikCADcDoAEgBkIANwIAIAZBADYCCCAFQSBqIgYgAyACoBAhIAUgBUGgAWogBSgCICAGIAUtACsiBsBBAEgiBxsgBSgCJCAGIAcbEBsiBigCCDYCuAEgBSAGKQIANwOwASAGQgA3AgAgBkEANgIIIAUgBUGwAWpByhMQGiIGKAIINgLIASAFIAYpAgA3A8ABIAZCADcCACAGQQA2AgggBUEUaiIGIAEQISAFIAVBwAFqIAUoAhQgBiAFLQAfIgbAQQBIIgcbIAUoAhggBiAHGxAbIgYoAgg2AtgBIAUgBikCADcD0AEgBkIANwIAIAZBADYCCCAFIAVB0AFqQagTEBoiBigCCDYC6AEgBSAGKQIANwPgASAGQgA3AgAgBkEANgIIIAVBCGoiBiADECEgBSAFQeABaiAFKAIIIAYgBS0AEyIGwEEASCIHGyAFKAIMIAYgBxsQGyIGKAIINgL4ASAFIAYpAgA3A/ABIAZCADcCACAGQQA2AgggCCAFQfABakGEHRAaIgYpAgA3AgQgCCAGKAIINgIMIAZCADcCACAGQQA2AgggBSwA+wFBAEgEQCAFKALwARAZCyAFLAATQQBIBEAgBSgCCBAZCyAFLADrAUEASARAIAUoAuABEBkLIAUsANsBQQBIBEAgBSgC0AEQGQsgBSwAH0EASARAIAUoAhQQGQsgBSwAywFBAEgEQCAFKALAARAZCyAFLAC7AUEASARAIAUoArABEBkLIAUsACtBAEgEQCAFKAIgEBkLIAUsAKsBQQBIBEAgBSgCoAEQGQsgBSwAmwFBAEgEQCAFKAKQARAZCyAFLAA3QQBIBEAgBSgCLBAZCyAFLACLAUEASARAIAUoAoABEBkLIAUsAHtBAEgEQCAFKAJwEBkLIAUsAENBAEgEQCAFKAI4EBkLIAUsAGtBAEgEQCAFKAJgEBkLIAUsAFtBAEgEQCAFKAJQEBkLIAUsAE9BAEgEQCAFKAJEEBkLIAVBgAJqJAAgACwAK0EASARAIAAoAiAQGQsgACAIKQIENwIgIAAgCCgCDDYCKCAIQRBqJAALPwEBfyABIAAoAgQiB0EBdWohASAAKAIAIQAgASACIAMgBCAFIAYgB0EBcQR/IAEoAgAgAGooAgAFIAALEQ4AC88bAgd/AXwjAEFAaiIJJAAgCSAFOQMgIAkgBDkDGCAJIAM5AxAgCSACOQMIIAkgATkDACMAQRBrIgYkACAGIAk2AgxByNMAQf4rIAlBABBNGiAGQRBqJAAjAEGABGsiBiQAIAlBNGoiC0EAOgAAIAtBADoACwJAIAFEAAAAAAAAAABkRQ0AIAZBADoA8AMgBkEAOgD7AyAGQQA6AOQDIAZBADoA7wMgBkKAgICAhICAgMAANwPYAyAGQoCAgICEgICAQDcD0AMgBkKAgICAjICAgMAANwPIAyAGQoCAgICMgICAQDcDwAMgBkKAgICEhICAwMAANwO4AyAGQoCAgISEgIDAQDcDsAMgBkKAgICEjICAwMAANwOoAyAGQoCAgISMgIDAQDcDoAMgBkKAgICGDDcDmAMgBkKAgICGBDcDkAMgBkKAgICAgICA4MAANwOIAyAGQoCAgICAgIDgQDcDgAMgBkKAgICIjICA0EA3A/gCIAZCgICAiIyAgNDAADcD8AIgBkKAgICIhICA0MAANwPoAiAGQoCAgIiEgIDQQDcD4AIgBkKAgICFjICAgEE3A9gCIAZCgICAhYyAgIDBADcD0AIgBkKAgICFhICAgMEANwPIAiAGQoCAgIWEgICAQTcDwAIgBkKAgICJBDcDuAIgBkKAgICJDDcDsAIgBkKAgICAgICAkMEANwOoAiAGQoCAgICAgICQQTcDoAJEAAAAAAAAAEAgBKMhBCABRJqZmZmZmem/okQAAAAAAADwP6AhDQNAIAZBsAFqIgggBxAvIAYgCEHECxAlIggoAgg2AsgBIAYgCCkCADcDwAEgCEIANwIAIAhBADYCCCAGIAZBwAFqQfQWEBoiCCgCCDYC2AEgBiAIKQIANwPQASAIQgA3AgAgCEEANgIIIAZBoAFqIgggBkGgAmogB0EDdGoiCioCABAuIAYgBkHQAWogBigCoAEgCCAGLQCrASIIwEEASCIMGyAGKAKkASAIIAwbEBsiCCgCCDYC6AEgBiAIKQIANwPgASAIQgA3AgAgCEEANgIIIAYgBkHgAWpB+RwQGiIIKAIINgL4ASAGIAgpAgA3A/ABIAhCADcCACAIQQA2AgggBkGQAWoiCCAKKgIEEC4gBiAGQfABaiAGKAKQASAIIAYtAJsBIgjAQQBIIgobIAYoApQBIAggChsQGyIIKAIINgKIAiAGIAgpAgA3A4ACIAhCADcCACAIQQA2AgggBiAGQYACakGXEhAaIggoAgg2ApgCIAYgCCkCADcDkAIgCEIANwIAIAhBADYCCCAGQeQDaiAGKAKQAiAGQZACaiAGLQCbAiIIwEEASCIKGyAGKAKUAiAIIAobEBsaIAYsAJsCQQBIBEAgBigCkAIQGQsgBiwAiwJBAEgEQCAGKAKAAhAZCyAGLACbAUEASARAIAYoApABEBkLIAYsAPsBQQBIBEAgBigC8AEQGQsgBiwA6wFBAEgEQCAGKALgARAZCyAGLACrAUEASARAIAYoAqABEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgBiwAywFBAEgEQCAGKALAARAZCyAGLAC7AUEASARAIAYoArABEBkLIAZB0AFqIgggBxAvIAYgCEGmCxAlIggoAgg2AugBIAYgCCkCADcD4AEgCEIANwIAIAhBADYCCCAGIAZB4AFqQfwcEBoiCCgCCDYC+AEgBiAIKQIANwPwASAIQgA3AgAgCEEANgIIIAZBwAFqIghDAAAAQEMAAEBAQwAAgD8gB0ETSxsgB0EMa0EISRsQLiAGIAZB8AFqIAYoAsABIAggBi0AywEiCMBBAEgiChsgBigCxAEgCCAKGxAbIggoAgg2AogCIAYgCCkCADcDgAIgCEIANwIAIAhBADYCCCAGIAZBgAJqQZcXEBoiCCgCCDYCmAIgBiAIKQIANwOQAiAIQgA3AgAgCEEANgIIIAZB8ANqIAYoApACIAZBkAJqIAYtAJsCIgjAQQBIIgobIAYoApQCIAggChsQGxogBiwAmwJBAEgEQCAGKAKQAhAZCyAGLACLAkEASARAIAYoAoACEBkLIAYsAMsBQQBIBEAgBigCwAEQGQsgBiwA+wFBAEgEQCAGKALwARAZCyAGLADrAUEASARAIAYoAuABEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgB0EBaiIHQRhHDQALIAZBNGoiByAEECEgBiAHQdoWECUiBygCCDYCSCAGIAcpAgA3A0AgB0IANwIAIAdBADYCCCAGIAZBQGtBpRIQGiIHKAIINgJYIAYgBykCADcDUCAHQgA3AgAgB0EANgIIIAZBKGoiB0QAAAAAAAAAQCAFoxAhIAYgBkHQAGogBigCKCAHIAYtADMiB8BBAEgiCBsgBigCLCAHIAgbEBsiBygCCDYCaCAGIAcpAgA3A2AgB0IANwIAIAdBADYCCCAGIAZB4ABqQdIdEBoiBygCCDYCeCAGIAcpAgA3A3AgB0IANwIAIAdBADYCCCAGIAZB8ABqIAYoAuQDIAZB5ANqIAYtAO8DIgfAQQBIIggbIAYoAugDIAcgCBsQGyIHKAIINgKIASAGIAcpAgA3A4ABIAdCADcCACAHQQA2AgggBiAGQYABakH6HRAaIgcoAgg2ApgBIAYgBykCADcDkAEgB0IANwIAIAdBADYCCCAGIAZBkAFqIAYoAvADIAZB8ANqIAYtAPsDIgfAQQBIIggbIAYoAvQDIAcgCBsQGyIHKAIINgKoASAGIAcpAgA3A6ABIAdCADcCACAHQQA2AgggBiAGQaABakGYGxAaIgcoAgg2ArgBIAYgBykCADcDsAEgB0IANwIAIAdBADYCCCAGQRxqIgcgDRAhIAYgBkGwAWogBigCHCAHIAYtACciB8BBAEgiCBsgBigCICAHIAgbEBsiBygCCDYCyAEgBiAHKQIANwPAASAHQgA3AgAgB0EANgIIIAYgBkHAAWpBlxUQGiIHKAIINgLYASAGIAcpAgA3A9ABIAdCADcCACAHQQA2AgggBkEQaiIHIAFEMzMzMzMz47+iRAAAAAAAAPA/oBAhIAYgBkHQAWogBigCECAHIAYtABsiB8BBAEgiCBsgBigCFCAHIAgbEBsiBygCCDYC6AEgBiAHKQIANwPgASAHQgA3AgAgB0EANgIIIAYgBkHgAWpBmhcQGiIHKAIINgL4ASAGIAcpAgA3A/ABIAdCADcCACAHQQA2AgggBkEEaiIHIAEQISAGIAZB8AFqIAYoAgQgByAGLQAPIgfAQQBIIggbIAYoAgggByAIGxAbIgcoAgg2AogCIAYgBykCADcDgAIgB0IANwIAIAdBADYCCCAGIAZBgAJqQcsdEBoiBygCCDYCmAIgBiAHKQIANwOQAiAHQgA3AgAgB0EANgIIIAsgBigCkAIgBkGQAmogBi0AmwIiB8BBAEgiCBsgBigClAIgByAIGxAbGiAGLACbAkEASARAIAYoApACEBkLIAYsAIsCQQBIBEAgBigCgAIQGQsgBiwAD0EASARAIAYoAgQQGQsgBiwA+wFBAEgEQCAGKALwARAZCyAGLADrAUEASARAIAYoAuABEBkLIAYsABtBAEgEQCAGKAIQEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgBiwAywFBAEgEQCAGKALAARAZCyAGLAAnQQBIBEAgBigCHBAZCyAGLAC7AUEASARAIAYoArABEBkLIAYsAKsBQQBIBEAgBigCoAEQGQsgBiwAmwFBAEgEQCAGKAKQARAZCyAGLACLAUEASARAIAYoAoABEBkLIAYsAHtBAEgEQCAGKAJwEBkLIAYsAGtBAEgEQCAGKAJgEBkLIAYsADNBAEgEQCAGKAIoEBkLIAYsAFtBAEgEQCAGKAJQEBkLIAYsAEtBAEgEQCAGKAJAEBkLIAYsAD9BAEgEQCAGKAI0EBkLIAYsAO8DQQBIBEAgBigC5AMQGQsgBiwA+wNBAE4NACAGKALwAxAZCwJAIANEAAAAAAAAAABkRQ0AIAZB5ANqIgcgA0TNzMzMzMzcP6JEmpmZmZmZuT+gECEgBiAHQcEZECUiBygCCDYC+AMgBiAHKQIANwPwAyAHQgA3AgAgB0EANgIIIAYgBkHwA2pB6ykQGiIHKAIINgKoAiAGIAcpAgA3A6ACIAdCADcCACAHQQA2AgggCyAGKAKgAiAGQaACaiAGLQCrAiIHwEEASCIIGyAGKAKkAiAHIAgbEBsaIAYsAKsCQQBIBEAgBigCoAIQGQsgBiwA+wNBAEgEQCAGKALwAxAZCyAGLADvA0EATg0AIAYoAuQDEBkLAkAgAkQAAAAAAAAAAGRFDQAgBkHkA2oiByACRLgehetRuL4/ohAhIAYgB0GBFRAlIgcoAgg2AvgDIAYgBykCADcD8AMgB0IANwIAIAdBADYCCCAGIAZB8ANqQdssEBoiBygCCDYCqAIgBiAHKQIANwOgAiAHQgA3AgAgB0EANgIIIAsgBigCoAIgBkGgAmogBi0AqwIiB8BBAEgiCxsgBigCpAIgByALGxAbGiAGLACrAkEASARAIAYoAqACEBkLIAYsAPsDQQBIBEAgBigC8AMQGQsgBiwA7wNBAE4NACAGKALkAxAZCyAGQYAEaiQAIAAsADdBAEgEQCAAKAIsEBkLIAAgCSkCNDcCLCAAIAkoAjw2AjQgCUFAayQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgJEIAJBEGokAAs3AQF/IwBBEGsiAiQAIAIgASgCRDYCCCAAQZzQACACQQhqEAc2AgQgAEHU1QA2AgAgAkEQaiQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgJAIAJBEGokAAs3AQF/IwBBEGsiAiQAIAIgASgCQDYCCCAAQZzQACACQQhqEAc2AgQgAEHU1QA2AgAgAkEQaiQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgI8IAJBEGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(Ve=ce,ce=I.locateFile?I.locateFile(Ve,f):f+Ve);var Ni=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function Co($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){RA[this.ptr+4>>2]=j},this.get_type=function(){return RA[this.ptr+4>>2]},this.set_destructor=function(j){RA[this.ptr+8>>2]=j},this.get_destructor=function(){return RA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,lA[this.ptr+12|0]=j},this.get_caught=function(){return lA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,lA[this.ptr+13|0]=j},this.get_rethrown=function(){return lA[this.ptr+13|0]!=0},this.init=function(j,vA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(vA)},this.set_adjusted_ptr=function(j){RA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return RA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(ba(this.get_type()))return RA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var to,so,ks,Gi=$=>{for(var j="",vA=$;tA[vA];)j+=to[tA[vA++]];return j},As={},Lo={},$i={},zt=$=>{throw new so($)},Ao=$=>{throw new ks($)},Ri=($,j,vA)=>{function jA(Pe){var rt=vA(Pe);rt.length!==$.length&&Ao("Mismatched type converter count");for(var ht=0;ht<$.length;++ht)Es($[ht],rt[ht])}$.forEach(function(Pe){$i[Pe]=j});var oe=new Array(j.length),ye=[],He=0;j.forEach((Pe,rt)=>{Lo.hasOwnProperty(Pe)?oe[rt]=Lo[Pe]:(ye.push(Pe),As.hasOwnProperty(Pe)||(As[Pe]=[]),As[Pe].push(()=>{oe[rt]=Lo[Pe],++He===ye.length&&jA(oe)}))}),ye.length===0&&jA(oe)};function Es($,j,vA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(jA,oe,ye={}){var He=oe.name;if(jA||zt(`type "${He}" must have a positive integer typeid pointer`),Lo.hasOwnProperty(jA)){if(ye.ignoreDuplicateRegistrations)return;zt(`Cannot register type '${He}' twice`)}if(Lo[jA]=oe,delete $i[jA],As.hasOwnProperty(jA)){var Pe=As[jA];delete As[jA],Pe.forEach(rt=>rt())}}($,j,vA)}var VA,Ee=$=>{zt($.$$.ptrType.registeredClass.name+" instance already deleted")},Je=!1,Ut=$=>{},ot=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},ut=($,j,vA)=>{if(j===vA)return $;if(vA.baseClass===void 0)return null;var jA=ut($,j,vA.baseClass);return jA===null?null:vA.downcast(jA)},$t={},Zt=()=>Object.keys(pt).length,Ge=()=>{var $=[];for(var j in pt)pt.hasOwnProperty(j)&&$.push(pt[j]);return $},Xe=[],se=()=>{for(;Xe.length;){var $=Xe.pop();$.$$.deleteScheduled=!1,$.delete()}},ve=$=>{VA=$,Xe.length&&VA&&VA(se)},pt={},mo=($,j)=>(j=((vA,jA)=>{for(jA===void 0&&zt("ptr should not be undefined");vA.baseClass;)jA=vA.upcast(jA),vA=vA.baseClass;return jA})($,j),pt[j]),No=($,j)=>(j.ptrType&&j.ptr||Ao("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&Ao("Both smartPtrType and smartPtr must be specified"),j.count={value:1},Go(Object.create($,{$$:{value:j}})));function no($){var j=this.getPointee($);if(!j)return this.destructor($),null;var vA=mo(this.registeredClass,j);if(vA!==void 0){if(vA.$$.count.value===0)return vA.$$.ptr=j,vA.$$.smartPtr=$,vA.clone();var jA=vA.clone();return this.destructor($),jA}function oe(){return this.isSmartPointer?No(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):No(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var ye,He=this.registeredClass.getActualType(j),Pe=$t[He];if(!Pe)return oe.call(this);ye=this.isConst?Pe.constPointerType:Pe.pointerType;var rt=ut(j,this.registeredClass,ye.registeredClass);return rt===null?oe.call(this):this.isSmartPointer?No(ye.registeredClass.instancePrototype,{ptrType:ye,ptr:rt,smartPtrType:this,smartPtr:$}):No(ye.registeredClass.instancePrototype,{ptrType:ye,ptr:rt})}var Go=$=>typeof FinalizationRegistry>"u"?(Go=j=>j,$):(Je=new FinalizationRegistry(j=>{ot(j.$$)}),Ut=j=>Je.unregister(j),(Go=j=>{var vA=j.$$;if(vA.smartPtr){var jA={$$:vA};Je.register(j,jA,j)}return j})($));function An(){}var rn=($,j)=>Object.defineProperty(j,"name",{value:$}),ds=($,j,vA)=>{if($[j].overloadTable===void 0){var jA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||zt(`Function '${vA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[jA.argCount]=jA}};function an($,j,vA,jA,oe,ye,He,Pe){this.name=$,this.constructor=j,this.instancePrototype=vA,this.rawDestructor=jA,this.baseClass=oe,this.getActualType=ye,this.upcast=He,this.downcast=Pe,this.pureVirtualFunctions=[]}var So=($,j,vA)=>{for(;j!==vA;)j.upcast||zt(`Expected null or instance of ${vA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`);var vA=j.$$.ptrType.registeredClass;return So(j.$$.ptr,vA,this.registeredClass)}function qn($,j){var vA;if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),this.isSmartPointer?(vA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,vA),vA):0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&zt(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var jA=j.$$.ptrType.registeredClass;if(vA=So(j.$$.ptr,jA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&zt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?vA=j.$$.smartPtr:zt(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:vA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)vA=j.$$.smartPtr;else{var oe=j.clone();vA=this.rawShare(vA,cn.toHandle(()=>oe.delete())),$!==null&&$.push(this.rawDestructor,vA)}break;default:zt("Unsupporting sharing policy")}return vA}function mr($,j){if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&zt(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var vA=j.$$.ptrType.registeredClass;return So(j.$$.ptr,vA,this.registeredClass)}function Cs($){return this.fromWireType(RA[$>>2])}function Zr($,j,vA,jA,oe,ye,He,Pe,rt,ht,_t){this.name=$,this.registeredClass=j,this.isReference=vA,this.isConst=jA,this.isSmartPointer=oe,this.pointeeType=ye,this.sharingPolicy=He,this.rawGetPointee=Pe,this.rawConstructor=rt,this.rawShare=ht,this.rawDestructor=_t,oe||j.baseClass!==void 0?this.toWireType=qn:jA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=mr,this.destructorFunction=null)}var Yi,Rs,rr=[],en=$=>{var j=rr[$];return j||($>=rr.length&&(rr.length=$+1),rr[$]=j=Yi.get($)),j},wn=($,j,vA)=>$.includes("j")?((jA,oe,ye)=>{var He=I["dynCall_"+jA];return ye&&ye.length?He.apply(null,[oe].concat(ye)):He.call(null,oe)})($,j,vA):en(j).apply(null,vA),jt=($,j)=>{var vA,jA,oe,ye=($=Gi($)).includes("j")?(vA=$,jA=j,oe=[],function(){return oe.length=0,Object.assign(oe,arguments),wn(vA,jA,oe)}):en(j);return typeof ye!="function"&&zt(`unknown function pointer with signature ${$}: ${j}`),ye},yg=$=>{var j=Ea($),vA=Gi(j);return yn(j),vA},Pn=($,j)=>{var vA=[],jA={};throw j.forEach(function oe(ye){jA[ye]||Lo[ye]||($i[ye]?$i[ye].forEach(oe):(vA.push(ye),jA[ye]=!0))}),new Rs(`${$}: `+vA.map(yg).join([", "]))},bn=($,j)=>{for(var vA=[],jA=0;jA<$;jA++)vA.push(RA[j+4*jA>>2]);return vA},Js=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function fr($,j,vA,jA,oe,ye){var He=j.length;He<2&&zt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Pe=j[1]!==null&&vA!==null,rt=!1,ht=1;ht($ instanceof Object||zt(`${vA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||zt(`${vA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||zt(`cannot call emscripten binding method ${vA} on deleted object`),So($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function yr(){this.allocated=[void 0],this.freelist=[]}var fo=new yr,gn=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},Ml=()=>{for(var $=0,j=fo.reserved;j($||zt("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function Dr($){return this.fromWireType(gA[$>>2])}var Us,Jc,fs,as=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},wu=($,j)=>{switch(j){case 4:return function(vA){return this.fromWireType(HA[vA>>2])};case 8:return function(vA){return this.fromWireType(ZA[vA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Wa=($,j,vA)=>{switch(j){case 1:return vA?jA=>lA[jA|0]:jA=>tA[jA|0];case 2:return vA?jA=>BA[jA>>1]:jA=>IA[jA>>1];case 4:return vA?jA=>gA[jA>>2]:jA=>RA[jA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},hs=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,sg=($,j,vA)=>{for(var jA=j+vA,oe=j;$[oe]&&!(oe>=jA);)++oe;if(oe-j>16&&$.buffer&&hs)return hs.decode($.subarray(j,oe));for(var ye="";j>10,56320|1023&ht)}}else ye+=String.fromCharCode((31&He)<<6|Pe)}else ye+=String.fromCharCode(He)}return ye},qI=($,j)=>$?sg(tA,$,j):"",es=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,eo=($,j)=>{for(var vA=$,jA=vA>>1,oe=jA+j/2;!(jA>=oe)&&IA[jA];)++jA;if((vA=jA<<1)-$>32&&es)return es.decode(tA.subarray($,vA));for(var ye="",He=0;!(He>=j/2);++He){var Pe=BA[$+2*He>>1];if(Pe==0)break;ye+=String.fromCharCode(Pe)}return ye},pc=($,j,vA)=>{if(vA===void 0&&(vA=2147483647),vA<2)return 0;for(var jA=j,oe=(vA-=2)<2*$.length?vA/2:$.length,ye=0;ye>1]=He,j+=2}return BA[j>>1]=0,j-jA},ng=$=>2*$.length,Dg=($,j)=>{for(var vA=0,jA="";!(vA>=j/4);){var oe=gA[$+4*vA>>2];if(oe==0)break;if(++vA,oe>=65536){var ye=oe-65536;jA+=String.fromCharCode(55296|ye>>10,56320|1023&ye)}else jA+=String.fromCharCode(oe)}return jA},ua=($,j,vA)=>{if(vA===void 0&&(vA=2147483647),vA<4)return 0;for(var jA=j,oe=jA+vA-4,ye=0;ye<$.length;++ye){var He=$.charCodeAt(ye);if(He>=55296&&He<=57343&&(He=65536+((1023&He)<<10)|1023&$.charCodeAt(++ye)),gA[j>>2]=He,(j+=4)+4>oe)break}return gA[j>>2]=0,j-jA},bo=$=>{for(var j=0,vA=0;vA<$.length;++vA){var jA=$.charCodeAt(vA);jA>=55296&&jA<=57343&&++vA,j+=4}return j},Xr=($,j)=>{var vA=Lo[$];return vA===void 0&&zt(j+" has unknown type "+yg($)),vA},To=($,j,vA)=>{var jA=[],oe=$.toWireType(jA,vA);return jA.length&&(RA[j>>2]=cn.toHandle(jA)),oe},Hc={},Kn=[],Hs=Reflect.construct,Sg=[null,[],[]],mc=($,j)=>{var vA=Sg[$];j===0||j===10?(($===1?N:L)(sg(vA,0)),vA.length=0):vA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);to=$})(),so=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},ks=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(An.prototype,{isAliasOf($){if(!(this instanceof An)||!($ instanceof An))return!1;var j=this.$$.ptrType.registeredClass,vA=this.$$.ptr;$.$$=$.$$;for(var jA=$.$$.ptrType.registeredClass,oe=$.$$.ptr;j.baseClass;)vA=j.upcast(vA),j=j.baseClass;for(;jA.baseClass;)oe=jA.upcast(oe),jA=jA.baseClass;return j===jA&&vA===oe},clone(){if(this.$$.ptr||Ee(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=Go(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&zt("Object already scheduled for deletion"),Ut(this),ot(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&zt("Object already scheduled for deletion"),Xe.push(this),Xe.length===1&&VA&&VA(se),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Zt,I.getLiveInheritedInstances=Ge,I.flushPendingDeletes=se,I.setDelayFunction=ve,Object.assign(Zr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:Cs,deleteObject($){$!==null&&$.delete()},fromWireType:no}),Rs=I.UnboundTypeError=(Us=Error,(fs=rn(Jc="UnboundTypeError",function($){this.name=Jc,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` +`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Us.prototype),fs.prototype.constructor=fs,fs.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},fs),Object.assign(yr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=Ml;var fn,Ga={w:($,j,vA)=>{throw new Co($).init(j,vA),$},q:($,j,vA,jA,oe)=>{},u:($,j,vA,jA)=>{Es($,{name:j=Gi(j),fromWireType:function(oe){return!!oe},toWireType:function(oe,ye){return ye?vA:jA},argPackAdvance:8,readValueFromPointer:function(oe){return this.fromWireType(tA[oe])},destructorFunction:null})},y:($,j,vA,jA,oe,ye,He,Pe,rt,ht,_t,Vt,ui)=>{_t=Gi(_t),ye=jt(oe,ye),Pe&&(Pe=jt(He,Pe)),ht&&(ht=jt(rt,ht)),ui=jt(Vt,ui);var It=(Yt=>{if(Yt===void 0)return"_unknown";var qi=(Yt=Yt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return qi>=48&&qi<=57?`_${Yt}`:Yt})(_t);((Yt,qi,Wi)=>{I.hasOwnProperty(Yt)?(zt(`Cannot register public name '${Yt}' twice`),ds(I,Yt,Yt),I.hasOwnProperty(Wi)&&zt(`Cannot register multiple overloads of a function with the same number of arguments (${Wi})!`),I[Yt].overloadTable[Wi]=qi):I[Yt]=qi})(It,function(){Pn(`Cannot construct ${_t} due to unbound types`,[jA])}),Ri([$,j,vA],jA?[jA]:[],function(Yt){var qi,Wi;Yt=Yt[0],Wi=jA?(qi=Yt.registeredClass).instancePrototype:An.prototype;var qs=rn(_t,function(){if(Object.getPrototypeOf(this)!==vi)throw new so("Use 'new' to construct "+_t);if(zo.constructor_body===void 0)throw new so(_t+" has no accessible constructor");var Yn=zo.constructor_body[arguments.length];if(Yn===void 0)throw new so(`Tried to invoke ctor of ${_t} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(zo.constructor_body).toString()}) parameters instead!`);return Yn.apply(this,arguments)}),vi=Object.create(Wi,{constructor:{value:qs}});qs.prototype=vi;var zo=new an(_t,qs,vi,ui,qi,ye,Pe,ht);zo.baseClass&&(zo.baseClass.__derivedClasses===void 0&&(zo.baseClass.__derivedClasses=[]),zo.baseClass.__derivedClasses.push(zo));var Mg=new Zr(_t,zo,!0,!1,!1),ar=new Zr(_t+"*",zo,!1,!1,!1),Sr=new Zr(_t+" const*",zo,!1,!0,!1);return $t[$]={pointerType:ar,constPointerType:Sr},((Yn,vl,Ks)=>{I.hasOwnProperty(Yn)||Ao("Replacing nonexistant public symbol"),I[Yn].overloadTable!==void 0&&Ks!==void 0?I[Yn].overloadTable[Ks]=vl:(I[Yn]=vl,I[Yn].argCount=Ks)})(It,qs),[Mg,ar,Sr]})},x:($,j,vA,jA,oe,ye)=>{var He=bn(j,vA);oe=jt(jA,oe),Ri([],[$],function(Pe){var rt=`constructor ${(Pe=Pe[0]).name}`;if(Pe.registeredClass.constructor_body===void 0&&(Pe.registeredClass.constructor_body=[]),Pe.registeredClass.constructor_body[j-1]!==void 0)throw new so(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${Pe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Pe.registeredClass.constructor_body[j-1]=()=>{Pn(`Cannot construct ${Pe.name} due to unbound types`,He)},Ri([],He,ht=>(ht.splice(1,0,null),Pe.registeredClass.constructor_body[j-1]=fr(rt,ht,null,oe,ye),[])),[]})},i:($,j,vA,jA,oe,ye,He,Pe,rt)=>{var ht=bn(vA,jA);j=(_t=>{const Vt=(_t=_t.trim()).indexOf("(");return Vt!==-1?_t.substr(0,Vt):_t})(j=Gi(j)),ye=jt(oe,ye),Ri([],[$],function(_t){var Vt=`${(_t=_t[0]).name}.${j}`;function ui(){Pn(`Cannot call ${Vt} due to unbound types`,ht)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),Pe&&_t.registeredClass.pureVirtualFunctions.push(j);var It=_t.registeredClass.instancePrototype,Yt=It[j];return Yt===void 0||Yt.overloadTable===void 0&&Yt.className!==_t.name&&Yt.argCount===vA-2?(ui.argCount=vA-2,ui.className=_t.name,It[j]=ui):(ds(It,j,Vt),It[j].overloadTable[vA-2]=ui),Ri([],ht,function(qi){var Wi=fr(Vt,qi,_t,ye,He);return It[j].overloadTable===void 0?(Wi.argCount=vA-2,It[j]=Wi):It[j].overloadTable[vA-2]=Wi,[]}),[]})},k:($,j,vA,jA,oe,ye,He,Pe,rt,ht)=>{j=Gi(j),oe=jt(jA,oe),Ri([],[$],function(_t){var Vt=`${(_t=_t[0]).name}.${j}`,ui={get(){Pn(`Cannot access ${Vt} due to unbound types`,[vA,He])},enumerable:!0,configurable:!0};return ui.set=rt?()=>Pn(`Cannot access ${Vt} due to unbound types`,[vA,He]):It=>zt(Vt+" is a read-only property"),Object.defineProperty(_t.registeredClass.instancePrototype,j,ui),Ri([],rt?[vA,He]:[vA],function(It){var Yt=It[0],qi={get(){var qs=xn(this,_t,Vt+" getter");return Yt.fromWireType(oe(ye,qs))},enumerable:!0};if(rt){rt=jt(Pe,rt);var Wi=It[1];qi.set=function(qs){var vi=xn(this,_t,Vt+" setter"),zo=[];rt(ht,vi,Wi.toWireType(zo,qs)),Js(zo)}}return Object.defineProperty(_t.registeredClass.instancePrototype,j,qi),[]}),[]})},t:($,j)=>{Es($,{name:j=Gi(j),fromWireType:vA=>{var jA=cn.toValue(vA);return gn(vA),jA},toWireType:(vA,jA)=>cn.toHandle(jA),argPackAdvance:8,readValueFromPointer:Dr,destructorFunction:null})},p:($,j,vA)=>{Es($,{name:j=Gi(j),fromWireType:jA=>jA,toWireType:(jA,oe)=>oe,argPackAdvance:8,readValueFromPointer:wu(j,vA),destructorFunction:null})},g:($,j,vA,jA,oe)=>{j=Gi(j);var ye=rt=>rt;if(jA===0){var He=32-8*vA;ye=rt=>rt<>>He}var Pe=j.includes("unsigned");Es($,{name:j,fromWireType:ye,toWireType:Pe?function(rt,ht){return this.name,ht>>>0}:function(rt,ht){return this.name,ht},argPackAdvance:8,readValueFromPointer:Wa(j,vA,jA!==0),destructorFunction:null})},a:($,j,vA)=>{var jA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function oe(ye){var He=RA[ye>>2],Pe=RA[ye+4>>2];return new jA(lA.buffer,Pe,He)}Es($,{name:vA=Gi(vA),fromWireType:oe,argPackAdvance:8,readValueFromPointer:oe},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var vA=(j=Gi(j))==="std::string";Es($,{name:j,fromWireType(jA){var oe,ye=RA[jA>>2],He=jA+4;if(vA)for(var Pe=He,rt=0;rt<=ye;++rt){var ht=He+rt;if(rt==ye||tA[ht]==0){var _t=qI(Pe,ht-Pe);oe===void 0?oe=_t:(oe+="\0",oe+=_t),Pe=ht+1}}else{var Vt=new Array(ye);for(rt=0;rt{for(var ui=0,It=0;It=55296&&Yt<=57343?(ui+=4,++It):ui+=3}return ui})(oe):oe.length;var Pe=ys(4+ye+1),rt=Pe+4;if(RA[Pe>>2]=ye,vA&&He)((Vt,ui,It,Yt)=>{if(!(Yt>0))return 0;for(var qi=It,Wi=It+Yt-1,qs=0;qs=55296&&vi<=57343&&(vi=65536+((1023&vi)<<10)|1023&Vt.charCodeAt(++qs)),vi<=127){if(It>=Wi)break;ui[It++]=vi}else if(vi<=2047){if(It+1>=Wi)break;ui[It++]=192|vi>>6,ui[It++]=128|63&vi}else if(vi<=65535){if(It+2>=Wi)break;ui[It++]=224|vi>>12,ui[It++]=128|vi>>6&63,ui[It++]=128|63&vi}else{if(It+3>=Wi)break;ui[It++]=240|vi>>18,ui[It++]=128|vi>>12&63,ui[It++]=128|vi>>6&63,ui[It++]=128|63&vi}}ui[It]=0})(oe,tA,rt,ye+1);else if(He)for(var ht=0;ht255&&(yn(rt),zt("String has UTF-16 code units that do not fit in 8 bits")),tA[rt+ht]=_t}else for(ht=0;ht{var jA,oe,ye,He,Pe;vA=Gi(vA),j===2?(jA=eo,oe=pc,He=ng,ye=()=>IA,Pe=1):j===4&&(jA=Dg,oe=ua,He=bo,ye=()=>RA,Pe=2),Es($,{name:vA,fromWireType:rt=>{for(var ht,_t=RA[rt>>2],Vt=ye(),ui=rt+4,It=0;It<=_t;++It){var Yt=rt+4+It*j;if(It==_t||Vt[Yt>>Pe]==0){var qi=jA(ui,Yt-ui);ht===void 0?ht=qi:(ht+="\0",ht+=qi),ui=Yt+j}}return yn(rt),ht},toWireType:(rt,ht)=>{typeof ht!="string"&&zt(`Cannot pass non-string to C++ string type ${vA}`);var _t=He(ht),Vt=ys(4+_t+j);return RA[Vt>>2]=_t>>Pe,oe(ht,Vt+4,_t+j),rt!==null&&rt.push(yn,Vt),Vt},argPackAdvance:8,readValueFromPointer:Dr,destructorFunction(rt){yn(rt)}})},v:($,j)=>{Es($,{isVoid:!0,name:j=Gi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(vA,jA)=>{}})},j:($,j,vA)=>($=cn.toValue($),j=Xr(j,"emval::as"),To(j,vA,$)),e:($,j,vA,jA,oe)=>{var ye,He;return($=Kn[$])(j=cn.toValue(j),j[vA=(He=Hc[ye=vA])===void 0?Gi(ye):He],jA,oe)},d:gn,f:($,j,vA)=>{var jA=((ht,_t)=>{for(var Vt=new Array(ht),ui=0;ui>2],"parameter "+ui);return Vt})($,j),oe=jA.shift();$--;var ye,He,Pe=new Array($),rt=`methodCaller<(${jA.map(ht=>ht.name).join(", ")}) => ${oe.name}>`;return ye=rn(rt,(ht,_t,Vt,ui)=>{for(var It=0,Yt=0;Yt<$;++Yt)Pe[Yt]=jA[Yt].readValueFromPointer(ui+It),It+=jA[Yt].argPackAdvance;var qi=vA===1?Hs(_t,Pe):_t.apply(ht,Pe);for(Yt=0;Yt<$;++Yt)jA[Yt].deleteObject&&jA[Yt].deleteObject(Pe[Yt]);return To(oe,Vt,qi)}),He=Kn.length,Kn.push(ye),He},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=cn.toValue($);Js(j),gn($)},h:($,j)=>{var vA=($=Xr($,"_emval_take_value")).readValueFromPointer(j);return cn.toHandle(vA)},m:()=>{ct("")},s:($,j,vA)=>tA.copyWithin($,j,j+vA),r:$=>{tA.length,ct("OOM")},n:($,j,vA,jA)=>{for(var oe=0,ye=0;ye>2],Pe=RA[j+4>>2];j+=8;for(var rt=0;rt>2]=oe,0}},In=function(){var $={a:Ga};function j(vA,jA){var oe,ye;return In=vA.exports,_=In.z,oe=_.buffer,I.HEAP8=lA=new Int8Array(oe),I.HEAP16=BA=new Int16Array(oe),I.HEAPU8=tA=new Uint8Array(oe),I.HEAPU16=IA=new Uint16Array(oe),I.HEAP32=gA=new Int32Array(oe),I.HEAPU32=RA=new Uint32Array(oe),I.HEAPF32=HA=new Float32Array(oe),I.HEAPF64=ZA=new Float64Array(oe),Yi=In.C,ye=In.A,ae.unshift(ye),function(){if(lt--,I.monitorRunDependencies&&I.monitorRunDependencies(lt),lt==0&&wt){var He=wt;wt=null,He()}}(),In}if(lt++,I.monitorRunDependencies&&I.monitorRunDependencies(lt),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(vA){L(`Module.instantiateWasm callback failed with error: ${vA}`),c(vA)}return oi(0,ce,$,function(vA){j(vA.instance)}).catch(c),{}}(),ys=$=>(ys=In.B)($),Ea=$=>(Ea=In.D)($),yn=$=>(yn=In.E)($),ba=$=>(ba=In.F)($);I.dynCall_jiji=($,j,vA,jA,oe)=>(I.dynCall_jiji=In.G)($,j,vA,jA,oe),I._vertexShaderSource=10688;function Sa(){function $(){fn||(fn=!0,I.calledRun=!0,KA||(Ni(ae),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)We(I.postRun.shift());Ni(gt)}()))}lt>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)dt(I.preRun.shift());Ni(me)}(),lt>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(wt=function $(){fn||Sa(),fn||(wt=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Sa(),i.ready}})(),ZaA=zaA,Cm=typeof navigator>"u"?"":navigator.userAgent,Ys=t=>new RegExp(t,"i").test(Cm),Bc=t=>{if(Ys(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),n=Cm.match(i);if(n&&n[1])return n[1]}return""},vV=t=>{if(Ys(t)){const i=new RegExp(`${t}\\/(\\d+)`),n=Cm.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},SZ=/AppleWebKit\/([\d.]+)/i.exec(Cm);SZ&&parseFloat(SZ[1]);var hX=Ys("iPad"),BX=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ys("Macintosh"),QX=Ys("iPhone")&&!hX,XaA=Ys("iPod"),pX=QX||hX||XaA||BX,a4=Ys("Android"),$aA=function(){if(a4){const t=Cm.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),n=t[2]&&parseFloat(t[2]);if(i&&n)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();a4&&Ys("webkit")&&$aA<2.3;var AgA=Ys("Firefox"),egA=Bc("Firefox");vV("Firefox");var mX=Ys("Edge"),tgA=Bc("Edge"),fX=Ys("Edg"),igA=Bc("Edg");vV("Edg");var yX=Ys("SogouMobileBrowser"),ogA=Bc("SogouMobileBrowser"),DX=Ys("MetaSr\\s"),sgA=Bc("MetaSr\\s"),Ov=Ys("TBS"),ngA=Bc("TBS"),SX=Ys("XWEB"),rgA=Bc("XWEB");Ys("MSIE\\s8\\.0");var agA=Ys("MSIE\\/\\d+");(function(){if(agA){const t=/MSIE\s(\d+)\.\d/.exec(Cm);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(Cm)&&/rv:11.0/.test(Cm)&&(i=11),i}return NaN})();var ggA=Ys("(micromessenger|webbrowser)"),cgA=Bc("MicroMessenger"),g4=!Ov&&Ys("MQQBrowser")&&Ys("COVC"),c4=!Ov&&Ys("MQQBrowser")&&!Ys("COVC"),MZ=c4||g4?Bc("MQQBrowser"):"",MX=!Ov&&Ys(" QQBrowser"),lgA=Bc(" QQBrowser"),vX=!Ov&&Ys("QQBrowserLite"),IgA=Bc("QQBrowserLite"),RX=!Ov&&Ys("MQBHD"),ugA=Bc("MQBHD");Ys("Windows");!pX&&Ys("MAC OS X");!a4&&Ys("Linux");Ys("CrOS");Ys("MicroMessenger");Ys("UCBrowser");Ys("Electron");var wX=Ys("MiuiBrowser"),EgA=Bc("MiuiBrowser"),_X=Ys("HuaweiBrowser");Ys("Huawei")||Ys("HUAWEI");Ys("Honor")||Ys("HONOR");var dgA=Bc("HuaweiBrowser"),TX=Ys("SamsungBrowser"),CgA=Bc("SamsungBrowser"),NX=Ys("HeyTapBrowser"),hgA=Bc("HeyTapBrowser"),GX=Ys("VivoBrowser"),BgA=Bc("VivoBrowser");Ys("OpenHarmony");Bc("OpenHarmony");var QgA=()=>vV("Chrome"),vZ=Ys("CriOS"),bX=Ys("Chrome"),pgA=!mX&&!DX&&!yX&&!Ov&&!SX&&!fX&&!MX&&!wX&&!_X&&!TX&&!NX&&!GX&&bX;Ys("HeadlessChrome");var mgA=QgA(),fgA=Bc("Chrome");vV("Electron");var ygA=!bX&&!c4&&!g4&&!vX&&!RX&&Ys("Safari"),kX=Bc("Version"),LX=(()=>{if(BX)return kX;if(pX){const t=Cm.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();Number(LX.split(".")[0]);(()=>{const t=Number(LX.split(".")[0]);return t===14||t===13})();DgA();function DgA(){const t=new Map([[AgA,["Firefox",egA]],[fX,["Edg",igA]],[pgA,["Chrome",fgA]],[vZ,["ChiOS",Bc("CriOS")]],[ygA&&!vZ,["Safari",kX]],[Ov,["TBS",ngA]],[SX,["XWEB",rgA]],[ggA&&QX,["WeChat",cgA]],[MX,["QQ(Win)",lgA]],[c4,["QQ(Mobile)",MZ]],[g4,["QQ(Mobile X5)",MZ]],[vX,["QQ(Mac)",IgA]],[RX,["QQ(iPad)",ugA]],[wX,["MI",EgA]],[_X,["HW",dgA]],[TX,["Samsung",CgA]],[NX,["OPPO",hgA]],[GX,["VIVO",BgA]],[mX,["EDGE",tgA]],[yX,["SogouMobile",ogA]],[DX,["Sogou",sgA]]]);let i="unknown",n="unknown";return t.has(!0)&&([i,n]=t.get(!0)),{name:i,version:n}}var dc=1e-6,cT=typeof Float32Array<"u"?Float32Array:Array,UX={};function SgA(){var t=new cT(16);return cT!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function MgA(t){var i=new cT(16);return i[0]=t[0],i[1]=t[1],i[2]=t[2],i[3]=t[3],i[4]=t[4],i[5]=t[5],i[6]=t[6],i[7]=t[7],i[8]=t[8],i[9]=t[9],i[10]=t[10],i[11]=t[11],i[12]=t[12],i[13]=t[13],i[14]=t[14],i[15]=t[15],i}function vgA(t,i){return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function RgA(t,i,n,c,I,C,f,w,_,N,L,q,lA,tA,BA,IA){var gA=new cT(16);return gA[0]=t,gA[1]=i,gA[2]=n,gA[3]=c,gA[4]=I,gA[5]=C,gA[6]=f,gA[7]=w,gA[8]=_,gA[9]=N,gA[10]=L,gA[11]=q,gA[12]=lA,gA[13]=tA,gA[14]=BA,gA[15]=IA,gA}function wgA(t,i,n,c,I,C,f,w,_,N,L,q,lA,tA,BA,IA,gA){return t[0]=i,t[1]=n,t[2]=c,t[3]=I,t[4]=C,t[5]=f,t[6]=w,t[7]=_,t[8]=N,t[9]=L,t[10]=q,t[11]=lA,t[12]=tA,t[13]=BA,t[14]=IA,t[15]=gA,t}function FX(t){return t[0]=1,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=1,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=1,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function _gA(t,i){if(t===i){var n=i[1],c=i[2],I=i[3],C=i[6],f=i[7],w=i[11];t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=n,t[6]=i[9],t[7]=i[13],t[8]=c,t[9]=C,t[11]=i[14],t[12]=I,t[13]=f,t[14]=w}else t[0]=i[0],t[1]=i[4],t[2]=i[8],t[3]=i[12],t[4]=i[1],t[5]=i[5],t[6]=i[9],t[7]=i[13],t[8]=i[2],t[9]=i[6],t[10]=i[10],t[11]=i[14],t[12]=i[3],t[13]=i[7],t[14]=i[11],t[15]=i[15];return t}function TgA(t,i){var n=i[0],c=i[1],I=i[2],C=i[3],f=i[4],w=i[5],_=i[6],N=i[7],L=i[8],q=i[9],lA=i[10],tA=i[11],BA=i[12],IA=i[13],gA=i[14],RA=i[15],HA=n*w-c*f,ZA=n*_-I*f,KA=n*N-C*f,me=c*_-I*w,ae=c*N-C*w,gt=I*N-C*_,dt=L*IA-q*BA,We=L*gA-lA*BA,lt=L*RA-tA*BA,wt=q*gA-lA*IA,ct=q*RA-tA*IA,ce=lA*RA-tA*gA,Ve=HA*ce-ZA*ct+KA*wt+me*lt-ae*We+gt*dt;return Ve?(Ve=1/Ve,t[0]=(w*ce-_*ct+N*wt)*Ve,t[1]=(I*ct-c*ce-C*wt)*Ve,t[2]=(IA*gt-gA*ae+RA*me)*Ve,t[3]=(lA*ae-q*gt-tA*me)*Ve,t[4]=(_*lt-f*ce-N*We)*Ve,t[5]=(n*ce-I*lt+C*We)*Ve,t[6]=(gA*KA-BA*gt-RA*ZA)*Ve,t[7]=(L*gt-lA*KA+tA*ZA)*Ve,t[8]=(f*ct-w*lt+N*dt)*Ve,t[9]=(c*lt-n*ct-C*dt)*Ve,t[10]=(BA*ae-IA*KA+RA*HA)*Ve,t[11]=(q*KA-L*ae-tA*HA)*Ve,t[12]=(w*We-f*wt-_*dt)*Ve,t[13]=(n*wt-c*We+I*dt)*Ve,t[14]=(IA*ZA-BA*me-gA*HA)*Ve,t[15]=(L*me-q*ZA+lA*HA)*Ve,t):null}function NgA(t,i){var n=i[0],c=i[1],I=i[2],C=i[3],f=i[4],w=i[5],_=i[6],N=i[7],L=i[8],q=i[9],lA=i[10],tA=i[11],BA=i[12],IA=i[13],gA=i[14],RA=i[15],HA=n*w-c*f,ZA=n*_-I*f,KA=n*N-C*f,me=c*_-I*w,ae=c*N-C*w,gt=I*N-C*_,dt=L*IA-q*BA,We=L*gA-lA*BA,lt=L*RA-tA*BA,wt=q*gA-lA*IA,ct=q*RA-tA*IA,ce=lA*RA-tA*gA;return t[0]=w*ce-_*ct+N*wt,t[1]=I*ct-c*ce-C*wt,t[2]=IA*gt-gA*ae+RA*me,t[3]=lA*ae-q*gt-tA*me,t[4]=_*lt-f*ce-N*We,t[5]=n*ce-I*lt+C*We,t[6]=gA*KA-BA*gt-RA*ZA,t[7]=L*gt-lA*KA+tA*ZA,t[8]=f*ct-w*lt+N*dt,t[9]=c*lt-n*ct-C*dt,t[10]=BA*ae-IA*KA+RA*HA,t[11]=q*KA-L*ae-tA*HA,t[12]=w*We-f*wt-_*dt,t[13]=n*wt-c*We+I*dt,t[14]=IA*ZA-BA*me-gA*HA,t[15]=L*me-q*ZA+lA*HA,t}function GgA(t){var i=t[0],n=t[1],c=t[2],I=t[3],C=t[4],f=t[5],w=t[6],_=t[7],N=t[8],L=t[9],q=t[10],lA=t[11],tA=t[12],BA=t[13],IA=t[14],gA=i*f-n*C,RA=i*w-c*C,HA=n*w-c*f,ZA=N*BA-L*tA,KA=N*IA-q*tA,me=L*IA-q*BA;return _*(i*me-n*KA+c*ZA)-I*(C*me-f*KA+w*ZA)+t[15]*(N*HA-L*RA+q*gA)-lA*(tA*HA-BA*RA+IA*gA)}function OX(t,i,n){var c=i[0],I=i[1],C=i[2],f=i[3],w=i[4],_=i[5],N=i[6],L=i[7],q=i[8],lA=i[9],tA=i[10],BA=i[11],IA=i[12],gA=i[13],RA=i[14],HA=i[15],ZA=n[0],KA=n[1],me=n[2],ae=n[3];return t[0]=ZA*c+KA*w+me*q+ae*IA,t[1]=ZA*I+KA*_+me*lA+ae*gA,t[2]=ZA*C+KA*N+me*tA+ae*RA,t[3]=ZA*f+KA*L+me*BA+ae*HA,ZA=n[4],KA=n[5],me=n[6],ae=n[7],t[4]=ZA*c+KA*w+me*q+ae*IA,t[5]=ZA*I+KA*_+me*lA+ae*gA,t[6]=ZA*C+KA*N+me*tA+ae*RA,t[7]=ZA*f+KA*L+me*BA+ae*HA,ZA=n[8],KA=n[9],me=n[10],ae=n[11],t[8]=ZA*c+KA*w+me*q+ae*IA,t[9]=ZA*I+KA*_+me*lA+ae*gA,t[10]=ZA*C+KA*N+me*tA+ae*RA,t[11]=ZA*f+KA*L+me*BA+ae*HA,ZA=n[12],KA=n[13],me=n[14],ae=n[15],t[12]=ZA*c+KA*w+me*q+ae*IA,t[13]=ZA*I+KA*_+me*lA+ae*gA,t[14]=ZA*C+KA*N+me*tA+ae*RA,t[15]=ZA*f+KA*L+me*BA+ae*HA,t}function bgA(t,i,n){var c,I,C,f,w,_,N,L,q,lA,tA,BA,IA=n[0],gA=n[1],RA=n[2];return i===t?(t[12]=i[0]*IA+i[4]*gA+i[8]*RA+i[12],t[13]=i[1]*IA+i[5]*gA+i[9]*RA+i[13],t[14]=i[2]*IA+i[6]*gA+i[10]*RA+i[14],t[15]=i[3]*IA+i[7]*gA+i[11]*RA+i[15]):(c=i[0],I=i[1],C=i[2],f=i[3],w=i[4],_=i[5],N=i[6],L=i[7],q=i[8],lA=i[9],tA=i[10],BA=i[11],t[0]=c,t[1]=I,t[2]=C,t[3]=f,t[4]=w,t[5]=_,t[6]=N,t[7]=L,t[8]=q,t[9]=lA,t[10]=tA,t[11]=BA,t[12]=c*IA+w*gA+q*RA+i[12],t[13]=I*IA+_*gA+lA*RA+i[13],t[14]=C*IA+N*gA+tA*RA+i[14],t[15]=f*IA+L*gA+BA*RA+i[15]),t}function kgA(t,i,n){var c=n[0],I=n[1],C=n[2];return t[0]=i[0]*c,t[1]=i[1]*c,t[2]=i[2]*c,t[3]=i[3]*c,t[4]=i[4]*I,t[5]=i[5]*I,t[6]=i[6]*I,t[7]=i[7]*I,t[8]=i[8]*C,t[9]=i[9]*C,t[10]=i[10]*C,t[11]=i[11]*C,t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function LgA(t,i,n,c){var I,C,f,w,_,N,L,q,lA,tA,BA,IA,gA,RA,HA,ZA,KA,me,ae,gt,dt,We,lt,wt,ct=c[0],ce=c[1],Ve=c[2],Dt=Math.sqrt(ct*ct+ce*ce+Ve*Ve);return Dt0?(n[0]=2*(w*f+L*c+_*C-N*I)/q,n[1]=2*(_*f+L*I+N*c-w*C)/q,n[2]=2*(N*f+L*C+w*I-_*c)/q):(n[0]=2*(w*f+L*c+_*C-N*I),n[1]=2*(_*f+L*I+N*c-w*C),n[2]=2*(N*f+L*C+w*I-_*c)),PX(t,i,n),t}function KgA(t,i){return t[0]=i[12],t[1]=i[13],t[2]=i[14],t}function xX(t,i){var n=i[0],c=i[1],I=i[2],C=i[4],f=i[5],w=i[6],_=i[8],N=i[9],L=i[10];return t[0]=Math.sqrt(n*n+c*c+I*I),t[1]=Math.sqrt(C*C+f*f+w*w),t[2]=Math.sqrt(_*_+N*N+L*L),t}function jgA(t,i){var n=new cT(3);xX(n,i);var c=1/n[0],I=1/n[1],C=1/n[2],f=i[0]*c,w=i[1]*I,_=i[2]*C,N=i[4]*c,L=i[5]*I,q=i[6]*C,lA=i[8]*c,tA=i[9]*I,BA=i[10]*C,IA=f+L+BA,gA=0;return IA>0?(gA=2*Math.sqrt(IA+1),t[3]=.25*gA,t[0]=(q-tA)/gA,t[1]=(lA-_)/gA,t[2]=(w-N)/gA):f>L&&f>BA?(gA=2*Math.sqrt(1+f-L-BA),t[3]=(q-tA)/gA,t[0]=.25*gA,t[1]=(w+N)/gA,t[2]=(lA+_)/gA):L>BA?(gA=2*Math.sqrt(1+L-f-BA),t[3]=(lA-_)/gA,t[0]=(w+N)/gA,t[1]=.25*gA,t[2]=(q+tA)/gA):(gA=2*Math.sqrt(1+BA-f-L),t[3]=(w-N)/gA,t[0]=(lA+_)/gA,t[1]=(q+tA)/gA,t[2]=.25*gA),t}function WgA(t,i,n,c){i[0]=c[12],i[1]=c[13],i[2]=c[14];var I=c[0],C=c[1],f=c[2],w=c[4],_=c[5],N=c[6],L=c[8],q=c[9],lA=c[10];n[0]=Math.sqrt(I*I+C*C+f*f),n[1]=Math.sqrt(w*w+_*_+N*N),n[2]=Math.sqrt(L*L+q*q+lA*lA);var tA=1/n[0],BA=1/n[1],IA=1/n[2],gA=I*tA,RA=C*BA,HA=f*IA,ZA=w*tA,KA=_*BA,me=N*IA,ae=L*tA,gt=q*BA,dt=lA*IA,We=gA+KA+dt,lt=0;return We>0?(lt=2*Math.sqrt(We+1),t[3]=.25*lt,t[0]=(me-gt)/lt,t[1]=(ae-HA)/lt,t[2]=(RA-ZA)/lt):gA>KA&&gA>dt?(lt=2*Math.sqrt(1+gA-KA-dt),t[3]=(me-gt)/lt,t[0]=.25*lt,t[1]=(RA+ZA)/lt,t[2]=(ae+HA)/lt):KA>dt?(lt=2*Math.sqrt(1+KA-gA-dt),t[3]=(ae-HA)/lt,t[0]=(RA+ZA)/lt,t[1]=.25*lt,t[2]=(me+gt)/lt):(lt=2*Math.sqrt(1+dt-gA-KA),t[3]=(RA-ZA)/lt,t[0]=(ae+HA)/lt,t[1]=(me+gt)/lt,t[2]=.25*lt),t}function zgA(t,i,n,c){var I=i[0],C=i[1],f=i[2],w=i[3],_=I+I,N=C+C,L=f+f,q=I*_,lA=I*N,tA=I*L,BA=C*N,IA=C*L,gA=f*L,RA=w*_,HA=w*N,ZA=w*L,KA=c[0],me=c[1],ae=c[2];return t[0]=(1-(BA+gA))*KA,t[1]=(lA+ZA)*KA,t[2]=(tA-HA)*KA,t[3]=0,t[4]=(lA-ZA)*me,t[5]=(1-(q+gA))*me,t[6]=(IA+RA)*me,t[7]=0,t[8]=(tA+HA)*ae,t[9]=(IA-RA)*ae,t[10]=(1-(q+BA))*ae,t[11]=0,t[12]=n[0],t[13]=n[1],t[14]=n[2],t[15]=1,t}function ZgA(t,i,n,c,I){var C=i[0],f=i[1],w=i[2],_=i[3],N=C+C,L=f+f,q=w+w,lA=C*N,tA=C*L,BA=C*q,IA=f*L,gA=f*q,RA=w*q,HA=_*N,ZA=_*L,KA=_*q,me=c[0],ae=c[1],gt=c[2],dt=I[0],We=I[1],lt=I[2],wt=(1-(IA+RA))*me,ct=(tA+KA)*me,ce=(BA-ZA)*me,Ve=(tA-KA)*ae,Dt=(1-(lA+RA))*ae,ti=(gA+HA)*ae,Pt=(BA+ZA)*gt,oi=(gA-HA)*gt,Ni=(1-(lA+IA))*gt;return t[0]=wt,t[1]=ct,t[2]=ce,t[3]=0,t[4]=Ve,t[5]=Dt,t[6]=ti,t[7]=0,t[8]=Pt,t[9]=oi,t[10]=Ni,t[11]=0,t[12]=n[0]+dt-(wt*dt+Ve*We+Pt*lt),t[13]=n[1]+We-(ct*dt+Dt*We+oi*lt),t[14]=n[2]+lt-(ce*dt+ti*We+Ni*lt),t[15]=1,t}function XgA(t,i){var n=i[0],c=i[1],I=i[2],C=i[3],f=n+n,w=c+c,_=I+I,N=n*f,L=c*f,q=c*w,lA=I*f,tA=I*w,BA=I*_,IA=C*f,gA=C*w,RA=C*_;return t[0]=1-q-BA,t[1]=L+RA,t[2]=lA-gA,t[3]=0,t[4]=L-RA,t[5]=1-N-BA,t[6]=tA+IA,t[7]=0,t[8]=lA+gA,t[9]=tA-IA,t[10]=1-N-q,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function $gA(t,i,n,c,I,C,f){var w=1/(n-i),_=1/(I-c),N=1/(C-f);return t[0]=2*C*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*C*_,t[6]=0,t[7]=0,t[8]=(n+i)*w,t[9]=(I+c)*_,t[10]=(f+C)*N,t[11]=-1,t[12]=0,t[13]=0,t[14]=f*C*2*N,t[15]=0,t}function YX(t,i,n,c,I){var C=1/Math.tan(i/2);if(t[0]=C/n,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=C,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,I!=null&&I!==1/0){var f=1/(c-I);t[10]=(I+c)*f,t[14]=2*I*c*f}else t[10]=-1,t[14]=-2*c;return t}JaA(UX,{add:()=>gcA,adjoint:()=>NgA,clone:()=>MgA,copy:()=>vgA,create:()=>SgA,decompose:()=>WgA,determinant:()=>GgA,equals:()=>ucA,exactEquals:()=>IcA,frob:()=>acA,fromQuat:()=>XgA,fromQuat2:()=>qgA,fromRotation:()=>YgA,fromRotationTranslation:()=>PX,fromRotationTranslationScale:()=>zgA,fromRotationTranslationScaleOrigin:()=>ZgA,fromScaling:()=>xgA,fromTranslation:()=>PgA,fromValues:()=>RgA,fromXRotation:()=>VgA,fromYRotation:()=>JgA,fromZRotation:()=>HgA,frustum:()=>$gA,getRotation:()=>jgA,getScaling:()=>xX,getTranslation:()=>KgA,identity:()=>FX,invert:()=>TgA,lookAt:()=>scA,mul:()=>EcA,multiply:()=>OX,multiplyScalar:()=>ccA,multiplyScalarAndAdd:()=>lcA,ortho:()=>icA,orthoNO:()=>VX,orthoZO:()=>ocA,perspective:()=>AcA,perspectiveFromFieldOfView:()=>tcA,perspectiveNO:()=>YX,perspectiveZO:()=>ecA,rotate:()=>LgA,rotateX:()=>UgA,rotateY:()=>FgA,rotateZ:()=>OgA,scale:()=>kgA,set:()=>wgA,str:()=>rcA,sub:()=>dcA,subtract:()=>JX,targetTo:()=>ncA,translate:()=>bgA,transpose:()=>_gA});var AcA=YX;function ecA(t,i,n,c,I){var C=1/Math.tan(i/2);if(t[0]=C/n,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=C,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,I!=null&&I!==1/0){var f=1/(c-I);t[10]=I*f,t[14]=I*c*f}else t[10]=-1,t[14]=-c;return t}function tcA(t,i,n,c){var I=Math.tan(i.upDegrees*Math.PI/180),C=Math.tan(i.downDegrees*Math.PI/180),f=Math.tan(i.leftDegrees*Math.PI/180),w=Math.tan(i.rightDegrees*Math.PI/180),_=2/(f+w),N=2/(I+C);return t[0]=_,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=N,t[6]=0,t[7]=0,t[8]=-(f-w)*_*.5,t[9]=(I-C)*N*.5,t[10]=c/(n-c),t[11]=-1,t[12]=0,t[13]=0,t[14]=c*n/(n-c),t[15]=0,t}function VX(t,i,n,c,I,C,f){var w=1/(i-n),_=1/(c-I),N=1/(C-f);return t[0]=-2*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*_,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=2*N,t[11]=0,t[12]=(i+n)*w,t[13]=(I+c)*_,t[14]=(f+C)*N,t[15]=1,t}var icA=VX;function ocA(t,i,n,c,I,C,f){var w=1/(i-n),_=1/(c-I),N=1/(C-f);return t[0]=-2*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=-2*_,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[10]=N,t[11]=0,t[12]=(i+n)*w,t[13]=(I+c)*_,t[14]=C*N,t[15]=1,t}function scA(t,i,n,c){var I,C,f,w,_,N,L,q,lA,tA,BA=i[0],IA=i[1],gA=i[2],RA=c[0],HA=c[1],ZA=c[2],KA=n[0],me=n[1],ae=n[2];return Math.abs(BA-KA)0&&(L*=tA=1/Math.sqrt(tA),q*=tA,lA*=tA);var BA=_*lA-N*q,IA=N*L-w*lA,gA=w*q-_*L;return(tA=BA*BA+IA*IA+gA*gA)>0&&(BA*=tA=1/Math.sqrt(tA),IA*=tA,gA*=tA),t[0]=BA,t[1]=IA,t[2]=gA,t[3]=0,t[4]=q*gA-lA*IA,t[5]=lA*BA-L*gA,t[6]=L*IA-q*BA,t[7]=0,t[8]=L,t[9]=q,t[10]=lA,t[11]=0,t[12]=I,t[13]=C,t[14]=f,t[15]=1,t}function rcA(t){return"mat4("+t[0]+", "+t[1]+", "+t[2]+", "+t[3]+", "+t[4]+", "+t[5]+", "+t[6]+", "+t[7]+", "+t[8]+", "+t[9]+", "+t[10]+", "+t[11]+", "+t[12]+", "+t[13]+", "+t[14]+", "+t[15]+")"}function acA(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]+t[3]*t[3]+t[4]*t[4]+t[5]*t[5]+t[6]*t[6]+t[7]*t[7]+t[8]*t[8]+t[9]*t[9]+t[10]*t[10]+t[11]*t[11]+t[12]*t[12]+t[13]*t[13]+t[14]*t[14]+t[15]*t[15])}function gcA(t,i,n){return t[0]=i[0]+n[0],t[1]=i[1]+n[1],t[2]=i[2]+n[2],t[3]=i[3]+n[3],t[4]=i[4]+n[4],t[5]=i[5]+n[5],t[6]=i[6]+n[6],t[7]=i[7]+n[7],t[8]=i[8]+n[8],t[9]=i[9]+n[9],t[10]=i[10]+n[10],t[11]=i[11]+n[11],t[12]=i[12]+n[12],t[13]=i[13]+n[13],t[14]=i[14]+n[14],t[15]=i[15]+n[15],t}function JX(t,i,n){return t[0]=i[0]-n[0],t[1]=i[1]-n[1],t[2]=i[2]-n[2],t[3]=i[3]-n[3],t[4]=i[4]-n[4],t[5]=i[5]-n[5],t[6]=i[6]-n[6],t[7]=i[7]-n[7],t[8]=i[8]-n[8],t[9]=i[9]-n[9],t[10]=i[10]-n[10],t[11]=i[11]-n[11],t[12]=i[12]-n[12],t[13]=i[13]-n[13],t[14]=i[14]-n[14],t[15]=i[15]-n[15],t}function ccA(t,i,n){return t[0]=i[0]*n,t[1]=i[1]*n,t[2]=i[2]*n,t[3]=i[3]*n,t[4]=i[4]*n,t[5]=i[5]*n,t[6]=i[6]*n,t[7]=i[7]*n,t[8]=i[8]*n,t[9]=i[9]*n,t[10]=i[10]*n,t[11]=i[11]*n,t[12]=i[12]*n,t[13]=i[13]*n,t[14]=i[14]*n,t[15]=i[15]*n,t}function lcA(t,i,n,c){return t[0]=i[0]+n[0]*c,t[1]=i[1]+n[1]*c,t[2]=i[2]+n[2]*c,t[3]=i[3]+n[3]*c,t[4]=i[4]+n[4]*c,t[5]=i[5]+n[5]*c,t[6]=i[6]+n[6]*c,t[7]=i[7]+n[7]*c,t[8]=i[8]+n[8]*c,t[9]=i[9]+n[9]*c,t[10]=i[10]+n[10]*c,t[11]=i[11]+n[11]*c,t[12]=i[12]+n[12]*c,t[13]=i[13]+n[13]*c,t[14]=i[14]+n[14]*c,t[15]=i[15]+n[15]*c,t}function IcA(t,i){return t[0]===i[0]&&t[1]===i[1]&&t[2]===i[2]&&t[3]===i[3]&&t[4]===i[4]&&t[5]===i[5]&&t[6]===i[6]&&t[7]===i[7]&&t[8]===i[8]&&t[9]===i[9]&&t[10]===i[10]&&t[11]===i[11]&&t[12]===i[12]&&t[13]===i[13]&&t[14]===i[14]&&t[15]===i[15]}function ucA(t,i){var n=t[0],c=t[1],I=t[2],C=t[3],f=t[4],w=t[5],_=t[6],N=t[7],L=t[8],q=t[9],lA=t[10],tA=t[11],BA=t[12],IA=t[13],gA=t[14],RA=t[15],HA=i[0],ZA=i[1],KA=i[2],me=i[3],ae=i[4],gt=i[5],dt=i[6],We=i[7],lt=i[8],wt=i[9],ct=i[10],ce=i[11],Ve=i[12],Dt=i[13],ti=i[14],Pt=i[15];return Math.abs(n-HA)<=dc*Math.max(1,Math.abs(n),Math.abs(HA))&&Math.abs(c-ZA)<=dc*Math.max(1,Math.abs(c),Math.abs(ZA))&&Math.abs(I-KA)<=dc*Math.max(1,Math.abs(I),Math.abs(KA))&&Math.abs(C-me)<=dc*Math.max(1,Math.abs(C),Math.abs(me))&&Math.abs(f-ae)<=dc*Math.max(1,Math.abs(f),Math.abs(ae))&&Math.abs(w-gt)<=dc*Math.max(1,Math.abs(w),Math.abs(gt))&&Math.abs(_-dt)<=dc*Math.max(1,Math.abs(_),Math.abs(dt))&&Math.abs(N-We)<=dc*Math.max(1,Math.abs(N),Math.abs(We))&&Math.abs(L-lt)<=dc*Math.max(1,Math.abs(L),Math.abs(lt))&&Math.abs(q-wt)<=dc*Math.max(1,Math.abs(q),Math.abs(wt))&&Math.abs(lA-ct)<=dc*Math.max(1,Math.abs(lA),Math.abs(ct))&&Math.abs(tA-ce)<=dc*Math.max(1,Math.abs(tA),Math.abs(ce))&&Math.abs(BA-Ve)<=dc*Math.max(1,Math.abs(BA),Math.abs(Ve))&&Math.abs(IA-Dt)<=dc*Math.max(1,Math.abs(IA),Math.abs(Dt))&&Math.abs(gA-ti)<=dc*Math.max(1,Math.abs(gA),Math.abs(ti))&&Math.abs(RA-Pt)<=dc*Math.max(1,Math.abs(RA),Math.abs(Pt))}var EcA=OX,dcA=JX,RL=`#version 300 es in vec2 a_position; in vec2 a_texCoord; out vec2 v_texCoord; void main() { gl_Position = vec4(a_position.x, a_position.y, 0, 1); v_texCoord = a_texCoord; -}`,JW=t=>`precision highp float; +}`,l4=t=>`precision highp float; uniform sampler2D mask;in vec2 v_texCoord; out vec4 outColor; -void main() {${t}}`,PgA=`#version 300 es +void main() {${t}}`,CcA=`#version 300 es uniform sampler2D lastMask; -${JW(`highp float current = texture(mask, v_texCoord).r; +${l4(`highp float current = texture(mask, v_texCoord).r; highp float previous = texture(lastMask, v_texCoord).r; highp float diff = abs(current - previous); const float smoothFactor = 0.05; @@ -392,8 +392,8 @@ ${JW(`highp float current = texture(mask, v_texCoord).r; ? previous * (1.0 - smoothFactor) + current * smoothFactor : current; outColor = vec4(blendedMask,0.0,0.0, 1.0);`)} -`,xgA=`#version 300 es -${JW(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); +`,hcA=`#version 300 es +${l4(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); float size = 3.0; int sizeDb = int(size*size); float samples[9]; @@ -417,8 +417,8 @@ ${JW(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); } float endR=samples[sizeDb/2]>0.5?1.0:0.0; outColor = vec4(endR, 0.0, 0.0, 1.0);`)} -`,YgA=`#version 300 es -${JW(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); +`,BcA=`#version 300 es +${l4(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); float size = 3.0; float side = (size - 1.0) / 2.0; float stronglyEroded = 1.0; @@ -429,7 +429,7 @@ ${JW(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); } } outColor = vec4(stronglyEroded, 0.0, 0.0, 1.0);`)} -`,VgA=`#version 300 es +`,QcA=`#version 300 es precision highp float; uniform sampler2D mask; uniform sampler2D originalMask; @@ -482,7 +482,7 @@ void main() { } outColor = vec4(finalAlpha, 0.0, 0.0, 1.0); } -`,JgA=`#version 300 es +`,pcA=`#version 300 es precision highp float; uniform sampler2D mask; in vec2 v_texCoord; @@ -524,18 +524,18 @@ void main() { float edge = nmsEdge > 0.0 ? 1.0 : 0.0; outColor = vec4(edge, 0.0, 0.0, 1.0); } -`,HgA=class{constructor(){Hg(this,"gl"),Hg(this,"positionBuffer"),Hg(this,"texCoordBuffer"),Hg(this,"ratio"),Hg(this,"_tdProgram"),Hg(this,"_kcProgram"),Hg(this,"_mdProgram"),Hg(this,"_edgeProgram"),Hg(this,"_borderProgram"),Hg(this,"_lastMaskTexture")}init(t,i,r,l){this.initParams(t,i,r,l),this.initPrograms()}initParams(t,i,r,l){this.gl=t,this.positionBuffer=i,this.texCoordBuffer=r,this.ratio=l}initPrograms(){this._tdProgram=this.createProgram(fL,PgA,["mask","lastMask"]),this._mdProgram=this.createProgram(fL,xgA,["mask"]),this._kcProgram=this.createProgram(fL,YgA,["mask"]),this._borderProgram=this.createProgram(fL,VgA,["mask","maskEdge","originalMask"]),this._edgeProgram=this.createProgram(fL,JgA,["mask"])}setAttributes(...t){const{gl:i}=this;t.forEach((r,l)=>{i.enableVertexAttribArray(l),i.bindBuffer(i.ARRAY_BUFFER,r),i.vertexAttribPointer(l,2,i.FLOAT,!1,0,0)})}createShader(t,i){const{gl:r}=this,l=r.createShader(t);return r.shaderSource(l,i),r.compileShader(l),l}createProgram(t,i,r){const{gl:l}=this,I=this.createShader(l.FRAGMENT_SHADER,i),h=this.createShader(l.VERTEX_SHADER,t),f=l.createProgram();if(l.attachShader(f,h),l.attachShader(f,I),l.linkProgram(f),!l.getProgramParameter(f,l.LINK_STATUS))throw new Error(`${l.getProgramInfoLog(f)}`);return l.useProgram(f),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.forEach((w,_)=>{l.uniform1i(l.getUniformLocation(f,w),1+_)}),f}createFramebuffer(t){const{gl:i}=this,r=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,r),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),r}getTempTexture(t,i,r=!0,l){const{gl:I}=this;let h,f;I.useProgram(t),this.ratio===16/9?(h=640,f=360):(h=640,f=480);const w=I.createTexture();I.activeTexture(I.TEXTURE0),I.bindTexture(I.TEXTURE_2D,w),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE),I.pixelStorei(I.PACK_ALIGNMENT,1),I.pixelStorei(I.UNPACK_ALIGNMENT,1),I.texImage2D(I.TEXTURE_2D,0,I.RGBA,h,f,0,I.RGBA,I.UNSIGNED_BYTE,null);const _=this.createFramebuffer(w);return i.forEach((G,U)=>{G&&(I.activeTexture(I.TEXTURE1+U),I.bindTexture(I.TEXTURE_2D,G||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.viewport(0,0,h,f),I.drawArrays(I.TRIANGLE_STRIP,0,4),r&&i.forEach((G,U)=>{G&&l!==U&&I.deleteTexture(G)}),I.deleteFramebuffer(_),w}postProcessing(t){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[t,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let r=0;r<3;r++){i=this.getTempTexture(this._mdProgram,[i]);const l=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,l,this._lastMaskTexture],!0,2)}return i}close(){const{gl:t}=this;this._borderProgram&&t.deleteProgram(this._borderProgram),this._edgeProgram&&t.deleteProgram(this._edgeProgram),this._kcProgram&&t.deleteProgram(this._kcProgram),this._mdProgram&&t.deleteProgram(this._mdProgram),this._tdProgram&&t.deleteProgram(this._tdProgram)}},qgA=new HgA,KgA=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(KgA||{}),jgA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},y_=570703,Yj=0,fX=class yX{constructor(i){this.core=i,Hg(this,"seq"),Hg(this,"_core"),Hg(this,"log"),Hg(this,"preLoadPromise"),Hg(this,"startResolve"),Hg(this,"startReject"),Hg(this,"mediaPipeSolutions"),Hg(this,"assetsPath"),Hg(this,"currentType"),Hg(this,"onAbort"),Hg(this,"isAborted",!1),Yj+=1,this.seq=Yj,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${Yj}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(HaA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",jgA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await maA());const r=l=>{var I;this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",l),this.core.clearStarted(this,this.getGroup()),this.stop(),(I=this.onAbort)==null||I.call(this,l)};this._core.room.videoManager.initVirtualBackground(r,EX,qgA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(r){const{RtcError:l,ErrorCode:I}=this._core.errorModule;throw new l({code:I.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${r}`})}}getName(){return yX.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return haA(this._core);case"update":return BaA(this._core);case"stop":return QaA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,r=!1,l="NONE"){let I=0;switch(this.currentType){case"blur":I|=0;break;case"image":I|=1;break;case"color":I|=2}switch(i&&(I|=256),r&&(I|=512),l){case"ABORT_IN_INFERENCE":I|=4096;break;case"ABORT_IN_VIDEO_MANAGER":I|=8192;break;case"OTHER":I|=61440}return I}hexToRgb(i){const r=i.replace("#","");return[parseInt(r.slice(0,2),16)/255,parseInt(r.slice(2,4),16)/255,parseInt(r.slice(4,6),16)/255]}async start(i){const{type:r="blur",src:l,blurLevel:I=3,onAbort:h}=i;this.currentType=r,this.onAbort=h,r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:f}=await daA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:w,ErrorCodeDictionary:_,ErrorCode:G}=this._core.errorModule;if(!f){const U=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new w({code:_.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:U}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new w({code:G.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});this.preLoadPromise=this.preload(this._core.assetsPath)}return await this.preLoadPromise,this.core.room.videoManager.setVirtualBackground({type:r,imageUrl:l,blurLevel:I,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:U=>{var j;this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(j=this.onAbort)==null||j.call(this,U)}}).then(()=>{this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(U=>{throw this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),U})}async update(i){const{type:r,src:l}=i;return r!==this.currentType&&(this.currentType=r),r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:r,imageUrl:l,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:y_,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Hg(fX,"Name","VirtualBackground");var DX=fX,WgA=DX;const zgA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:DX,default:WgA},Symbol.toStringTag,{value:"Module"})),ZgA=kU(zgA);var XgA=Object.defineProperty,$gA=(t,i,r)=>i in t?XgA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,UL=(t,i,r)=>$gA(t,typeof i!="symbol"?i+"":i,r);function AcA(t){return{name:"BasicBeautyOptions",type:"object",required:!0,allowEmpty:!1,properties:{beauty:{required:!1,type:"number"},brightness:{required:!1,type:"number"},ruddy:{required:!1,type:"number"}},validate(i,r,l,I){const{RtcError:h,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(t.utils.isOverseaSdkAppId(i.sdkAppId))throw new h({code:f.INVALID_OPERATION,extraCode:w.INVALID_OPERATION,message:"This feature is not yet available in your country or region. If you have any questions, you can go to the community for consultation: https://zhiliao.qq.com/s/cWSPGIIM62CC/c3TPGIIM62CQ"})}}}function ecA(t){return{name:"StopBasicBeautyOptions",required:!1}}var tcA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,l,I=i;I.ready=new Promise(($,K)=>{r=$,l=K});var h=Object.assign({},I),f="";typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),t&&(f=t),f=f.indexOf("blob:")!==0?f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,G=I.print||console.log.bind(console),U=I.printErr||console.error.bind(console);function j($){if(Me($))return function(K){for(var vA=atob(K),qA=new Uint8Array(vA.length),Ae=0;Ae$.startsWith(yt);function Oe($){return Promise.resolve().then(()=>function(K){if(K==re&&w)return new Uint8Array(w);var vA=j(K);if(vA)return vA;throw"both async and sync fetching of the wasm failed"}($))}function gt($,K,vA,qA){return function(Ae,me,Pe){return Oe(Ae).then(Fe=>WebAssembly.instantiate(Fe,me)).then(Fe=>Fe).then(Pe,Fe=>{U(`failed to asynchronously prepare wasm: ${Fe}`),Et(Fe)})}(K,vA,qA)}Me(re="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQA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KAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2AhwgAEIANwMQIAAgACgCAEEgcjYCAEEAIAdBAkYNABogAiAEKAIEawshCiADQSBqJAAgCgt+AQF/IAAEQCAALAA3QQBIBEAgACgCLBAZCyAALAArQQBIBEAgACgCIBAZCyAAKAIcIgEEQCABEAMgAEEANgIcCyAAKAIUIgEEQCABEAMgAEEANgIUCyAAKAIMIgEEQCABEAMgAEEANgIMCyAAKAIEIgEEQCABEAMLIAAQGQsLJAECfyAAKAIEIgAQKkEBaiIBEC0iAgR/IAIgACABECIFQQALC/AeAw1/AnwBfSMAQUBqIgMkACADQaADEBwiAjYCHCADQp2DgICAtICAgH83AiAgAkGuHkGdAxAiQQA6AJ0DIANBHGoiAkGVEUGAESABLQA4GxAaGgJAIAICf0GAEiABKAJEIgJB2gBGDQAaIAJBjgJHBEAgAkG0AUcNAkHGEQwBC0HmEQsQGhoLIANBHGpBtyYQGhoCQAJAAkACQAJAIAEoAjxBAWsOAwABAgMLIANBKGohDSABKAJAIQwjAEGgAWsiBiQAIwBBEGsiBCQAIARBADYCDCAEQgA3AgQgBEE4EBwiAjYCBCAEIAJBOGoiBTYCDCACQQBBOBAmGiAEIAU2AggCfyAGQZQBaiIFQQA2AgggBUIANwIAIAVB1AAQHCICNgIEIAUgAjYCACAFIAJB1ABqIgg2AggCQAJAIAQoAggiByAEKAIEIglGBEAgAkEAQdQAECYaDAELIAcgCWsiCkEDdSIHQYCAgIACTw0BIAdBA3QhCwNAIAJBADYCCCACQgA3AgAgAiAKEBwiBzYCBCACIAc2AgAgAiAHIAtqIg42AgggByAJIAoQIhogAiAONgIEIAJBDGoiAiAIRw0ACwsgBSAINgIEIAUMAQsgAkEANgIIIAJCADcCAEHiCBBSAAshCSAEKAIEIgIEQCAEIAI2AgggAhAZC0EAIQIDQCAJKAIAIAJBDGxqIQcgAiACbCEIAkAgAkUEQEEAIQUDQCAFIAVsIAhqt58iD0QAAAAAAAAcQGUEQCAHKAIAIAVBA3RqIA8gD5qiRAAAAAAAADJAoxA2RAMkJUW5G5I/oiIPOQMAIA8gEKAhEAsgBUEBaiIFQQdHDQALDAELIAi3nyIPRAAAAAAAABxAZQRAIA8gD5qiRAAAAAAAADJAoxA2IQ8gBygCACAPRAMkJUW5G5I/oiIPOQMAIA8gEKAhEAtBASEFA0AgBSAFbCAIarefIg9EAAAAAAAAHEBlBEAgBygCACAFQQN0aiAPIA+aokQAAAAAAAAyQKMQNkQDJCVFuRuSP6IiDzkDACAPRAAAAAAAABBAoiAQoCEQCyAFQQFqIgVBB0cNAAsLIAJBAWoiAkEHRw0ACyAJKAIAIQlBACECA0AgCSACQQxsaigCACEHQQAhBUEAIQgDQCAHIAVBA3QiCmoiCyALKwMAIBCjOQMAIAcgCkEIcmoiCiAKKwMAIBCjOQMAIAVBAmohBSAIQQJqIghBBkcNAAsgByAFQQN0aiIFIAUrAwAgEKM5AwAgAkEBaiICQQdHDQALIARBEGokACAGQQA6AIgBIAZBADoAkwFBeiEFA0AgBSAMbCEHIAUgBUEfdSICcyACa0EMbCEIQXohAgNAAkAgBigClAEgCGooAgAgAiACQR91IgRzIARrQQN0aisDALYiEUMAAAAAXkUNACAGQRxqIgQgBxAvIAYgBEHNFhAlIgQoAgg2AjAgBiAEKQIANwMoIARCADcCACAEQQA2AgggBkFAayAGQShqQaMSEBoiBCgCCDYCACAGIAQpAgA3AzggBEIANwIAIARBADYCCCAGQRBqIgQgAiAMbBAvIAYgBkE4aiAGKAIQIAQgBi0AGyIEwEEASCIJGyAGKAIUIAQgCRsQGyIEKAIINgJQIAYgBCkCADcDSCAEQgA3AgAgBEEANgIIIAYgBkHIAGpBpxIQGiIEKAIINgJgIAYgBCkCADcDWCAEQgA3AgAgBEEANgIIIAZBBGoiBCAREC4gBiAGQdgAaiAGKAIEIAQgBi0ADyIEwEEASCIJGyAGKAIIIAQgCRsQGyIEKAIINgJwIAYgBCkCADcDaCAEQgA3AgAgBEEANgIIIAYgBkHoAGpBmBIQGiIEKAIINgKAASAGIAQpAgA3A3ggBEIANwIAIARBADYCCCAGQYgBaiAGKAJ4IAZB+ABqIAYtAIMBIgTAQQBIIgkbIAYoAnwgBCAJGxAbGiAGLACDAUEASARAIAYoAngQGQsgBiwAc0EASARAIAYoAmgQGQsgBiwAD0EASARAIAYoAgQQGQsgBiwAY0EASARAIAYoAlgQGQsgBiwAU0EASARAIAYoAkgQGQsgBiwAG0EASARAIAYoAhAQGQsgBiwAQ0EASARAIAYoAjgQGQsgBiwAM0EASARAIAYoAigQGQsgBiwAJ0EATg0AIAYoAhwQGQsgAkEBaiICQQdHDQALIAVBAWoiBUEHRw0ACyMAQRBrIgwkAEGZJhAqIQcCfyAGQYgBaiIFLQALQQd2BEAgBSgCBAwBCyAFLQALQf8AcQshCAJ/An8jAEEQayIJJAAgBkH4AGohAiAHIAhqIgRB7////wdNBEACQCAEQQtJBEAgAkIANwIAIAJBADYCCCACIAItAAtBgAFxIARB/wBxcjoACyACIAItAAtB/wBxOgALDAELIARBC08EfyAEQRBqQXBxIgogCkEBayIKIApBC0YbBUEKC0EBaiIKEBwhCyACIAIoAghBgICAgHhxIApB/////wdxcjYCCCACIAIoAghBgICAgHhyNgIIIAIgCzYCACACIAQ2AgQLIAlBEGokACACDAELECcACyIELQALQQd2BEAgBCgCAAwBCyAECyIEQZkmIAcQIyAEIAdqIgQCfyAFLQALQQd2BEAgBSgCAAwBCyAFCyAIECMgBCAIakEBEEAgDEEQaiQAIA0gAkHzKRAaIgIpAgA3AgAgDSACKAIINgIIIAJCADcCACACQQA2AgggBiwAgwFBAEgEQCAGKAJ4EBkLIAYsAJMBQQBIBEAgBigCiAEQGQsgBigClAEiBQRAIAYoApgBIgQgBSICRwRAA0AgBEEMayICKAIAIgcEQCAEQQhrIAc2AgAgBxAZCyACIgQgBUcNAAsgBigClAEhAgsgBiAFNgKYASACEBkLIAZBoAFqJAAgA0EcaiADKAIoIA0gAy0AMyICwEEASCIFGyADKAIsIAIgBRsQGxogAywAM0EATg0DIAMoAigQGQwDCyADQRxqQcwhEBoaDAILIANBHGpBrywQGhoMAQsgA0EcakGYLBAaGgsCQAJAIAEoAjAgAS0ANyICIALAIgZBAEgbIgRBAWoiBUHw////B0kEQAJAAkAgBUELTwRAIAVBD3JBAWoiBxAcIQIgAyAFNgIsIAMgAjYCKCADIAdBgICAgHhyNgIwDAELIANBADYCMCADQgA3AyggAyAFOgAzIANBKGohAiAERQ0BCyACIAFBLGoiBSgCACAFIAZBAEgbIAQQMgsgAiAEakEKOwAAIANBHGogAygCKCADQShqIAMtADMiAsBBAEgiBRsgAygCLCACIAUbEBsaIAMsADNBAEgEQCADKAIoEBkLIAEoAiQgAS0AKyICIALAIgZBAEgbIgRBAmoiBUHw////B08NAQJAAkAgBUELTwRAIAVBD3JBAWoiBxAcIQIgAyAFNgIsIAMgAjYCKCADIAdBgICAgHhyNgIwDAELIANBADYCMCADQgA3AyggAyAFOgAzIANBKGohAiAERQ0BCyACIAFBIGoiBSgCACAFIAZBAEgbIAQQMgsgAiAEaiICQQA6AAIgAkH9FDsAACADQRxqIAMoAiggA0EoaiADLQAzIgLAQQBIIgUbIAMoAiwgAiAFGxAbGiADLAAzQQBIBEAgAygCKBAZC0HA0wAoAgAiBBAqIgJB8P///wdPDQICQAJAIAJBC08EQCACQQ9yQQFqIgYQHCEFIAMgBkGAgICAeHI2AhggAyAFNgIQIAMgAjYCFAwBCyADIAI6ABsgA0EQaiEFIAJFDQELIAUgBCACEDILIAIgBWpBADoAACADQShqIAFBsZYCIANBEGoQUyADKAIsIQIgA0EANgIsIAMoAighBQJAIAEoAhQiBEUEQCABIAI2AhQgASAFNgIQDAELIAQQAyADKAIsIQQgASACNgIUIAEgBTYCECAERQ0AIAQQAyADQQA2AiwLIAMsABtBAEgEQCADKAIQEBkLAkAgAywAJ0EATgRAIAMgAygCJDYCCCADIAMpAhw3AwAMAQsgAygCHCEGIAMoAiAhBSMAQRBrIgQkAAJAAkACQCAFQQtJBEAgAyECIAMgAy0AC0GAAXEgBUH/AHFyOgALIAMgAy0AC0H/AHE6AAsMAQsgBUHv////B0sNASAEQQhqIAMgBUELTwR/IAVBEGpBcHEiAiACQQFrIgIgAkELRhsFQQoLQQFqEDAgBCgCDBogAyAEKAIIIgI2AgAgAyADKAIIQYCAgIB4cSAEKAIMQf////8HcXI2AgggAyADKAIIQYCAgIB4cjYCCCADIAU2AgQLIAIgBiAFQQFqECMgBEEQaiQADAELECcACwsgA0EoaiABQbCWAiADEFMgAygCLCECIANBADYCLCADKAIoIQUCQCABKAIMIgRFBEAgASACNgIMIAEgBTYCCAwBCyAEEAMgAygCLCEEIAEgAjYCDCABIAU2AgggBEUNACAEEAMgA0EANgIsCyADLAALQQBIBEAgAygCABAZCyADQQA2AihBhNUALQAAQQFxRQRAQQFBqC9BABAFIQJBhNUAQQE6AABBgNUAIAI2AgALAn9BgNUAKAIAIAEoAgRB6QkgA0EoakEAEAQiEEQAAAAAAADwQWMgEEQAAAAAAAAAAGZxBEAgEKsMAQtBAAshAiADKAIoIgUEQCAFEAELIAEoAhwiBQRAIAUQAwsgASACNgIcIAFB1NUANgIYIAIQAiADIAI2AiggASgCFCICEAIgAyACNgIwIANBADYCPEGM1QAtAABBAXFFBEBBA0GsL0EAEAUhAkGM1QBBAToAAEGI1QAgAjYCAAtBiNUAKAIAIAEoAgRB8AggA0E8aiADQShqEAQaIAMoAjwiAgRAIAIQAQsgASgCHCICEAIgAyACNgIoIAEoAgwiAhACIAMgAjYCMCADQQA2AjxBjNUALQAAQQFxRQRAQQNBrC9BABAFIQJBjNUAQQE6AABBiNUAIAI2AgALQYjVACgCACABKAIEQfAIIANBPGogA0EoahAEGiADKAI8IgIEQCACEAELIAEoAhwiAhACIAMgAjYCKCADQQA2AjxB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACABKAIEQc8JIANBPGogA0EoahAEGiADKAI8IgIEQCACEAELIAAgASgCHCIBNgIEIABB1NUANgIAIAEQAiADLAAnQQBIBEAgAygCHBAZCyADQUBrJAAPCxA3AAsQNwALEDcAC9gCAQJ/IwBBEGsiASQAIAAoAhQiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQf0IIAFBBGogAUEIahAEGiABKAIEIgIEQCACEAELIAAoAgwiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQf0IIAFBBGogAUEIahAEGiABKAIEIgIEQCACEAELIAAoAhwiAhACIAEgAjYCCCABQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQJB7NQAQQE6AABB6NQAIAI2AgALQejUACgCACAAKAIEQdsJIAFBBGogAUEIahAEGiABKAIEIgAEQCAAEAELIAFBEGokAAs1AQF/IAEgACgCBCICQQF1aiEBIAAoAgAhACABIAJBAXEEfyABKAIAIABqKAIABSAACxEDAAsvAAJ/IAAsACtBAEgEQCAAQQA2AiQgACgCIAwBCyAAQQA6ACsgAEEgagtBADoAAAsFAEHoLAs9AQF/IAEgACgCBCIGQQF1aiEBIAAoAgAhACABIAIgAyAEIAUgBkEBcQR/IAEoAgAgAGooAgAFIAALEQ0AC7wJAgR/AXwjAEEQayIIJAAgASEJIAAoAkQhBiMAQYACayIFJAACQAJAIAZBjgJGDQAgBkHaAEYNACADIQEgBCEDDAELIAQhAQsgBUHEAGoiBiAJECEgBSAGQdsSECUiBigCCDYCWCAFIAYpAgA3A1AgBkIANwIAIAZBADYCCCAFIAVB0ABqQfEUEBoiBigCCDYCaCAFIAYpAgA3A2AgBkIANwIAIAZBADYCCCAFQThqIgYgAhAhIAUgBUHgAGogBSgCOCAGIAUtAEMiBsBBAEgiBxsgBSgCPCAGIAcbEBsiBigCCDYCeCAFIAYpAgA3A3AgBkIANwIAIAZBADYCCCAFIAVB8ABqQbYSEBoiBigCCDYCiAEgBSAGKQIANwOAASAGQgA3AgAgBkEANgIIIAVBLGoiBiABIAmgECEgBSAFQYABaiAFKAIsIAYgBS0ANyIGwEEASCIHGyAFKAIwIAYgBxsQGyIGKAIINgKYASAFIAYpAgA3A5ABIAZCADcCACAGQQA2AgggBSAFQZABakHxFBAaIgYoAgg2AqgBIAUgBikCADcDoAEgBkIANwIAIAZBADYCCCAFQSBqIgYgAyACoBAhIAUgBUGgAWogBSgCICAGIAUtACsiBsBBAEgiBxsgBSgCJCAGIAcbEBsiBigCCDYCuAEgBSAGKQIANwOwASAGQgA3AgAgBkEANgIIIAUgBUGwAWpByhMQGiIGKAIINgLIASAFIAYpAgA3A8ABIAZCADcCACAGQQA2AgggBUEUaiIGIAEQISAFIAVBwAFqIAUoAhQgBiAFLQAfIgbAQQBIIgcbIAUoAhggBiAHGxAbIgYoAgg2AtgBIAUgBikCADcD0AEgBkIANwIAIAZBADYCCCAFIAVB0AFqQagTEBoiBigCCDYC6AEgBSAGKQIANwPgASAGQgA3AgAgBkEANgIIIAVBCGoiBiADECEgBSAFQeABaiAFKAIIIAYgBS0AEyIGwEEASCIHGyAFKAIMIAYgBxsQGyIGKAIINgL4ASAFIAYpAgA3A/ABIAZCADcCACAGQQA2AgggCCAFQfABakGEHRAaIgYpAgA3AgQgCCAGKAIINgIMIAZCADcCACAGQQA2AgggBSwA+wFBAEgEQCAFKALwARAZCyAFLAATQQBIBEAgBSgCCBAZCyAFLADrAUEASARAIAUoAuABEBkLIAUsANsBQQBIBEAgBSgC0AEQGQsgBSwAH0EASARAIAUoAhQQGQsgBSwAywFBAEgEQCAFKALAARAZCyAFLAC7AUEASARAIAUoArABEBkLIAUsACtBAEgEQCAFKAIgEBkLIAUsAKsBQQBIBEAgBSgCoAEQGQsgBSwAmwFBAEgEQCAFKAKQARAZCyAFLAA3QQBIBEAgBSgCLBAZCyAFLACLAUEASARAIAUoAoABEBkLIAUsAHtBAEgEQCAFKAJwEBkLIAUsAENBAEgEQCAFKAI4EBkLIAUsAGtBAEgEQCAFKAJgEBkLIAUsAFtBAEgEQCAFKAJQEBkLIAUsAE9BAEgEQCAFKAJEEBkLIAVBgAJqJAAgACwAK0EASARAIAAoAiAQGQsgACAIKQIENwIgIAAgCCgCDDYCKCAIQRBqJAALPwEBfyABIAAoAgQiB0EBdWohASAAKAIAIQAgASACIAMgBCAFIAYgB0EBcQR/IAEoAgAgAGooAgAFIAALEQ4AC88bAgd/AXwjAEFAaiIJJAAgCSAFOQMgIAkgBDkDGCAJIAM5AxAgCSACOQMIIAkgATkDACMAQRBrIgYkACAGIAk2AgxByNMAQf4rIAlBABBNGiAGQRBqJAAjAEGABGsiBiQAIAlBNGoiC0EAOgAAIAtBADoACwJAIAFEAAAAAAAAAABkRQ0AIAZBADoA8AMgBkEAOgD7AyAGQQA6AOQDIAZBADoA7wMgBkKAgICAhICAgMAANwPYAyAGQoCAgICEgICAQDcD0AMgBkKAgICAjICAgMAANwPIAyAGQoCAgICMgICAQDcDwAMgBkKAgICEhICAwMAANwO4AyAGQoCAgISEgIDAQDcDsAMgBkKAgICEjICAwMAANwOoAyAGQoCAgISMgIDAQDcDoAMgBkKAgICGDDcDmAMgBkKAgICGBDcDkAMgBkKAgICAgICA4MAANwOIAyAGQoCAgICAgIDgQDcDgAMgBkKAgICIjICA0EA3A/gCIAZCgICAiIyAgNDAADcD8AIgBkKAgICIhICA0MAANwPoAiAGQoCAgIiEgIDQQDcD4AIgBkKAgICFjICAgEE3A9gCIAZCgICAhYyAgIDBADcD0AIgBkKAgICFhICAgMEANwPIAiAGQoCAgIWEgICAQTcDwAIgBkKAgICJBDcDuAIgBkKAgICJDDcDsAIgBkKAgICAgICAkMEANwOoAiAGQoCAgICAgICQQTcDoAJEAAAAAAAAAEAgBKMhBCABRJqZmZmZmem/okQAAAAAAADwP6AhDQNAIAZBsAFqIgggBxAvIAYgCEHECxAlIggoAgg2AsgBIAYgCCkCADcDwAEgCEIANwIAIAhBADYCCCAGIAZBwAFqQfQWEBoiCCgCCDYC2AEgBiAIKQIANwPQASAIQgA3AgAgCEEANgIIIAZBoAFqIgggBkGgAmogB0EDdGoiCioCABAuIAYgBkHQAWogBigCoAEgCCAGLQCrASIIwEEASCIMGyAGKAKkASAIIAwbEBsiCCgCCDYC6AEgBiAIKQIANwPgASAIQgA3AgAgCEEANgIIIAYgBkHgAWpB+RwQGiIIKAIINgL4ASAGIAgpAgA3A/ABIAhCADcCACAIQQA2AgggBkGQAWoiCCAKKgIEEC4gBiAGQfABaiAGKAKQASAIIAYtAJsBIgjAQQBIIgobIAYoApQBIAggChsQGyIIKAIINgKIAiAGIAgpAgA3A4ACIAhCADcCACAIQQA2AgggBiAGQYACakGXEhAaIggoAgg2ApgCIAYgCCkCADcDkAIgCEIANwIAIAhBADYCCCAGQeQDaiAGKAKQAiAGQZACaiAGLQCbAiIIwEEASCIKGyAGKAKUAiAIIAobEBsaIAYsAJsCQQBIBEAgBigCkAIQGQsgBiwAiwJBAEgEQCAGKAKAAhAZCyAGLACbAUEASARAIAYoApABEBkLIAYsAPsBQQBIBEAgBigC8AEQGQsgBiwA6wFBAEgEQCAGKALgARAZCyAGLACrAUEASARAIAYoAqABEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgBiwAywFBAEgEQCAGKALAARAZCyAGLAC7AUEASARAIAYoArABEBkLIAZB0AFqIgggBxAvIAYgCEGmCxAlIggoAgg2AugBIAYgCCkCADcD4AEgCEIANwIAIAhBADYCCCAGIAZB4AFqQfwcEBoiCCgCCDYC+AEgBiAIKQIANwPwASAIQgA3AgAgCEEANgIIIAZBwAFqIghDAAAAQEMAAEBAQwAAgD8gB0ETSxsgB0EMa0EISRsQLiAGIAZB8AFqIAYoAsABIAggBi0AywEiCMBBAEgiChsgBigCxAEgCCAKGxAbIggoAgg2AogCIAYgCCkCADcDgAIgCEIANwIAIAhBADYCCCAGIAZBgAJqQZcXEBoiCCgCCDYCmAIgBiAIKQIANwOQAiAIQgA3AgAgCEEANgIIIAZB8ANqIAYoApACIAZBkAJqIAYtAJsCIgjAQQBIIgobIAYoApQCIAggChsQGxogBiwAmwJBAEgEQCAGKAKQAhAZCyAGLACLAkEASARAIAYoAoACEBkLIAYsAMsBQQBIBEAgBigCwAEQGQsgBiwA+wFBAEgEQCAGKALwARAZCyAGLADrAUEASARAIAYoAuABEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgB0EBaiIHQRhHDQALIAZBNGoiByAEECEgBiAHQdoWECUiBygCCDYCSCAGIAcpAgA3A0AgB0IANwIAIAdBADYCCCAGIAZBQGtBpRIQGiIHKAIINgJYIAYgBykCADcDUCAHQgA3AgAgB0EANgIIIAZBKGoiB0QAAAAAAAAAQCAFoxAhIAYgBkHQAGogBigCKCAHIAYtADMiB8BBAEgiCBsgBigCLCAHIAgbEBsiBygCCDYCaCAGIAcpAgA3A2AgB0IANwIAIAdBADYCCCAGIAZB4ABqQdIdEBoiBygCCDYCeCAGIAcpAgA3A3AgB0IANwIAIAdBADYCCCAGIAZB8ABqIAYoAuQDIAZB5ANqIAYtAO8DIgfAQQBIIggbIAYoAugDIAcgCBsQGyIHKAIINgKIASAGIAcpAgA3A4ABIAdCADcCACAHQQA2AgggBiAGQYABakH6HRAaIgcoAgg2ApgBIAYgBykCADcDkAEgB0IANwIAIAdBADYCCCAGIAZBkAFqIAYoAvADIAZB8ANqIAYtAPsDIgfAQQBIIggbIAYoAvQDIAcgCBsQGyIHKAIINgKoASAGIAcpAgA3A6ABIAdCADcCACAHQQA2AgggBiAGQaABakGYGxAaIgcoAgg2ArgBIAYgBykCADcDsAEgB0IANwIAIAdBADYCCCAGQRxqIgcgDRAhIAYgBkGwAWogBigCHCAHIAYtACciB8BBAEgiCBsgBigCICAHIAgbEBsiBygCCDYCyAEgBiAHKQIANwPAASAHQgA3AgAgB0EANgIIIAYgBkHAAWpBlxUQGiIHKAIINgLYASAGIAcpAgA3A9ABIAdCADcCACAHQQA2AgggBkEQaiIHIAFEMzMzMzMz47+iRAAAAAAAAPA/oBAhIAYgBkHQAWogBigCECAHIAYtABsiB8BBAEgiCBsgBigCFCAHIAgbEBsiBygCCDYC6AEgBiAHKQIANwPgASAHQgA3AgAgB0EANgIIIAYgBkHgAWpBmhcQGiIHKAIINgL4ASAGIAcpAgA3A/ABIAdCADcCACAHQQA2AgggBkEEaiIHIAEQISAGIAZB8AFqIAYoAgQgByAGLQAPIgfAQQBIIggbIAYoAgggByAIGxAbIgcoAgg2AogCIAYgBykCADcDgAIgB0IANwIAIAdBADYCCCAGIAZBgAJqQcsdEBoiBygCCDYCmAIgBiAHKQIANwOQAiAHQgA3AgAgB0EANgIIIAsgBigCkAIgBkGQAmogBi0AmwIiB8BBAEgiCBsgBigClAIgByAIGxAbGiAGLACbAkEASARAIAYoApACEBkLIAYsAIsCQQBIBEAgBigCgAIQGQsgBiwAD0EASARAIAYoAgQQGQsgBiwA+wFBAEgEQCAGKALwARAZCyAGLADrAUEASARAIAYoAuABEBkLIAYsABtBAEgEQCAGKAIQEBkLIAYsANsBQQBIBEAgBigC0AEQGQsgBiwAywFBAEgEQCAGKALAARAZCyAGLAAnQQBIBEAgBigCHBAZCyAGLAC7AUEASARAIAYoArABEBkLIAYsAKsBQQBIBEAgBigCoAEQGQsgBiwAmwFBAEgEQCAGKAKQARAZCyAGLACLAUEASARAIAYoAoABEBkLIAYsAHtBAEgEQCAGKAJwEBkLIAYsAGtBAEgEQCAGKAJgEBkLIAYsADNBAEgEQCAGKAIoEBkLIAYsAFtBAEgEQCAGKAJQEBkLIAYsAEtBAEgEQCAGKAJAEBkLIAYsAD9BAEgEQCAGKAI0EBkLIAYsAO8DQQBIBEAgBigC5AMQGQsgBiwA+wNBAE4NACAGKALwAxAZCwJAIANEAAAAAAAAAABkRQ0AIAZB5ANqIgcgA0TNzMzMzMzcP6JEmpmZmZmZuT+gECEgBiAHQcEZECUiBygCCDYC+AMgBiAHKQIANwPwAyAHQgA3AgAgB0EANgIIIAYgBkHwA2pB6ykQGiIHKAIINgKoAiAGIAcpAgA3A6ACIAdCADcCACAHQQA2AgggCyAGKAKgAiAGQaACaiAGLQCrAiIHwEEASCIIGyAGKAKkAiAHIAgbEBsaIAYsAKsCQQBIBEAgBigCoAIQGQsgBiwA+wNBAEgEQCAGKALwAxAZCyAGLADvA0EATg0AIAYoAuQDEBkLAkAgAkQAAAAAAAAAAGRFDQAgBkHkA2oiByACRLgehetRuL4/ohAhIAYgB0GBFRAlIgcoAgg2AvgDIAYgBykCADcD8AMgB0IANwIAIAdBADYCCCAGIAZB8ANqQdssEBoiBygCCDYCqAIgBiAHKQIANwOgAiAHQgA3AgAgB0EANgIIIAsgBigCoAIgBkGgAmogBi0AqwIiB8BBAEgiCxsgBigCpAIgByALGxAbGiAGLACrAkEASARAIAYoAqACEBkLIAYsAPsDQQBIBEAgBigC8AMQGQsgBiwA7wNBAE4NACAGKALkAxAZCyAGQYAEaiQAIAAsADdBAEgEQCAAKAIsEBkLIAAgCSkCNDcCLCAAIAkoAjw2AjQgCUFAayQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgJEIAJBEGokAAs3AQF/IwBBEGsiAiQAIAIgASgCRDYCCCAAQZzQACACQQhqEAc2AgQgAEHU1QA2AgAgAkEQaiQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgJAIAJBEGokAAs3AQF/IwBBEGsiAiQAIAIgASgCQDYCCCAAQZzQACACQQhqEAc2AgQgAEHU1QA2AgAgAkEQaiQAC2ACAX8BfCMAQRBrIgIkACACQQA2AgwgASgCBEGc0AAgAkEMahAJIQMgAigCDCIBBEAgARABCyAAAn8gA5lEAAAAAAAA4EFjBEAgA6oMAQtBgICAgHgLNgI8IAJBEGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(qe=re,re=I.locateFile?I.locateFile(qe,f):f+qe);var Fi=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function To($){this.excPtr=$,this.ptr=$-24,this.set_type=function(K){TA[this.ptr+4>>2]=K},this.get_type=function(){return TA[this.ptr+4>>2]},this.set_destructor=function(K){TA[this.ptr+8>>2]=K},this.get_destructor=function(){return TA[this.ptr+8>>2]},this.set_caught=function(K){K=K?1:0,lA[this.ptr+12|0]=K},this.get_caught=function(){return lA[this.ptr+12|0]!=0},this.set_rethrown=function(K){K=K?1:0,lA[this.ptr+13|0]=K},this.get_rethrown=function(){return lA[this.ptr+13|0]!=0},this.init=function(K,vA){this.set_adjusted_ptr(0),this.set_type(K),this.set_destructor(vA)},this.set_adjusted_ptr=function(K){TA[this.ptr+16>>2]=K},this.get_adjusted_ptr=function(){return TA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(ba(this.get_type()))return TA[this.excPtr>>2];var K=this.get_adjusted_ptr();return K!==0?K:this.excPtr}}var io,Eo,Vs,ki=$=>{for(var K="",vA=$;sA[vA];)K+=io[sA[vA++]];return K},ns={},jo={},Ao={},Zt=$=>{throw new Eo($)},oo=$=>{throw new Vs($)},bi=($,K,vA)=>{function qA(Fe){var rt=vA(Fe);rt.length!==$.length&&oo("Mismatched type converter count");for(var Ct=0;Ct<$.length;++Ct)vs($[Ct],rt[Ct])}$.forEach(function(Fe){Ao[Fe]=K});var Ae=new Array(K.length),me=[],Pe=0;K.forEach((Fe,rt)=>{jo.hasOwnProperty(Fe)?Ae[rt]=jo[Fe]:(me.push(Fe),ns.hasOwnProperty(Fe)||(ns[Fe]=[]),ns[Fe].push(()=>{Ae[rt]=jo[Fe],++Pe===me.length&&qA(Ae)}))}),me.length===0&&qA(Ae)};function vs($,K,vA={}){if(!("argPackAdvance"in K))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(qA,Ae,me={}){var Pe=Ae.name;if(qA||Zt(`type "${Pe}" must have a positive integer typeid pointer`),jo.hasOwnProperty(qA)){if(me.ignoreDuplicateRegistrations)return;Zt(`Cannot register type '${Pe}' twice`)}if(jo[qA]=Ae,delete Ao[qA],ns.hasOwnProperty(qA)){var Fe=ns[qA];delete ns[qA],Fe.forEach(rt=>rt())}}($,K,vA)}var HA,ce=$=>{Zt($.$$.ptrType.registeredClass.name+" instance already deleted")},Ve=!1,Ot=$=>{},nt=$=>{$.count.value-=1,$.count.value===0&&(K=>{K.smartPtr?K.smartPtrType.rawDestructor(K.smartPtr):K.ptrType.registeredClass.rawDestructor(K.ptr)})($)},It=($,K,vA)=>{if(K===vA)return $;if(vA.baseClass===void 0)return null;var qA=It($,K,vA.baseClass);return qA===null?null:vA.downcast(qA)},ei={},ti=()=>Object.keys(Oi).length,be=()=>{var $=[];for(var K in Oi)Oi.hasOwnProperty(K)&&$.push(Oi[K]);return $},Ze=[],wt=()=>{for(;Ze.length;){var $=Ze.pop();$.$$.deleteScheduled=!1,$.delete()}},Nt=$=>{HA=$,Ze.length&&HA&&HA(wt)},Oi={},po=($,K)=>(K=((vA,qA)=>{for(qA===void 0&&Zt("ptr should not be undefined");vA.baseClass;)qA=vA.upcast(qA),vA=vA.baseClass;return qA})($,K),Oi[K]),No=($,K)=>(K.ptrType&&K.ptr||oo("makeClassHandle requires ptr and ptrType"),!!K.smartPtrType!=!!K.smartPtr&&oo("Both smartPtrType and smartPtr must be specified"),K.count={value:1},Go(Object.create($,{$$:{value:K}})));function so($){var K=this.getPointee($);if(!K)return this.destructor($),null;var vA=po(this.registeredClass,K);if(vA!==void 0){if(vA.$$.count.value===0)return vA.$$.ptr=K,vA.$$.smartPtr=$,vA.clone();var qA=vA.clone();return this.destructor($),qA}function Ae(){return this.isSmartPointer?No(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:K,smartPtrType:this,smartPtr:$}):No(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var me,Pe=this.registeredClass.getActualType(K),Fe=ei[Pe];if(!Fe)return Ae.call(this);me=this.isConst?Fe.constPointerType:Fe.pointerType;var rt=It(K,this.registeredClass,me.registeredClass);return rt===null?Ae.call(this):this.isSmartPointer?No(me.registeredClass.instancePrototype,{ptrType:me,ptr:rt,smartPtrType:this,smartPtr:$}):No(me.registeredClass.instancePrototype,{ptrType:me,ptr:rt})}var Go=$=>typeof FinalizationRegistry>"u"?(Go=K=>K,$):(Ve=new FinalizationRegistry(K=>{nt(K.$$)}),Ot=K=>Ve.unregister(K),(Go=K=>{var vA=K.$$;if(vA.smartPtr){var qA={$$:vA};Ve.register(K,qA,K)}return K})($));function An(){}var rn=($,K)=>Object.defineProperty(K,"name",{value:$}),Es=($,K,vA)=>{if($[K].overloadTable===void 0){var qA=$[K];$[K]=function(){return $[K].overloadTable.hasOwnProperty(arguments.length)||Zt(`Function '${vA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[K].overloadTable})!`),$[K].overloadTable[arguments.length].apply(this,arguments)},$[K].overloadTable=[],$[K].overloadTable[qA.argCount]=qA}};function an($,K,vA,qA,Ae,me,Pe,Fe){this.name=$,this.constructor=K,this.instancePrototype=vA,this.rawDestructor=qA,this.baseClass=Ae,this.getActualType=me,this.upcast=Pe,this.downcast=Fe,this.pureVirtualFunctions=[]}var Do=($,K,vA)=>{for(;K!==vA;)K.upcast||Zt(`Expected null or instance of ${vA.name}, got an instance of ${K.name}`),$=K.upcast($),K=K.baseClass;return $};function pA($,K){if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`);var vA=K.$$.ptrType.registeredClass;return Do(K.$$.ptr,vA,this.registeredClass)}function Jn($,K){var vA;if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),this.isSmartPointer?(vA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,vA),vA):0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&K.$$.ptrType.isConst&&Zt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);var qA=K.$$.ptrType.registeredClass;if(vA=Do(K.$$.ptr,qA,this.registeredClass),this.isSmartPointer)switch(K.$$.smartPtr===void 0&&Zt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:K.$$.smartPtrType===this?vA=K.$$.smartPtr:Zt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:vA=K.$$.smartPtr;break;case 2:if(K.$$.smartPtrType===this)vA=K.$$.smartPtr;else{var Ae=K.clone();vA=this.rawShare(vA,cn.toHandle(()=>Ae.delete())),$!==null&&$.push(this.rawDestructor,vA)}break;default:Zt("Unsupporting sharing policy")}return vA}function Qr($,K){if(K===null)return this.isReference&&Zt(`null is not a valid ${this.name}`),0;K.$$||Zt(`Cannot pass "${as(K)}" as a ${this.name}`),K.$$.ptr||Zt(`Cannot pass deleted object as a pointer of type ${this.name}`),K.$$.ptrType.isConst&&Zt(`Cannot convert argument of type ${K.$$.ptrType.name} to parameter type ${this.name}`);var vA=K.$$.ptrType.registeredClass;return Do(K.$$.ptr,vA,this.registeredClass)}function ds($){return this.fromWireType(TA[$>>2])}function zr($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct,Rt){this.name=$,this.registeredClass=K,this.isReference=vA,this.isConst=qA,this.isSmartPointer=Ae,this.pointeeType=me,this.sharingPolicy=Pe,this.rawGetPointee=Fe,this.rawConstructor=rt,this.rawShare=Ct,this.rawDestructor=Rt,Ae||K.baseClass!==void 0?this.toWireType=Jn:qA?(this.toWireType=pA,this.destructorFunction=null):(this.toWireType=Qr,this.destructorFunction=null)}var Pi,Rs,or=[],en=$=>{var K=or[$];return K||($>=or.length&&(or.length=$+1),or[$]=K=Pi.get($)),K},wn=($,K,vA)=>$.includes("j")?((qA,Ae,me)=>{var Pe=I["dynCall_"+qA];return me&&me.length?Pe.apply(null,[Ae].concat(me)):Pe.call(null,Ae)})($,K,vA):en(K).apply(null,vA),qt=($,K)=>{var vA,qA,Ae,me=($=ki($)).includes("j")?(vA=$,qA=K,Ae=[],function(){return Ae.length=0,Object.assign(Ae,arguments),wn(vA,qA,Ae)}):en(K);return typeof me!="function"&&Zt(`unknown function pointer with signature ${$}: ${K}`),me},yg=$=>{var K=Ea($),vA=ki(K);return yn(K),vA},On=($,K)=>{var vA=[],qA={};throw K.forEach(function Ae(me){qA[me]||jo[me]||(Ao[me]?Ao[me].forEach(Ae):(vA.push(me),qA[me]=!0))}),new Rs(`${$}: `+vA.map(yg).join([", "]))},Gn=($,K)=>{for(var vA=[],qA=0;qA<$;qA++)vA.push(TA[K+4*qA>>2]);return vA},Js=$=>{for(;$.length;){var K=$.pop();$.pop()(K)}};function pr($,K,vA,qA,Ae,me){var Pe=K.length;Pe<2&&Zt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Fe=K[1]!==null&&vA!==null,rt=!1,Ct=1;Ct($ instanceof Object||Zt(`${vA} with invalid "this": ${$}`),$ instanceof K.registeredClass.constructor||Zt(`${vA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||Zt(`cannot call emscripten binding method ${vA} on deleted object`),Do($.$$.ptr,$.$$.ptrType.registeredClass,K.registeredClass));function mr(){this.allocated=[void 0],this.freelist=[]}var mo=new mr,gn=$=>{$>=mo.reserved&&--mo.get($).refcount===0&&mo.free($)},Sl=()=>{for(var $=0,K=mo.reserved;K($||Zt("Cannot use deleted val. handle = "+$),mo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return mo.allocate({refcount:1,value:$})}}};function fr($){return this.fromWireType(cA[$>>2])}var Ls,Jc,ms,as=$=>{if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$},Ru=($,K)=>{switch(K){case 4:return function(vA){return this.fromWireType(WA[vA>>2])};case 8:return function(vA){return this.fromWireType(ue[vA>>3])};default:throw new TypeError(`invalid float width (${K}): ${$}`)}},Wa=($,K,vA)=>{switch(K){case 1:return vA?qA=>lA[qA|0]:qA=>sA[qA|0];case 2:return vA?qA=>mA[qA>>1]:qA=>IA[qA>>1];case 4:return vA?qA=>cA[qA>>2]:qA=>TA[qA>>2];default:throw new TypeError(`invalid integer width (${K}): ${$}`)}},Cs=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,sg=($,K,vA)=>{for(var qA=K+vA,Ae=K;$[Ae]&&!(Ae>=qA);)++Ae;if(Ae-K>16&&$.buffer&&Cs)return Cs.decode($.subarray(K,Ae));for(var me="";K>10,56320|1023&Ct)}}else me+=String.fromCharCode((31&Pe)<<6|Fe)}else me+=String.fromCharCode(Pe)}return me},HI=($,K)=>$?sg(sA,$,K):"",As=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,$i=($,K)=>{for(var vA=$,qA=vA>>1,Ae=qA+K/2;!(qA>=Ae)&&IA[qA];)++qA;if((vA=qA<<1)-$>32&&As)return As.decode(sA.subarray($,vA));for(var me="",Pe=0;!(Pe>=K/2);++Pe){var Fe=mA[$+2*Pe>>1];if(Fe==0)break;me+=String.fromCharCode(Fe)}return me},pc=($,K,vA)=>{if(vA===void 0&&(vA=2147483647),vA<2)return 0;for(var qA=K,Ae=(vA-=2)<2*$.length?vA/2:$.length,me=0;me>1]=Pe,K+=2}return mA[K>>1]=0,K-qA},ng=$=>2*$.length,Dg=($,K)=>{for(var vA=0,qA="";!(vA>=K/4);){var Ae=cA[$+4*vA>>2];if(Ae==0)break;if(++vA,Ae>=65536){var me=Ae-65536;qA+=String.fromCharCode(55296|me>>10,56320|1023&me)}else qA+=String.fromCharCode(Ae)}return qA},ua=($,K,vA)=>{if(vA===void 0&&(vA=2147483647),vA<4)return 0;for(var qA=K,Ae=qA+vA-4,me=0;me<$.length;++me){var Pe=$.charCodeAt(me);if(Pe>=55296&&Pe<=57343&&(Pe=65536+((1023&Pe)<<10)|1023&$.charCodeAt(++me)),cA[K>>2]=Pe,(K+=4)+4>Ae)break}return cA[K>>2]=0,K-qA},bo=$=>{for(var K=0,vA=0;vA<$.length;++vA){var qA=$.charCodeAt(vA);qA>=55296&&qA<=57343&&++vA,K+=4}return K},Zr=($,K)=>{var vA=jo[$];return vA===void 0&&Zt(K+" has unknown type "+yg($)),vA},_o=($,K,vA)=>{var qA=[],Ae=$.toWireType(qA,vA);return qA.length&&(TA[K>>2]=cn.toHandle(qA)),Ae},Hc={},Hn=[],Hs=Reflect.construct,Sg=[null,[],[]],mc=($,K)=>{var vA=Sg[$];K===0||K===10?(($===1?G:U)(sg(vA,0)),vA.length=0):vA.push(K)};(()=>{for(var $=new Array(256),K=0;K<256;++K)$[K]=String.fromCharCode(K);io=$})(),Eo=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},Vs=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(An.prototype,{isAliasOf($){if(!(this instanceof An)||!($ instanceof An))return!1;var K=this.$$.ptrType.registeredClass,vA=this.$$.ptr;$.$$=$.$$;for(var qA=$.$$.ptrType.registeredClass,Ae=$.$$.ptr;K.baseClass;)vA=K.upcast(vA),K=K.baseClass;for(;qA.baseClass;)Ae=qA.upcast(Ae),qA=qA.baseClass;return K===qA&&vA===Ae},clone(){if(this.$$.ptr||ce(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,K=Go(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return K.$$.count.value+=1,K.$$.deleteScheduled=!1,K},delete(){this.$$.ptr||ce(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Zt("Object already scheduled for deletion"),Ot(this),nt(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||ce(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&Zt("Object already scheduled for deletion"),Ze.push(this),Ze.length===1&&HA&&HA(wt),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=ti,I.getLiveInheritedInstances=be,I.flushPendingDeletes=wt,I.setDelayFunction=Nt,Object.assign(zr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:ds,deleteObject($){$!==null&&$.delete()},fromWireType:so}),Rs=I.UnboundTypeError=(Ls=Error,(ms=rn(Jc="UnboundTypeError",function($){this.name=Jc,this.message=$;var K=new Error($).stack;K!==void 0&&(this.stack=this.toString()+` -`+K.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Ls.prototype),ms.prototype.constructor=ms,ms.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},ms),Object.assign(mr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var K=this.freelist.pop()||this.allocated.length;return this.allocated[K]=$,K},free($){this.allocated[$]=void 0,this.freelist.push($)}}),mo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),mo.reserved=mo.allocated.length,I.count_emval_handles=Sl;var fn,Ga={w:($,K,vA)=>{throw new To($).init(K,vA),$},q:($,K,vA,qA,Ae)=>{},u:($,K,vA,qA)=>{vs($,{name:K=ki(K),fromWireType:function(Ae){return!!Ae},toWireType:function(Ae,me){return me?vA:qA},argPackAdvance:8,readValueFromPointer:function(Ae){return this.fromWireType(sA[Ae])},destructorFunction:null})},y:($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct,Rt,Yt,Ii)=>{Rt=ki(Rt),me=qt(Ae,me),Fe&&(Fe=qt(Pe,Fe)),Ct&&(Ct=qt(rt,Ct)),Ii=qt(Yt,Ii);var ct=(xt=>{if(xt===void 0)return"_unknown";var Ji=(xt=xt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return Ji>=48&&Ji<=57?`_${xt}`:xt})(Rt);((xt,Ji,Ki)=>{I.hasOwnProperty(xt)?(Zt(`Cannot register public name '${xt}' twice`),Es(I,xt,xt),I.hasOwnProperty(Ki)&&Zt(`Cannot register multiple overloads of a function with the same number of arguments (${Ki})!`),I[xt].overloadTable[Ki]=Ji):I[xt]=Ji})(ct,function(){On(`Cannot construct ${Rt} due to unbound types`,[qA])}),bi([$,K,vA],qA?[qA]:[],function(xt){var Ji,Ki;xt=xt[0],Ki=qA?(Ji=xt.registeredClass).instancePrototype:An.prototype;var qs=rn(Rt,function(){if(Object.getPrototypeOf(this)!==Mi)throw new Eo("Use 'new' to construct "+Rt);if(zo.constructor_body===void 0)throw new Eo(Rt+" has no accessible constructor");var xn=zo.constructor_body[arguments.length];if(xn===void 0)throw new Eo(`Tried to invoke ctor of ${Rt} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(zo.constructor_body).toString()}) parameters instead!`);return xn.apply(this,arguments)}),Mi=Object.create(Ki,{constructor:{value:qs}});qs.prototype=Mi;var zo=new an(Rt,qs,Mi,Ii,Ji,me,Fe,Ct);zo.baseClass&&(zo.baseClass.__derivedClasses===void 0&&(zo.baseClass.__derivedClasses=[]),zo.baseClass.__derivedClasses.push(zo));var Mg=new zr(Rt,zo,!0,!1,!1),sr=new zr(Rt+"*",zo,!1,!1,!1),yr=new zr(Rt+" const*",zo,!1,!0,!1);return ei[$]={pointerType:sr,constPointerType:yr},((xn,Ml,Ks)=>{I.hasOwnProperty(xn)||oo("Replacing nonexistant public symbol"),I[xn].overloadTable!==void 0&&Ks!==void 0?I[xn].overloadTable[Ks]=Ml:(I[xn]=Ml,I[xn].argCount=Ks)})(ct,qs),[Mg,sr,yr]})},x:($,K,vA,qA,Ae,me)=>{var Pe=Gn(K,vA);Ae=qt(qA,Ae),bi([],[$],function(Fe){var rt=`constructor ${(Fe=Fe[0]).name}`;if(Fe.registeredClass.constructor_body===void 0&&(Fe.registeredClass.constructor_body=[]),Fe.registeredClass.constructor_body[K-1]!==void 0)throw new Eo(`Cannot register multiple constructors with identical number of parameters (${K-1}) for class '${Fe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Fe.registeredClass.constructor_body[K-1]=()=>{On(`Cannot construct ${Fe.name} due to unbound types`,Pe)},bi([],Pe,Ct=>(Ct.splice(1,0,null),Fe.registeredClass.constructor_body[K-1]=pr(rt,Ct,null,Ae,me),[])),[]})},i:($,K,vA,qA,Ae,me,Pe,Fe,rt)=>{var Ct=Gn(vA,qA);K=(Rt=>{const Yt=(Rt=Rt.trim()).indexOf("(");return Yt!==-1?Rt.substr(0,Yt):Rt})(K=ki(K)),me=qt(Ae,me),bi([],[$],function(Rt){var Yt=`${(Rt=Rt[0]).name}.${K}`;function Ii(){On(`Cannot call ${Yt} due to unbound types`,Ct)}K.startsWith("@@")&&(K=Symbol[K.substring(2)]),Fe&&Rt.registeredClass.pureVirtualFunctions.push(K);var ct=Rt.registeredClass.instancePrototype,xt=ct[K];return xt===void 0||xt.overloadTable===void 0&&xt.className!==Rt.name&&xt.argCount===vA-2?(Ii.argCount=vA-2,Ii.className=Rt.name,ct[K]=Ii):(Es(ct,K,Yt),ct[K].overloadTable[vA-2]=Ii),bi([],Ct,function(Ji){var Ki=pr(Yt,Ji,Rt,me,Pe);return ct[K].overloadTable===void 0?(Ki.argCount=vA-2,ct[K]=Ki):ct[K].overloadTable[vA-2]=Ki,[]}),[]})},k:($,K,vA,qA,Ae,me,Pe,Fe,rt,Ct)=>{K=ki(K),Ae=qt(qA,Ae),bi([],[$],function(Rt){var Yt=`${(Rt=Rt[0]).name}.${K}`,Ii={get(){On(`Cannot access ${Yt} due to unbound types`,[vA,Pe])},enumerable:!0,configurable:!0};return Ii.set=rt?()=>On(`Cannot access ${Yt} due to unbound types`,[vA,Pe]):ct=>Zt(Yt+" is a read-only property"),Object.defineProperty(Rt.registeredClass.instancePrototype,K,Ii),bi([],rt?[vA,Pe]:[vA],function(ct){var xt=ct[0],Ji={get(){var qs=Pn(this,Rt,Yt+" getter");return xt.fromWireType(Ae(me,qs))},enumerable:!0};if(rt){rt=qt(Fe,rt);var Ki=ct[1];Ji.set=function(qs){var Mi=Pn(this,Rt,Yt+" setter"),zo=[];rt(Ct,Mi,Ki.toWireType(zo,qs)),Js(zo)}}return Object.defineProperty(Rt.registeredClass.instancePrototype,K,Ji),[]}),[]})},t:($,K)=>{vs($,{name:K=ki(K),fromWireType:vA=>{var qA=cn.toValue(vA);return gn(vA),qA},toWireType:(vA,qA)=>cn.toHandle(qA),argPackAdvance:8,readValueFromPointer:fr,destructorFunction:null})},p:($,K,vA)=>{vs($,{name:K=ki(K),fromWireType:qA=>qA,toWireType:(qA,Ae)=>Ae,argPackAdvance:8,readValueFromPointer:Ru(K,vA),destructorFunction:null})},g:($,K,vA,qA,Ae)=>{K=ki(K);var me=rt=>rt;if(qA===0){var Pe=32-8*vA;me=rt=>rt<>>Pe}var Fe=K.includes("unsigned");vs($,{name:K,fromWireType:me,toWireType:Fe?function(rt,Ct){return this.name,Ct>>>0}:function(rt,Ct){return this.name,Ct},argPackAdvance:8,readValueFromPointer:Wa(K,vA,qA!==0),destructorFunction:null})},a:($,K,vA)=>{var qA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][K];function Ae(me){var Pe=TA[me>>2],Fe=TA[me+4>>2];return new qA(lA.buffer,Fe,Pe)}vs($,{name:vA=ki(vA),fromWireType:Ae,argPackAdvance:8,readValueFromPointer:Ae},{ignoreDuplicateRegistrations:!0})},o:($,K)=>{var vA=(K=ki(K))==="std::string";vs($,{name:K,fromWireType(qA){var Ae,me=TA[qA>>2],Pe=qA+4;if(vA)for(var Fe=Pe,rt=0;rt<=me;++rt){var Ct=Pe+rt;if(rt==me||sA[Ct]==0){var Rt=HI(Fe,Ct-Fe);Ae===void 0?Ae=Rt:(Ae+="\0",Ae+=Rt),Fe=Ct+1}}else{var Yt=new Array(me);for(rt=0;rt{for(var Ii=0,ct=0;ct=55296&&xt<=57343?(Ii+=4,++ct):Ii+=3}return Ii})(Ae):Ae.length;var Fe=fs(4+me+1),rt=Fe+4;if(TA[Fe>>2]=me,vA&&Pe)((Yt,Ii,ct,xt)=>{if(!(xt>0))return 0;for(var Ji=ct,Ki=ct+xt-1,qs=0;qs=55296&&Mi<=57343&&(Mi=65536+((1023&Mi)<<10)|1023&Yt.charCodeAt(++qs)),Mi<=127){if(ct>=Ki)break;Ii[ct++]=Mi}else if(Mi<=2047){if(ct+1>=Ki)break;Ii[ct++]=192|Mi>>6,Ii[ct++]=128|63&Mi}else if(Mi<=65535){if(ct+2>=Ki)break;Ii[ct++]=224|Mi>>12,Ii[ct++]=128|Mi>>6&63,Ii[ct++]=128|63&Mi}else{if(ct+3>=Ki)break;Ii[ct++]=240|Mi>>18,Ii[ct++]=128|Mi>>12&63,Ii[ct++]=128|Mi>>6&63,Ii[ct++]=128|63&Mi}}Ii[ct]=0})(Ae,sA,rt,me+1);else if(Pe)for(var Ct=0;Ct255&&(yn(rt),Zt("String has UTF-16 code units that do not fit in 8 bits")),sA[rt+Ct]=Rt}else for(Ct=0;Ct{var qA,Ae,me,Pe,Fe;vA=ki(vA),K===2?(qA=$i,Ae=pc,Pe=ng,me=()=>IA,Fe=1):K===4&&(qA=Dg,Ae=ua,Pe=bo,me=()=>TA,Fe=2),vs($,{name:vA,fromWireType:rt=>{for(var Ct,Rt=TA[rt>>2],Yt=me(),Ii=rt+4,ct=0;ct<=Rt;++ct){var xt=rt+4+ct*K;if(ct==Rt||Yt[xt>>Fe]==0){var Ji=qA(Ii,xt-Ii);Ct===void 0?Ct=Ji:(Ct+="\0",Ct+=Ji),Ii=xt+K}}return yn(rt),Ct},toWireType:(rt,Ct)=>{typeof Ct!="string"&&Zt(`Cannot pass non-string to C++ string type ${vA}`);var Rt=Pe(Ct),Yt=fs(4+Rt+K);return TA[Yt>>2]=Rt>>Fe,Ae(Ct,Yt+4,Rt+K),rt!==null&&rt.push(yn,Yt),Yt},argPackAdvance:8,readValueFromPointer:fr,destructorFunction(rt){yn(rt)}})},v:($,K)=>{vs($,{isVoid:!0,name:K=ki(K),argPackAdvance:0,fromWireType:()=>{},toWireType:(vA,qA)=>{}})},j:($,K,vA)=>($=cn.toValue($),K=Zr(K,"emval::as"),_o(K,vA,$)),e:($,K,vA,qA,Ae)=>{var me,Pe;return($=Hn[$])(K=cn.toValue(K),K[vA=(Pe=Hc[me=vA])===void 0?ki(me):Pe],qA,Ae)},d:gn,f:($,K,vA)=>{var qA=((Ct,Rt)=>{for(var Yt=new Array(Ct),Ii=0;Ii>2],"parameter "+Ii);return Yt})($,K),Ae=qA.shift();$--;var me,Pe,Fe=new Array($),rt=`methodCaller<(${qA.map(Ct=>Ct.name).join(", ")}) => ${Ae.name}>`;return me=rn(rt,(Ct,Rt,Yt,Ii)=>{for(var ct=0,xt=0;xt<$;++xt)Fe[xt]=qA[xt].readValueFromPointer(Ii+ct),ct+=qA[xt].argPackAdvance;var Ji=vA===1?Hs(Rt,Fe):Rt.apply(Ct,Fe);for(xt=0;xt<$;++xt)qA[xt].deleteObject&&qA[xt].deleteObject(Fe[xt]);return _o(Ae,Yt,Ji)}),Pe=Hn.length,Hn.push(me),Pe},c:$=>{$>4&&(mo.get($).refcount+=1)},b:$=>{var K=cn.toValue($);Js(K),gn($)},h:($,K)=>{var vA=($=Zr($,"_emval_take_value")).readValueFromPointer(K);return cn.toHandle(vA)},m:()=>{Et("")},s:($,K,vA)=>sA.copyWithin($,K,K+vA),r:$=>{sA.length,Et("OOM")},n:($,K,vA,qA)=>{for(var Ae=0,me=0;me>2],Fe=TA[K+4>>2];K+=8;for(var rt=0;rt>2]=Ae,0}},In=function(){var $={a:Ga};function K(vA,qA){var Ae,me;return In=vA.exports,_=In.z,Ae=_.buffer,I.HEAP8=lA=new Int8Array(Ae),I.HEAP16=mA=new Int16Array(Ae),I.HEAPU8=sA=new Uint8Array(Ae),I.HEAPU16=IA=new Uint16Array(Ae),I.HEAP32=cA=new Int32Array(Ae),I.HEAPU32=TA=new Uint32Array(Ae),I.HEAPF32=WA=new Float32Array(Ae),I.HEAPF64=ue=new Float64Array(Ae),Pi=In.C,me=In.A,Qe.unshift(me),function(){if(Mt--,I.monitorRunDependencies&&I.monitorRunDependencies(Mt),Mt==0&&jt){var Pe=jt;jt=null,Pe()}}(),In}if(Mt++,I.monitorRunDependencies&&I.monitorRunDependencies(Mt),I.instantiateWasm)try{return I.instantiateWasm($,K)}catch(vA){U(`Module.instantiateWasm callback failed with error: ${vA}`),l(vA)}return gt(0,re,$,function(vA){K(vA.instance)}).catch(l),{}}(),fs=$=>(fs=In.B)($),Ea=$=>(Ea=In.D)($),yn=$=>(yn=In.E)($),ba=$=>(ba=In.F)($);I.dynCall_jiji=($,K,vA,qA,Ae)=>(I.dynCall_jiji=In.G)($,K,vA,qA,Ae),I._vertexShaderSource=10688;function Sa(){function $(){fn||(fn=!0,I.calledRun=!0,Ce||(Fi(Qe),r(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)je(I.postRun.shift());Fi(ut)}()))}Mt>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)ft(I.preRun.shift());Fi(xe)}(),Mt>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(jt=function $(){fn||Sa(),fn||(jt=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Sa(),i.ready}})(),icA=tcA,Vj=0,SX=class MX{constructor(i){this.core=i,UL(this,"seq"),UL(this,"_core"),UL(this,"log"),UL(this,"beautyParams"),Vj+=1,this.seq=Vj,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${Vj}`}),this.log.info("created")}getName(){return MX.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return AcA(this._core);case"stop":return ecA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await icA()),this._core.room.videoManager.renderMode="webgl";const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,l=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:l,ruddy:I})}async update(i){const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,l=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:l,ruddy:I})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};UL(SX,"Name","BasicBeauty");var vX=SX,ocA=vX;const scA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:vX,default:ocA},Symbol.toStringTag,{value:"Module"})),ncA=kU(scA);var rcA=Object.defineProperty,acA=(t,i,r)=>i in t?rcA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,nY=(t,i,r)=>acA(t,typeof i!="symbol"?i+"":i,r),gcA={name:"option",required:!0,properties:{sourceLanguage:{type:"string",required:!0},translationLanguages:{type:["string","array"],required:!1},userIdsToTranscribe:{type:["string","array"],required:!1},transcriberRobotId:{type:"string",required:!1}}},ccA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},lcA=new Set([2002,4003]),RX=class wX{constructor(i){this.core=i,nY(this,"disableRandomCall",!0),nY(this,"activeTranscriberMap",new Map),nY(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return wX.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return gcA;case"update":return{};case"stop":return ccA}}async start(i){var r;const{RtcError:l,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new l({code:I.ENV_NOT_SUPPORTED});const{sourceLanguage:h,translationLanguages:f,userIdsToTranscribe:w="all",transcriberRobotId:_}=i,G=_||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,U={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:G,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:h,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};f&&f.length>0&&(U.translationParams.mode=1,U.translationParams.targetLangs=Array.isArray(f)?f:[f]),w==="all"?U.subscribeParams.subUsers=[]:Array.isArray(w)?U.subscribeParams.subUsers=w.map(j=>({userId:j,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):w&&(U.subscribeParams.subUsers=[{userId:w,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(U)}`);const j=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:U,retries:0}),{code:lA,data:sA}=j.data;if(lA!==0){const IA=((r=j.data)==null?void 0:r.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:lA,reason:IA,data:sA}),new l({code:I.SERVER_ERROR,extraCode:lA,message:IA})}const{taskId:mA}=sA;if(!mA)throw this._log.error("taskId is required",{data:j.data}),new l({code:I.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(mA,i),this._log.info(`start_cloud_transcription success ${mA}, activeSize: ${this.activeTranscriberMap.size}`),mA}catch(j){throw this._log.error("start_cloud_transcription failed",{error:j}),j}}async update(){}async stop({transcriberRobotId:i}){var r;const{RtcError:l,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new l({code:I.ENV_NOT_SUPPORTED});try{const h=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(h.data.code!==0){const f=h.data.code,w=((r=h.data)==null?void 0:r.message)||"";if(!lcA.has(f))throw this._log.error("stop_cloud_transcription failed",{extraCode:f,reason:w,data:h.data.data}),new l({code:I.SERVER_ERROR,extraCode:f,message:w});this._log.warn("stop_cloud_transcription ignored error",{extraCode:f,reason:w,data:h.data.data})}this.activeTranscriberMap.delete(i)}catch(h){throw this._log.error("stop_cloud_transcription failed",{error:h}),h}}destroy(){this.activeTranscriberMap.clear()}};nY(RX,"Name","RealtimeTranscriber");var _X=RX,IcA=_X;const ucA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:_X,default:IcA},Symbol.toStringTag,{value:"Module"})),EcA=kU(ucA);var dcA=Object.create,FU=Object.defineProperty,CcA=Object.defineProperties,TX=Object.getOwnPropertyDescriptor,hcA=Object.getOwnPropertyDescriptors,NX=Object.getOwnPropertyNames,DY=Object.getOwnPropertySymbols,BcA=Object.getPrototypeOf,HW=Object.prototype.hasOwnProperty,GX=Object.prototype.propertyIsEnumerable,P3=(t,i,r)=>i in t?FU(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,Rn=(t,i)=>{for(var r in i||(i={}))HW.call(i,r)&&P3(t,r,i[r]);if(DY)for(var r of DY(i))GX.call(i,r)&&P3(t,r,i[r]);return t},nB=(t,i)=>CcA(t,hcA(i)),QcA=(t,i)=>{var r={};for(var l in t)HW.call(t,l)&&i.indexOf(l)<0&&(r[l]=t[l]);if(t!=null&&DY)for(var l of DY(t))i.indexOf(l)<0&&GX.call(t,l)&&(r[l]=t[l]);return r},OU=(t,i)=>function(){return i||(0,t[NX(t)[0]])((i={exports:{}}).exports,i),i.exports},qW=(t,i)=>{for(var r in i)FU(t,r,{get:i[r],enumerable:!0})},pcA=(t,i,r,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of NX(i))HW.call(t,I)||I===r||FU(t,I,{get:()=>i[I],enumerable:!(l=TX(i,I))||l.enumerable});return t},dT=(t,i,r)=>(r=t!=null?dcA(BcA(t)):{},pcA(FU(r,"default",{value:t,enumerable:!0}),t)),Cc=(t,i,r,l)=>{for(var I,h=TX(i,r),f=t.length-1;f>=0;f--)(I=t[f])&&(h=I(i,r,h)||h);return h&&FU(i,r,h),h},de=(t,i,r)=>P3(t,typeof i!="symbol"?i+"":i,r),PU=OU({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,l="~";function I(){}function h(G,U,j){this.fn=G,this.context=U,this.once=j||!1}function f(G,U,j,lA,sA){if(typeof j!="function")throw new TypeError("The listener must be a function");var mA=new h(j,lA||G,sA),IA=l?l+U:U;return G._events[IA]?G._events[IA].fn?G._events[IA]=[G._events[IA],mA]:G._events[IA].push(mA):(G._events[IA]=mA,G._eventsCount++),G}function w(G,U){--G._eventsCount===0?G._events=new I:delete G._events[U]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(l=!1)),_.prototype.eventNames=function(){var G,U,j=[];if(this._eventsCount===0)return j;for(U in G=this._events)r.call(G,U)&&j.push(l?U.slice(1):U);return Object.getOwnPropertySymbols?j.concat(Object.getOwnPropertySymbols(G)):j},_.prototype.listeners=function(G){var U=l?l+G:G,j=this._events[U];if(!j)return[];if(j.fn)return[j.fn];for(var lA=0,sA=j.length,mA=new Array(sA);lA1&&(f[_[0]]=void 0),f};t.parseParams=function(f){return f.split(/;\s?/).reduce(h,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(f){return f.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(f){for(var w=[],_=f.split(" ").map(i),G=0;G<_.length;G+=3)w.push({component:_[G],ip:_[G+1],port:_[G+2]});return w},t.parseImageAttributes=function(f){return f.split(" ").map(function(w){return w.substring(1,w.length-1).split(",").reduce(h,{})})},t.parseSimulcastStreamList=function(f){return f.split(";").map(function(w){return w.split(",").map(function(_){var G,U=!1;return _[0]!=="~"?G=i(_):(G=i(_.substring(1,_.length)),U=!0),{scid:G,paused:U}})})}}}),fcA=OU({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(t,i){var r=KW(),l=/%[sdv%]/g,I=function(_){var G=1,U=arguments,j=U.length;return _.replace(l,function(lA){if(G>=j)return lA;var sA=U[G];switch(G+=1,lA){case"%%":return"%";case"%s":return String(sA);case"%d":return Number(sA);case"%v":return""}})},h=function(_,G,U){var j=[_+"="+(G.format instanceof Function?G.format(G.push?U:U[G.name]):G.format)];if(G.names)for(var lA=0;lA{i.enableVertexAttribArray(c),i.bindBuffer(i.ARRAY_BUFFER,n),i.vertexAttribPointer(c,2,i.FLOAT,!1,0,0)})}createShader(t,i){const{gl:n}=this,c=n.createShader(t);return n.shaderSource(c,i),n.compileShader(c),c}createProgram(t,i,n){const{gl:c}=this,I=this.createShader(c.FRAGMENT_SHADER,i),C=this.createShader(c.VERTEX_SHADER,t),f=c.createProgram();if(c.attachShader(f,C),c.attachShader(f,I),c.linkProgram(f),!c.getProgramParameter(f,c.LINK_STATUS))throw new Error(`${c.getProgramInfoLog(f)}`);return c.useProgram(f),this.setAttributes(this.positionBuffer,this.texCoordBuffer),n.forEach((w,_)=>{c.uniform1i(c.getUniformLocation(f,w),1+_)}),f}createFramebuffer(t){const{gl:i}=this,n=i.createFramebuffer();return i.bindFramebuffer(i.FRAMEBUFFER,n),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t,0),n}getTempTexture(t,i,n=!0,c){const{gl:I}=this;let C,f;I.useProgram(t),this.ratio===16/9?(C=640,f=360):(C=640,f=480);const w=I.createTexture();I.activeTexture(I.TEXTURE0),I.bindTexture(I.TEXTURE_2D,w),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MIN_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_MAG_FILTER,I.LINEAR),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_S,I.CLAMP_TO_EDGE),I.texParameteri(I.TEXTURE_2D,I.TEXTURE_WRAP_T,I.CLAMP_TO_EDGE),I.pixelStorei(I.PACK_ALIGNMENT,1),I.pixelStorei(I.UNPACK_ALIGNMENT,1),I.texImage2D(I.TEXTURE_2D,0,I.RGBA,C,f,0,I.RGBA,I.UNSIGNED_BYTE,null);const _=this.createFramebuffer(w);return i.forEach((N,L)=>{N&&(I.activeTexture(I.TEXTURE1+L),I.bindTexture(I.TEXTURE_2D,N||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),I.viewport(0,0,C,f),I.drawArrays(I.TRIANGLE_STRIP,0,4),n&&i.forEach((N,L)=>{N&&c!==L&&I.deleteTexture(N)}),I.deleteFramebuffer(_),w}postProcessing(t){this._lastMaskTexture=this.getTempTexture(this._tdProgram,[t,this._lastMaskTexture]);let i=this.getTempTexture(this._kcProgram,[this._lastMaskTexture],!1);for(let n=0;n<3;n++){i=this.getTempTexture(this._mdProgram,[i]);const c=this.getTempTexture(this._edgeProgram,[i],!1);i=this.getTempTexture(this._borderProgram,[i,c,this._lastMaskTexture],!0,2)}return i}close(){const{gl:t}=this;this._borderProgram&&t.deleteProgram(this._borderProgram),this._edgeProgram&&t.deleteProgram(this._edgeProgram),this._kcProgram&&t.deleteProgram(this._kcProgram),this._mdProgram&&t.deleteProgram(this._mdProgram),this._tdProgram&&t.deleteProgram(this._tdProgram)}},fcA=new mcA,ycA=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(ycA||{}),DcA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},M_=570703,i3=0,HX=class qX{constructor(i){this.core=i,Hg(this,"seq"),Hg(this,"_core"),Hg(this,"log"),Hg(this,"preLoadPromise"),Hg(this,"startResolve"),Hg(this,"startReject"),Hg(this,"mediaPipeSolutions"),Hg(this,"assetsPath"),Hg(this,"currentType"),Hg(this,"onAbort"),Hg(this,"isAborted",!1),i3+=1,this.seq=i3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${i3}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(mgA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",DcA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await ZaA());const n=c=>{var I;this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!1,this.isAborted,"ABORT_IN_INFERENCE")}),this.isAborted=!0,this.log.error("mediaPipeSolutions abort",c),this.core.clearStarted(this,this.getGroup()),this.stop(),(I=this.onAbort)==null||I.call(this,c)};this._core.room.videoManager.initVirtualBackground(n,UX,fcA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(n){const{RtcError:c,ErrorCode:I}=this._core.errorModule;throw new c({code:I.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${n}`})}}getName(){return qX.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return KaA(this._core);case"update":return jaA(this._core);case"stop":return WaA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,n=!1,c="NONE"){let I=0;switch(this.currentType){case"blur":I|=0;break;case"image":I|=1;break;case"color":I|=2}switch(i&&(I|=256),n&&(I|=512),c){case"ABORT_IN_INFERENCE":I|=4096;break;case"ABORT_IN_VIDEO_MANAGER":I|=8192;break;case"OTHER":I|=61440}return I}hexToRgb(i){const n=i.replace("#","");return[parseInt(n.slice(0,2),16)/255,parseInt(n.slice(2,4),16)/255,parseInt(n.slice(4,6),16)/255]}async start(i){const{type:n="blur",src:c,blurLevel:I=3,onAbort:C}=i;this.currentType=n,this.onAbort=C,n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:f}=await HaA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:w,ErrorCodeDictionary:_,ErrorCode:N}=this._core.errorModule;if(!f){const L=this._core.utils.isOverseaSdkAppId(i.sdkAppId)?"https://trtc.io/document/56025":"https://cloud.tencent.com/document/product/647/85386";throw new w({code:_.NEED_TO_BUY,messageParams:{value:"Virtual Background",url:L}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new w({code:N.INVALID_PARAMETER,message:"you need to deploy the assets of the npm package and set assetsPath param in TRTC.create()"});this.preLoadPromise=this.preload(this._core.assetsPath)}return await this.preLoadPromise,this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:I,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:L=>{var q;this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!0,this.isAborted,"ABORT_IN_VIDEO_MANAGER")}),this.isAborted=!0,this.core.clearStarted(this,this.getGroup()),this.stop(),delete this.preLoadPromise,(q=this.onAbort)==null||q.call(this,L)}}).then(()=>{this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(L=>{throw this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),L})}async update(i){const{type:n,src:c}=i;return n!==this.currentType&&(this.currentType=n),n==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color)),this.core.room.videoManager.setVirtualBackground({type:n,imageUrl:c,blurLevel:i.blurLevel,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color}).then(()=>{this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:M_,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Hg(HX,"Name","VirtualBackground");var KX=HX,ScA=KX;const McA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:KX,default:ScA},Symbol.toStringTag,{value:"Module"})),vcA=HU(McA);var RcA=Object.defineProperty,wcA=(t,i,n)=>i in t?RcA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,VL=(t,i,n)=>wcA(t,typeof i!="symbol"?i+"":i,n);function _cA(t){return{name:"BasicBeautyOptions",type:"object",required:!0,allowEmpty:!1,properties:{beauty:{required:!1,type:"number"},brightness:{required:!1,type:"number"},ruddy:{required:!1,type:"number"}},validate(i,n,c,I){const{RtcError:C,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(t.utils.isOverseaSdkAppId(i.sdkAppId))throw new C({code:f.INVALID_OPERATION,extraCode:w.INVALID_OPERATION,message:"This feature is not yet available in your country or region. If you have any questions, you can go to the community for consultation: https://zhiliao.qq.com/s/cWSPGIIM62CC/c3TPGIIM62CQ"})}}}function TcA(t){return{name:"StopBasicBeautyOptions",required:!1}}var NcA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var n,c,I=i;I.ready=new Promise(($,j)=>{n=$,c=j});var C=Object.assign({},I),f="";typeof document<"u"&&document.currentScript&&(f=document.currentScript.src),t&&(f=t),f=f.indexOf("blob:")!==0?f.substr(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,N=I.print||console.log.bind(console),L=I.printErr||console.error.bind(console);function q($){if(ti($))return function(j){for(var vA=atob(j),jA=new Uint8Array(vA.length),oe=0;oe$.startsWith(Dt);function Pt($){return Promise.resolve().then(()=>function(j){if(j==ce&&w)return new Uint8Array(w);var vA=q(j);if(vA)return vA;throw"both async and sync fetching of the wasm failed"}($))}function oi($,j,vA,jA){return function(oe,ye,He){return Pt(oe).then(Pe=>WebAssembly.instantiate(Pe,ye)).then(Pe=>Pe).then(He,Pe=>{L(`failed to asynchronously prepare wasm: ${Pe}`),ct(Pe)})}(j,vA,jA)}ti(ce="data:application/octet-stream;base64,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IAEoAgA2AgAgAiABKAIENgIEIAIgASgCCDYCCCACIAEoAgw2AgwgAiABKAIQNgIQIAIgASgCFDYCFCACIAEoAhg2AhggAiABKAIcNgIcIAIgASgCIDYCICACIAEoAiQ2AiQgAiABKAIoNgIoIAIgASgCLDYCLCACIAEoAjA2AjAgAiABKAI0NgI0IAIgASgCODYCOCACIAEoAjw2AjwgAUFAayEBIAJBQGsiAiAFTQ0ACwsgAiAETw0BA0AgAiABKAIANgIAIAFBBGohASACQQRqIgIgBEkNAAsMAQsgA0EESQRAIAAhAgwBCyAAIANBBGsiBEsEQCAAIQIMAQsgACECA0AgAiABLQAAOgAAIAIgAS0AAToAASACIAEtAAI6AAIgAiABLQADOgADIAFBBGohASACQQRqIgIgBE0NAAsLIAIgA0kEQANAIAIgAS0AADoAACABQQFqIQEgAkEBaiICIANHDQALCyAACwsAIAEgAiAAEEIaCxIAIAFBAXRB8MoAakECIAAQQgv5AQEEfwJ/IAEQKiECIwBBEGsiBSQAAn8gAC0AC0EHdgRAIAAoAgQMAQsgAC0AC0H/AHELIgRBAE8EQAJAIAIgAC0AC0EHdgR/IAAoAghB/////wdxQQFrBUEKCyIDIARrTQRAIAJFDQECfyAALQALQQd2BEAgACgCAAwBCyAACyIDIAQEfyACIANqIAMgBBBFIAEgAkEAIAMgBGogAUsbQQAgASADTxtqBSABCyACEEUgACACIARqIgEQMSAFQQA6AA8gASADaiAFLQAPOgAADAELIAAgAyACIARqIANrIARBACACIAEQRAsgBUEQaiQAIAAMAQsQJwALC/ICAgJ/AX4CQCACRQ0AIAAgAToAACAAIAJqIgNBAWsgAToAACACQQNJDQAgACABOgACIAAgAToAASADQQNrIAE6AAAgA0ECayABOgAAIAJBB0kNACAAIAE6AAMgA0EEayABOgAAIAJBCUkNACAAQQAgAGtBA3EiBGoiAyABQf8BcUGBgoQIbCIBNgIAIAMgAiAEa0F8cSIEaiICQQRrIAE2AgAgBEEJSQ0AIAMgATYCCCADIAE2AgQgAkEIayABNgIAIAJBDGsgATYCACAEQRlJDQAgAyABNgIYIAMgATYCFCADIAE2AhAgAyABNgIMIAJBEGsgATYCACACQRRr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ACACQQA6AA8DQCABBEAgACACLQAPOgAAIAFBAWshASAAQQFqIQAMAQsLIAJBEGokAAsaACAALQALQQd2BEAgACgCCBogACgCABAZCwvmAQEFfyMAQRBrIgUkACMAQSBrIgMkACMAQRBrIgQkACAEIAA2AgwgBCAAIAFqNgIIIAMgBCgCDDYCGCADIAQoAgg2AhwgBEEQaiQAIAMoAhghBCADKAIcIQYjAEEQayIBJAAgASAGNgIMIAIgBCAGIARrIgQQQyABIAIgBGo2AgggAyABKAIMNgIQIAMgASgCCDYCFCABQRBqJAAgAyAAIAMoAhAgAGtqNgIMIAMgAiADKAIUIAJrajYCCCAFIAMoAgw2AgggBSADKAIINgIMIANBIGokACAFKAIMIQcgBUEQaiQAIAcLDwAgAgRAIAAgASACEDILC/UCAQV/IwBBEGsiByQAIAIgAUF/c0Hv////B2pNBEACfyAALQALQQd2BEAgACgCAAwBCyAACyEIIAdBBGoiCSAAIAFB5////wNJBH8gByABQQF0NgIMIAcgASACajYCBCMAQRBrIgIkACAJKAIAIAdBDGoiCigCAEkhCyACQRBqJAAgCiAJIAsbKAIAIgJBC08EfyACQRBqQXBxIgIgAkEBayICIAJBC0YbBUEKC0EBagVB7////wcLEDAgBygCBCECIAcoAggaIAQEQCACIAggBBAjCyAFBEAgAiAEaiAGIAUQIwsgAyAEayEGIAMgBEcEQCACIARqIAVqIAQgCGogBhAjCyABQQpHBEAgCBAZCyAAIAI2AgAgACAAKAIIQYCAgIB4cSAHKAIIQf////8HcXI2AgggACAAKAIIQYCAgIB4cjYCCCAAIAQgBWogBmoiADYCBCAHQQA6AAwgACACaiAHLQAMOgAAIAdBEGokAA8LECcACwoAIAAgASACEEMLuQEBBH8jAEEQayIEJAAgBCACNgIMIwBBoAFrIgMkACADIAAgA0GeAWogARsiBjYClAFBfyEFIAMgAUEBayIAQQAgACABTRs2ApgBIANBAEGQARAmIgBBfzYCTCAAQSA2AiQgAEF/NgJQIAAgAEGfAWo2AiwgACAAQZQBajYCVAJAIAFBAEgEQEHo3gBBPTYCAAwBCyAGQQA6AAAgAEH9CiACQR8QTSEFCyAAQaABaiQAIARBEGokACAFCwQAIAALmQIAIABFBEBBAA8LAn8CQCAABH8gAUH/AE0NAQJAQbTWACgCACgCAEUEQCABQYB/cUGAvwNGDQMMAQsgAUH/D00EQCAAIAFBP3FBgAFyOgABIAAgAUEGdkHAAXI6AABBAgwECyABQYBAcUGAwANHIAFBgLADT3FFBEAgACABQT9xQYABcjoAAiAAIAFBDHZB4AFyOgAAIAAgAUEGdkE/cUGAAXI6AAFBAwwECyABQYCABGtB//8/TQRAIAAgAUE/cUGAAXI6AAMgACABQRJ2QfABcjoAACAAIAFBBnZBP3FBgAFyOgACIAAgAUEMdkE/cUGAAXI6AAFBBAwECwtB6N4AQRk2AgBBfwVBAQsMAQsgACABOgAAQQELC54YAxN/AXwCfiMAQbAEayIMJAAgDEEANgIsAkAgAb0iGkIAUwRAQQEhD0GUCCETIAGaIgG9IRoMAQsgBEGAEHEEQEEBIQ9BlwghEwwBC0GaCEGVCCAEQQFxIg8bIRMgD0UhFQsCQCAaQoCAgICAgID4/wCDQoCAgICAgID4/wBRBEAgAEEgIAIgD0EDaiIDIARB//97cRAfIAAgEyAPEB0gAEHLCUHVCyAFQSBxIgUbQfkKQdkLIAUbIAEgAWIbQQMQHSAAQSAgAiADIARBgMAAcxAfIAMgAiACIANIGyEJDAELIAxBEGohEgJAAn8CQCABIAxBLGoQTiIBIAGgIgFEAAAAAAAAAABiBEAgDCAMKAIsIgZBAWs2AiwgBUEgciIOQeEARw0BDAMLIAVBIHIiDkHhAEYNAiAMKAIsIQpBBiADIANBAEgbDAELIAwgBkEdayIKNgIsIAFEAAAAAAAAsEGiIQFBBiADIANBAEgbCyELIAxBMGpBoAJBACAKQQBOG2oiDSEHA0AgBwJ/IAFEAAAAAAAA8EFjIAFEAAAAAAAAAABmcQRAIAGrDAELQQALIgM2AgAgB0EEaiEHIAEgA7ihRAAAAABlzc1BoiIBRAAAAAAAAAAAYg0ACwJAIApBAEwEQCAKIQMgByEGIA0hCAwBCyANIQggCiEDA0BBHSADIANBHU4bIQMCQCAHQQRrIgYgCEkNACADrSEbQgAhGgNAIAYgGkL/////D4MgBjUCACAbhnwiGiAaQoCU69wDgCIaQoCU69wDfn0+AgAgBkEEayIGIAhPDQALIBqnIgZFDQAgCEEEayIIIAY2AgALA0AgCCAHIgZJBEAgBkEEayIHKAIARQ0BCwsgDCAMKAIsIANrIgM2AiwgBiEHIANBAEoNAAsLIANBAEgEQCALQRlqQQluQQFqIRAgDkHmAEYhEQNAQQlBACADayIDIANBCU4bIQkCQCAGIAhNBEAgCCgCACEHDAELQYCU69wDIAl2IRRBfyAJdEF/cyEWQQAhAyAIIQcDQCAHIAMgBygCACIXIAl2ajYCACAWIBdxIBRsIQMgB0EEaiIHIAZJDQALIAgoAgAhByADRQ0AIAYgAzYCACAGQQRqIQYLIAwgDCgCLCAJaiIDNgIsIA0gCCAHRUECdGoiCCARGyIHIBBBAnRqIAYgBiAHa0ECdSAQShshBiADQQBIDQALC0EAIQMCQCAGIAhNDQAgDSAIa0ECdUEJbCEDQQohByAIKAIAIglBCkkNAANAIANBAWohAyAJIAdBCmwiB08NAAsLIAsgA0EAIA5B5gBHG2sgDkHnAEYgC0EAR3FrIgcgBiANa0ECdUEJbEEJa0gEQCAMQTBqQQRBpAIgCkEASBtqIAdBgMgAaiIJQQltIhFBAnRqIhBBgCBrIQpBCiEHIAkgEUEJbGsiCUEHTARAA0AgB0EKbCEHIAlBAWoiCUEIRw0ACwsCQCAKKAIAIhEgESAHbiIUIAdsayIJRSAQQfwfayIWIAZGcQ0AAkAgFEEBcUUEQEQAAAAAAABAQyEBIAdBgJTr3ANHDQEgCCAKTw0BIBBBhCBrLQAAQQFxRQ0BC0QBAAAAAABAQyEBC0QAAAAAAADgP0QAAAAAAADwP0QAAAAAAAD4PyAGIBZGG0QAAAAAAAD4PyAJIAdBAXYiFEYbIAkgFEkbIRkCQCAVDQAgEy0AAEEtRw0AIBmaIRkgAZohAQsgCiARIAlrIgk2AgAgASAZoCABYQ0AIAogByAJaiIDNgIAIANBgJTr3ANPBEADQCAKQQA2AgAgCCAKQQRrIgpLBEAgCEEEayIIQQA2AgALIAogCigCAEEBaiIDNgIAIANB/5Pr3ANLDQALCyANIAhrQQJ1QQlsIQNBCiEHIAgoAgAiCUEKSQ0AA0AgA0EBaiEDIAkgB0EKbCIHTw0ACwsgCkEEaiIHIAYgBiAHSxshBgsDQCAGIgcgCE0iCUUEQCAGQQRrIgYoAgBFDQELCwJAIA5B5wBHBEAgBEEIcSEKDAELIANBf3NBfyALQQEgCxsiBiADSiADQXtKcSIKGyAGaiELQX9BfiAKGyAFaiEFIARBCHEiCg0AQXchBgJAIAkNACAHQQRrKAIAIg5FDQBBCiEJQQAhBiAOQQpwDQADQCAGIgpBAWohBiAOIAlBCmwiCXBFDQALIApBf3MhBgsgByANa0ECdUEJbCEJIAVBX3FBxgBGBEBBACEKIAsgBiAJakEJayIGQQAgBkEAShsiBiAGIAtKGyELDAELQQAhCiALIAMgCWogBmpBCWsiBkEAIAZBAEobIgYgBiALShshCwtBfyEJIAtB/f///wdB/v///wcgCiALciIRG0oNASALIBFBAEdqQQFqIQ4CQCAFQV9xIhVBxgBGBEAgAyAOQf////8Hc0oNAyADQQAgA0EAShshBgwBCyASIAMgA0EfdSIGcyAGa60gEhApIgZrQQFMBEADQCAGQQFrIgZBMDoAACASIAZrQQJIDQALCyAGQQJrIhAgBToAACAGQQFrQS1BKyADQQBIGzoAACASIBBrIgYgDkH/////B3NKDQILIAYgDmoiAyAPQf////8Hc0oNASAAQSAgAiADIA9qIgUgBBAfIAAgEyAPEB0gAEEwIAIgBSAEQYCABHMQHwJAAkACQCAVQcYARgRAIAxBEGoiBkEIciEDIAZBCXIhCiANIAggCCANSxsiCSEIA0AgCDUCACAKECkhBgJAIAggCUcEQCAGIAxBEGpNDQEDQCAGQQFrIgZBMDoAACAGIAxBEGpLDQALDAELIAYgCkcNACAMQTA6ABggAyEGCyAAIAYgCiAGaxAdIAhBBGoiCCANTQ0ACyARBEAgAEGhEkEBEB0LIAcgCE0NASALQQBMDQEDQCAINQIAIAoQKSIGIAxBEGpLBEADQCAGQQFrIgZBMDoAACAGIAxBEGpLDQALCyAAIAZBCSALIAtBCU4bEB0gC0EJayEGIAhBBGoiCCAHTw0DIAtBCUohGCAGIQsgGA0ACwwCCwJAIAtBAEgNACAHIAhBBGogByAISxshCSAMQRBqIgZBCHIhAyAGQQlyIQ0gCCEHA0AgDSAHNQIAIA0QKSIGRgRAIAxBMDoAGCADIQYLAkAgByAIRwRAIAYgDEEQak0NAQNAIAZBAWsiBkEwOgAAIAYgDEEQaksNAAsMAQsgACAGQQEQHSAGQQFqIQYgCiALckUNACAAQaESQQEQHQsgACAGIA0gBmsiBiALIAYgC0gbEB0gCyAGayELIAdBBGoiByAJTw0BIAtBAE4NAAsLIABBMCALQRJqQRJBABAfIAAgECASIBBrEB0MAgsgCyEGCyAAQTAgBkEJakEJQQAQHwsgAEEgIAIgBSAEQYDAAHMQHyAFIAIgAiAFSBshCQwBCyATIAVBGnRBH3VBCXFqIQgCQCADQQtLDQBBDCADayEGRAAAAAAAADBAIRkDQCAZRAAAAAAAADBAoiEZIAZBAWsiBg0ACyAILQAAQS1GBEAgGSABmiAZoaCaIQEMAQsgASAZoCAZoSEBCyASIAwoAiwiBiAGQR91IgZzIAZrrSASECkiBkYEQCAMQTA6AA8gDEEPaiEGCyAPQQJyIQsgBUEgcSENIAwoAiwhByAGQQJrIgogBUEPajoAACAGQQFrQS1BKyAHQQBIGzoAACAEQQhxIQYgDEEQaiEHA0AgByIFAn8gAZlEAAAAAAAA4EFjBEAgAaoMAQtBgICAgHgLIgdBsMoAai0AACANcjoAACABIAe3oUQAAAAAAAAwQKIhAQJAIAVBAWoiByAMQRBqa0EBRw0AAkAgBg0AIANBAEoNACABRAAAAAAAAAAAYQ0BCyAFQS46AAEgBUECaiEHCyABRAAAAAAAAAAAYg0AC0F/IQlB/f///wcgCyASIAprIgZqIg1rIANIDQAgAEEgIAIgDSADQQJqIAcgDEEQaiIHayIFIAVBAmsgA0gbIAUgAxsiCWoiAyAEEB8gACAIIAsQHSAAQTAgAiADIARBgIAEcxAfIAAgByAFEB0gAEEwIAkgBWtBAEEAEB8gACAKIAYQHSAAQSAgAiADIARBgMAAcxAfIAMgAiACIANIGyEJCyAMQbAEaiQAIAkLvAIAAkACQAJAAkACQAJAAkACQAJAAkACQCABQQlrDhIACAkKCAkBAgMECgkKCggJBQYHCyACIAIoAgAiAUEEajYCACAAIAEoAgA2AgAPCyACIAIoAgAiAUEEajYCACAAIAEyAQA3AwAPCyACIAIoAgAiAUEEajYCACAAIAEzAQA3AwAPCyACIAIoAgAiAUEEajYCACAAIAEwAAA3AwAPCyACIAIoAgAiAUEEajYCACAAIAExAAA3AwAPCyACIAIoAgBBB2pBeHEiAUEIajYCACAAIAErAwA5AwAPCyAAIAIgAxEAAAsPCyACIAIoAgAiAUEEajYCACAAIAE0AgA3AwAPCyACIAIoAgAiAUEEajYCACAAIAE1AgA3AwAPCyACIAIoAgBBB2pBeHEiAUEIajYCACAAIAEpAwA3AwALcgEDfyAAKAIALAAAQTBrQQpPBEBBAA8LA0AgACgCACEDQX8hASACQcyZs+YATQRAQX8gAywAAEEwayIBIAJBCmwiAmogASACQf////8Hc0obIQELIAAgA0EBajYCACABIQIgAywAAUEwa0EKSQ0ACyACC9AUAhh/AX4jAEHQAGsiByQAIAcgATYCTCAEQcABayEXIANBgANrIRggB0E3aiEZIAdBOGohEwJAAkACQANAQQAhBgNAIAEhDCAGIBJB/////wdzSg0CIAYgEmohEgJAAkACQCABIgYtAAAiCARAA0ACQAJAIAhB/wFxIgFFBEAgBiEBDAELIAFBJUcNASAGIQgDQCAILQABQSVHBEAgCCEBDAILIAZBAWohBiAILQACIRsgCEECaiIBIQggG0ElRg0ACwsgBiAMayIGIBJB/////wdzIhpKDQggAARAIAAgDCAGEB0LIAYNBiAHIAE2AkwgAUEBaiEGQX8hDgJAIAEsAAFBMGsiCkEKTw0AIAEtAAJBJEcNACABQQNqIQYgCiEOQQEhFAsgByAGNgJMQQAhCwJAIAYsAAAiCEEgayIBQR9LBEAgBiEKDAELIAYhCkEBIAF0IgFBidEEcUUNAANAIAcgBkEBaiIKNgJMIAEgC3IhCyAGLAABIghBIGsiAUEgTw0BIAohBkEBIAF0IgFBidEEcQ0ACwsCQCAIQSpGBEAgCkEBaiEIAn8CQCAKLAABQTBrQQpPDQAgCi0AAkEkRw0AIAgsAAAhASAKQQNqIQhBASEUAn8gAEUEQCAXIAFBAnRqQQo2AgBBAAwBCyAYIAFBA3RqKAIACwwBCyAUDQYgAEUEQCAHIAg2AkxBACEUQQAhDwwDCyACIAIoAgAiAUEEajYCAEEAIRQgASgCAAshDyAHIAg2AkwgD0EATg0BQQAgD2shDyALQYDAAHIhCwwBCyAHQcwAahBLIg9BAEgNCSAHKAJMIQgLQQAhBkF/IQkCfyAILQAAQS5HBEAgCCEBQQAMAQsgCC0AAUEqRgRAIAhBAmohAQJAAkAgCCwAAkEwa0EKTw0AIAgtAANBJEcNACABLAAAIQECfyAARQRAIBcgAUECdGpBCjYCAEEADAELIBggAUEDdGooAgALIQkgCEEEaiEBDAELIBQNBiAARQRAQQAhCQwBCyACIAIoAgAiCkEEajYCACAKKAIAIQkLIAcgATYCTCAJQQBODAELIAcgCEEBajYCTCAHQcwAahBLIQkgBygCTCEBQQELIRUDQCAGIQ1BHCEQIAEiESwAACIGQfsAa0FGSQ0KIAFBAWohASAGIA1BOmxqQZ/GAGotAAAiBkEBa0EISQ0ACyAHIAE2AkwCQCAGQRtHBEAgBkUNCyAOQQBOBEAgAEUEQCAEIA5BAnRqIAY2AgAMCwsgByADIA5BA3RqKQMANwNADAILIABFDQcgB0FAayAGIAIgBRBKDAELIA5BAE4NCkEAIQYgAEUNBwtBfyEQIAAtAABBIHENCiALQf//e3EiCCALIAtBgMAAcRshC0EAIQ5BigghFiATIQoCQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQCARLAAAIgZBX3EgBiAGQQ9xQQNGGyAGIA0bIgZB2ABrDiEEFBQUFBQUFBQOFA8GDg4OFAYUFBQUAgUDFBQJFAEUFAQACwJAIAZBwQBrDgcOFAsUDg4OAAsgBkHTAEYNCQwTCyAHKQNAIR5BiggMBQtBACEGAkACQAJAAkACQAJAAkAgDUH/AXEOCAABAgMEGgUGGgsgBygCQCASNgIADBkLIAcoAkAgEjYCAAwYCyAHKAJAIBKsNwMADBcLIAcoAkAgEjsBAAwWCyAHKAJAIBI6AAAMFQsgBygCQCASNgIADBQLIAcoAkAgEqw3AwAMEwtBCCAJIAlBCE0bIQkgC0EIciELQfgAIQYLIBMhASAHKQNAIh5CAFIEQCAGQSBxIQgDQCABQQFrIgEgHqdBD3FBsMoAai0AACAIcjoAACAeQg9WIRwgHkIEiCEeIBwNAAsLIAEhDCAHKQNAUA0DIAtBCHFFDQMgBkEEdkGKCGohFkECIQ4MAwsgEyEBIAcpA0AiHkIAUgRAA0AgAUEBayIBIB6nQQdxQTByOgAAIB5CB1YhHSAeQgOIIR4gHQ0ACwsgASEMIAtBCHFFDQIgCSATIAFrIgFBAWogASAJSBshCQwCCyAHKQNAIh5CAFMEQCAHQgAgHn0iHjcDQEEBIQ5BiggMAQsgC0GAEHEEQEEBIQ5BiwgMAQtBjAhBigggC0EBcSIOGwshFiAeIBMQKSEMCyAVIAlBAEhxDQ8gC0H//3txIAsgFRshCwJAIAcpA0AiHkIAUg0AIAkNACATIQxBACEJDAwLIAkgHlAgEyAMa2oiASABIAlIGyEJDAsLAn9B/////wcgCSAJQf////8HTxsiCiIRQQBHIQsCQAJAAkAgBygCQCIBQa8SIAEbIgwiBiINQQNxRQ0AIBFFDQADQCANLQAARQ0CIBFBAWsiEUEARyELIA1BAWoiDUEDcUUNASARDQALCyALRQ0BAkAgDS0AAEUNACARQQRJDQADQCANKAIAIgFBf3MgAUGBgoQIa3FBgIGChHhxDQIgDUEEaiENIBFBBGsiEUEDSw0ACwsgEUUNAQsDQCANIA0tAABFDQIaIA1BAWohDSARQQFrIhENAAsLQQALIgEgBmsgCiABGyIBIAxqIQogCUEATgRAIAghCyABIQkMCwsgCCELIAEhCSAKLQAADQ4MCgsgCQRAIAcoAkAMAgtBACEGIABBICAPQQAgCxAfDAILIAdBADYCDCAHIAcpA0A+AgggByAHQQhqIgY2AkBBfyEJIAYLIQhBACEGAkADQCAIKAIAIgxFDQECQCAHQQRqIAwQSCIKQQBIIgwNACAKIAkgBmtLDQAgCEEEaiEIIAYgCmoiBiAJSQ0BDAILCyAMDQ4LQT0hECAGQQBIDQwgAEEgIA8gBiALEB8gBkUEQEEAIQYMAQtBACEKIAcoAkAhCANAIAgoAgAiDEUNASAHQQRqIgkgDBBIIgwgCmoiCiAGSw0BIAAgCSAMEB0gCEEEaiEIIAYgCksNAAsLIABBICAPIAYgC0GAwABzEB8gDyAGIAYgD0gbIQYMCAsgFSAJQQBIcQ0JQT0hECAAIAcrA0AgDyAJIAsgBhBJIgZBAE4NBwwKCyAHIAcpA0A8ADdBASEJIBkhDCAIIQsMBAsgBi0AASEIIAZBAWohBgwACwALIBIhECAADQcgFEUNAkEBIQYDQCAEIAZBAnRqKAIAIgAEQCADIAZBA3RqIAAgAiAFEEpBASEQIAZBAWoiBkEKRw0BDAkLC0EBIRAgBkEKTw0HA0AgBCAGQQJ0aigCAA0BIAZBAWoiBkEKRw0ACwwHC0EcIRAMBQsgCSAKIAxrIgogCSAKShsiASAOQf////8Hc0oNA0E9IRAgDyABIA5qIgggCCAPSBsiBiAaSg0EIABBICAGIAggCxAfIAAgFiAOEB0gAEEwIAYgCCALQYCABHMQHyAAQTAgASAKQQAQHyAAIAwgChAdIABBICAGIAggC0GAwABzEB8gBygCTCEBDAELCwtBACEQDAILQT0hEAtB6N4AIBA2AgBBfyEQCyAHQdAAaiQAIBALvwIBBX8jAEHQAWsiBCQAIAQgAjYCzAEgBEGgAWoiAkEAQSgQJhogBCAEKALMATYCyAECQEEAIAEgBEHIAWogBEHQAGogAiADEExBAEgEQEF/IQMMAQsgACgCTEEASCEIIAAgACgCACIHQV9xNgIAAn8CQAJAIAAoAjBFBEAgAEHQADYCMCAAQQA2AhwgAEIANwMQIAAoAiwhBSAAIAQ2AiwMAQsgACgCEA0BC0F/IAAQTw0BGgsgACABIARByAFqIARB0ABqIARBoAFqIAMQTAshAiAFBEAgAEEAQQAgACgCJBECABogAEEANgIwIAAgBTYCLCAAQQA2AhwgACgCFCEBIABCADcDECACQX8gARshAgsgACAAKAIAIgAgB0EgcXI2AgBBfyACIABBIHEbIQMgCA0ACyAEQdABaiQAIAMLfgIBfwF+IAC9IgNCNIinQf8PcSICQf8PRwR8IAJFBEAgASAARAAAAAAAAAAAYQR/QQAFIABEAAAAAAAA8EOiIAEQTiEAIAEoAgBBQGoLNgIAIAAPCyABIAJB/gdrNgIAIANC/////////4eAf4NCgICAgICAgPA/hL8FIAALC1kBAX8gACAAKAJIIgFBAWsgAXI2AkggACgCACIBQQhxBEAgACABQSByNgIAQX8PCyAAQgA3AgQgACAAKAIsIgE2AhwgACABNgIUIAAgASAAKAIwajYCEEEACwIAC/ADAEG8zwBBoQsQFUHUzwBB9wlBAUEAEBRB4M8AQa4JQQFBgH9B/wAQBkH4zwBBpwlBAUGAf0H/ABAGQezPAEGlCUEBQQBB/wEQBkGE0ABBsAhBAkGAgH5B//8BEAZBkNAAQacIQQJBAEH//wMQBkGc0ABBvwhBBEGAgICAeEH/////BxAGQajQAEG2CEEEQQBBfxAGQbTQAEGwCkEEQYCAgIB4Qf////8HEAZBwNAAQacKQQRBAEF/EAZBzNAAQc8IQoCAgICAgICAgH9C////////////ABBUQdjQAEHOCEIAQn8QVEHk0ABByAhBBBAPQfDQAEGGC0EIEA9BoC9BzwoQDkH4L0HVDxAOQcAwQQRBtQoQC0GMMUECQdsKEAtB2DFBBEHqChALQcwtQfwJEBNBgDJBAEGQDxAAQagyQQBB9g8QAEHQMkEBQa4PEABB+DJBAkHdCxAAQaAzQQNB/AsQAEHIM0EEQaQMEABB8DNBBUHBDBAAQZg0QQRBmxAQAEHANEEFQbkQEABBqDJBAEGnDRAAQdAyQQFBhg0QAEH4MkECQekNEABBoDNBA0HHDRAAQcgzQQRB7w4QAEHwM0EFQc0OEABB6DRBCEGsDhAAQZA1QQlBig4QAEG4NUEGQecMEABB4DVBB0HgEBAAC2YBA39B2AAQLUHQAGoiAUGg0gA2AgAgAUHM0gA2AgAgABAqIgJBDWoQHCIDQQA2AgggAyACNgIEIAMgAjYCACABIANBDGogACACQQFqECI2AgQgAUH80gA2AgAgAUGc0wBBGBAWAAvYAwIEfwF8IwBBEGsiBCQAIAQgAjYCCCAEQQA2AgRB9NQALQAAQQFxRQRAQQJBzC5BABAFIQJB9NQAQQE6AABB8NQAIAI2AgALAn9B8NQAKAIAIAEoAgRBigkgBEEEaiAEQQhqEAQiCEQAAAAAAADwQWMgCEQAAAAAAAAAAGZxBEAgCKsMAQtBAAshBSAEKAIEIQIgACAFNgIEIABB1NUANgIAIAIEQCACEAELIwBBIGsiAiQAIAAoAgQiBRACIAIgBTYCECADKAIEIAMtAAsiBSAFwEEASCIHGyIFQQRqEC0iBiAFNgIAIAZBBGogAygCACADIAcbIAUQIhogAiAGNgIYIAJBADYCDEH81AAtAABBAXFFBEBBA0HULkEAEAUhA0H81ABBAToAAEH41AAgAzYCAAtB+NQAKAIAIAEoAgRBlAsgAkEMaiACQRBqEAQaIAIoAgwiAwRAIAMQAQsgAkEgaiQAIAAoAgQiABACIAQgADYCCCAEQQA2AgRB7NQALQAAQQFxRQRAQQJBvC5BABAFIQBB7NQAQQE6AABB6NQAIAA2AgALQejUACgCACABKAIEQZcJIARBBGogBEEIahAEGiAEKAIEIgAEQCAAEAELIARBEGokAAscACAAIAFBCCACpyACQiCIpyADpyADQiCIpxAQC4sEAQJ/QegsQfwsQZgtQQBBqC1BAUGrLUEAQastQQBBmhJBrS1BAhAYQegsQQJBsC1B1C1BA0EEEBdBCBAcIgBBADYCBCAAQQU2AgBBCBAcIgFBADYCBCABQQY2AgBB6CxB6QhBzC1B1C1BByAAQcwtQdgtQQggARAKQQgQHCIAQQA2AgQgAEEJNgIAQQgQHCIBQQA2AgQgAUEKNgIAQegsQY0LQcwtQdQtQQcgAEHMLUHYLUEIIAEQCkEIEBwiAEEANgIEIABBCzYCAEEIEBwiAUEANgIEIAFBDDYCAEHoLEHXCEHMLUHULUEHIABBzC1B2C1BCCABEApBCBAcIgBBADYCBCAAQQ02AgBBCBAcIgFBADYCBCABQQ42AgBB6CxBwglBzC1B1C1BByAAQcwtQdgtQQggARAKQQgQHCIAQQA2AgQgAEEPNgIAQegsQYAIQQdB4C1B/C1BECAAQQBBABAIQQgQHCIAQQA2AgQgAEERNgIAQegsQYwKQQZBkC5BqC5BEiAAQQBBABAIQQgQHCIAQQA2AgQgAEETNgIAQegsQZkKQQJBsC5BuC5BFCAAQQBBABAIQQgQHCIAQQA2AgQgAEEVNgIAQegsQYALQQJBsC5BuC5BFCAAQQBBABAIQQgQHCIAQQA2AgQgAEEWNgIAQegsQcMIQQJBxC5B1C1BFyAAQQBBABAICwcAIAAoAgQLBQBBswkLFgAgAEUEQEEADwsgAEHszQAQIEEARwsaACAAIAEoAgggBRAeBEAgASACIAMgBBA7Cws3ACAAIAEoAgggBRAeBEAgASACIAMgBBA7DwsgACgCCCIAIAEgAiADIAQgBSAAKAIAKAIUEQkAC6cBACAAIAEoAgggBBAeBEACQCABKAIEIAJHDQAgASgCHEEBRg0AIAEgAzYCHAsPCwJAIAAgASgCACAEEB5FDQACQCACIAEoAhBHBEAgASgCFCACRw0BCyADQQFHDQEgAUEBNgIgDwsgASACNgIUIAEgAzYCICABIAEoAihBAWo2AigCQCABKAIkQQFHDQAgASgCGEECRw0AIAFBAToANgsgAUEENgIsCwuIAgAgACABKAIIIAQQHgRAAkAgASgCBCACRw0AIAEoAhxBAUYNACABIAM2AhwLDwsCQCAAIAEoAgAgBBAeBEACQCACIAEoAhBHBEAgASgCFCACRw0BCyADQQFHDQIgAUEBNgIgDwsgASADNgIgAkAgASgCLEEERg0AIAFBADsBNCAAKAIIIgAgASACIAJBASAEIAAoAgAoAhQRCQAgAS0ANQRAIAFBAzYCLCABLQA0RQ0BDAMLIAFBBDYCLAsgASACNgIUIAEgASgCKEEBajYCKCABKAIkQQFHDQEgASgCGEECRw0BIAFBAToANg8LIAAoAggiACABIAIgAyAEIAAoAgAoAhgRCAALC2kBAn8jAEEQayIDJAAgASAAKAIEIgRBAXVqIQEgACgCACEAIARBAXEEQCABKAIAIABqKAIAIQALIAMgAjYCDCADQdTVADYCCCABIANBCGogABEAACADKAIMIgAEQCAAEAMLIANBEGokAAuEBQEEfyMAQUBqIgQkAAJAIAFByM8AQQAQHgRAIAJBADYCAEEBIQUMAQsCQCAAIAEgAC0ACEEYcQR/QQEFIAFFDQEgAUG8zQAQICIDRQ0BIAMtAAhBGHFBAEcLEB4hBgsgBgRAQQEhBSACKAIAIgBFDQEgAiAAKAIANgIADAELAkAgAUUNACABQezNABAgIgZFDQEgAigCACIBBEAgAiABKAIANgIACyAGKAIIIgMgACgCCCIBQX9zcUEHcQ0BIANBf3MgAXFB4ABxDQFBASEFIAAoAgwgBigCDEEAEB4NASAAKAIMQbzPAEEAEB4EQCAGKAIMIgBFDQIgAEGgzgAQIEUhBQwCCyAAKAIMIgNFDQBBACEFIANB7M0AECAiAQRAIAAtAAhBAXFFDQICfyAGKAIMIQBBACECAkADQEEAIABFDQIaIABB7M0AECAiA0UNASADKAIIIAEoAghBf3NxDQFBASABKAIMIAMoAgxBABAeDQIaIAEtAAhBAXFFDQEgASgCDCIARQ0BIABB7M0AECAiAQRAIAMoAgwhAAwBCwsgAEHczgAQICIARQ0AIAAgAygCDBA8IQILIAILIQUMAgsgA0HczgAQICIBBEAgAC0ACEEBcUUNAiABIAYoAgwQPCEFDAILIANBjM0AECAiAUUNASAGKAIMIgBFDQEgAEGMzQAQICIARQ0BIARBDGpBAEE0ECYaIARBATYCOCAEQX82AhQgBCABNgIQIAQgADYCCCAAIARBCGogAigCAEEBIAAoAgAoAhwRBgACQCAEKAIgIgBBAUcNACACKAIARQ0AIAIgBCgCGDYCAAsgAEEBRiEFDAELQQAhBQsgBEFAayQAIAULMQAgACABKAIIQQAQHgRAIAEgAiADED0PCyAAKAIIIgAgASACIAMgACgCACgCHBEGAAsYACAAIAEoAghBABAeBEAgASACIAMQPQsLnQEBAn8jAEFAaiIDJAACf0EBIAAgAUEAEB4NABpBACABRQ0AGkEAIAFBjM0AECAiAUUNABogA0EMakEAQTQQJhogA0EBNgI4IANBfzYCFCADIAA2AhAgAyABNgIIIAEgA0EIaiACKAIAQQEgASgCACgCHBEGACADKAIgIgBBAUYEQCACIAMoAhg2AgALIABBAUYLIQQgA0FAayQAIAQLCgAgACABQQAQHgtOAgF/AXwjAEEQayICJAAgAkEANgIMIAEoAgRB1M8AIAJBDGoQCSEDIAIoAgwiAQRAIAEQAQsgACADRAAAAAAAAAAAYjoAOCACQRBqJAALNwEBfyMAQRBrIgIkACACIAEtADg2AgggAEHUzwAgAkEIahAHNgIEIABB1NUANgIAIAJBEGokAAuoAQEFfyAAKAJUIgMoAgAhBSADKAIEIgQgACgCFCAAKAIcIgdrIgYgBCAGSRsiBgRAIAUgByAGECIaIAMgAygCACAGaiIFNgIAIAMgAygCBCAGayIENgIECyAEIAIgAiAESxsiBARAIAUgASAEECIaIAMgAygCACAEaiIFNgIAIAMgAygCBCAEazYCBAsgBUEAOgAAIAAgACgCLCIBNgIcIAAgATYCFCACC5wBAQJ/IwBBEGsiAiQAQcgAEBwhASAAKAIEIgAQAiACIAA2AgggAUHMLSACQQhqEAc2AgQgAUHU1QA2AgAgAUEBNgIcIAFB1NUANgIYIAFBATYCFCABQdTVADYCECABQQE2AgwgAUHU1QA2AgggAUEAOgAgIAFBADYCRCABQoCAgIAwNwI8IAFBADsANyABQQA7ACsgAkEQaiQAIAELigUCBn4CfyABIAEoAgBBB2pBeHEiAUEQajYCACAAIQkgASkDACEDIAEpAwghBSMAQSBrIgAkAAJAIAVC////////////AIMiBEKAgICAgIDAgDx9IARCgICAgICAwP/DAH1UBEAgBUIEhiADQjyIhCEEIANC//////////8PgyIDQoGAgICAgICACFoEQCAEQoGAgICAgICAwAB8IQIMAgsgBEKAgICAgICAgEB9IQIgA0KAgICAgICAgAhSDQEgAiAEQgGDfCECDAELIANQIARCgICAgICAwP//AFQgBEKAgICAgIDA//8AURtFBEAgBUIEhiADQjyIhEL/////////A4NCgICAgICAgPz/AIQhAgwBC0KAgICAgICA+P8AIQIgBEL///////+//8MAVg0AQgAhAiAEQjCIpyIBQZH3AEkNACADIQIgBUL///////8/g0KAgICAgIDAAIQiBCEGAkAgAUGB9wBrIghBwABxBEAgAyAIQUBqrYYhBkIAIQIMAQsgCEUNACAGIAitIgeGIAJBwAAgCGutiIQhBiACIAeGIQILIAAgAjcDECAAIAY3AxgCQEGB+AAgAWsiAUHAAHEEQCAEIAFBQGqtiCEDQgAhBAwBCyABRQ0AIARBwAAgAWuthiADIAGtIgKIhCEDIAQgAoghBAsgACADNwMAIAAgBDcDCCAAKQMIQgSGIAApAwAiA0I8iIQhAiAAKQMQIAApAxiEQgBSrSADQv//////////D4OEIgNCgYCAgICAgIAIWgRAIAJCAXwhAgwBCyADQoCAgICAgICACFINACACQgGDIAJ8IQILIABBIGokACAJIAIgBUKAgICAgICAgIB/g4S/OQMAC0ABAn8jAEEQayICJAAgAiABNgIMIAJB1NUANgIIIAJBCGogABEBACEDIAIoAgwiAQRAIAEQAwsgAkEQaiQAIAMLBABCAAsEAEEAC/YCAQh/IwBBIGsiAyQAIAMgACgCHCIENgIQIAAoAhQhBSADIAI2AhwgAyABNgIYIAMgBSAEayIBNgIUIAEgAmohBUECIQcCfwJAAkACQCAAKAI8IANBEGoiAUECIANBDGoQDSIEBH9B6N4AIAQ2AgBBfwVBAAsEQCABIQQMAQsDQCAFIAMoAgwiBkYNAiAGQQBIBEAgASEEDAQLIAEgBiABKAIEIghLIglBA3RqIgQgBiAIQQAgCRtrIgggBCgCAGo2AgAgAUEMQQQgCRtqIgEgASgCACAIazYCACAFIAZrIQUgACgCPCAEIgEgByAJayIHIANBDGoQDSIGBH9B6N4AIAY2AgBBfwVBAAtFDQALCyAFQX9HDQELIAAgACgCLCIBNgIcIAAgATYCFCAAIAEgACgCMGo2AhAgAgwBCyAAQQA2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EGokAAsiAQF+IAEgAq0gA61CIIaEIAQgABEMACIFQiCIpyQBIAWnCzcBAX8jAEEQayICJAAgAiABKAI8NgIIIABBnNAAIAJBCGoQBzYCBCAAQdTVADYCACACQRBqJAALC/NKFQBBgAgLhCZzZXRCZWF1dHkALSsgICAwWDB4AC0wWCswWCAwWC0weCsweCAweAB1bnNpZ25lZCBzaG9ydAB1bnNpZ25lZCBpbnQAaW5pdABmbG9hdAB1aW50NjRfdABibHVyUmFkaXVzAHZlY3RvcgBtaXJyb3IAYXR0YWNoU2hhZGVyAGRlbGV0ZVNoYWRlcgBjcmVhdGVTaGFkZXIAY29tcGlsZVNoYWRlcgB1bnNpZ25lZCBjaGFyAHN0ZDo6ZXhjZXB0aW9uAHJvdGF0aW9uAG5hbgBsaW5rUHJvZ3JhbQBkZWxldGVQcm9ncmFtAGNyZWF0ZVByb2dyYW0AYm9vbABlbXNjcmlwdGVuOjp2YWwAc2V0V2F0ZXJNYXJrAHN0b3BXYXRlck1hcmsAdW5zaWduZWQgbG9uZwBzdGQ6OndzdHJpbmcAYmFzaWNfc3RyaW5nAHN0ZDo6c3RyaW5nAHN0ZDo6dTE2c3RyaW5nAHN0ZDo6dTMyc3RyaW5nAGluZgAlZgBjbG9zZQBkb3VibGUAdmJNb2RlAHNoYWRlclNvdXJjZQB2b2lkAHNhbXBsZUNvbG9yICs9IHRleHR1cmUoZnJhbWUsIGJsdXJDb29yZGluYXRlc1sATkFOAElORgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaG9ydD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgc2hvcnQ+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgaW50PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxmbG9hdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDhfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50OF90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8aW50MTZfdD4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dWludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PGludDY0X3Q+AGVtc2NyaXB0ZW46Om1lbW9yeV92aWV3PHVpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxpbnQzMl90PgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzx1bnNpZ25lZCBjaGFyPgBzdGQ6OmJhc2ljX3N0cmluZzx1bnNpZ25lZCBjaGFyPgBlbXNjcmlwdGVuOjptZW1vcnlfdmlldzxzaWduZWQgY2hhcj4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8bG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8dW5zaWduZWQgbG9uZz4AZW1zY3JpcHRlbjo6bWVtb3J5X3ZpZXc8ZG91YmxlPgB2ZWMyIGMgPSB2X3RleENvb3JkOwB2ZWMyIGMgPSB2ZWMyKDEuMCAtIHZfdGV4Q29vcmQueCwgdl90ZXhDb29yZC55KTsAYyA9IHZlYzIoMS4wIC0gYy54LCAxLjAgLSBjLnkpOwBjID0gdmVjMihjLnksIDEuMCAtIGMueCk7AGMgPSB2ZWMyKDEuMCAtIGMueSwgYy54KTsAQWxsSW4xAC4ALjAsAC4wKSpvKSoAKG51bGwpACkqby55KTsgICAgdmVjMiBjb29yZDIgPSB2ZWMyKGZsb2F0KAAgICAgYyA9IHZlYzIodl90ZXhDb29yZC54LCAxLjAgLSB2X3RleENvb3JkLnkpOyAgICB2ZWMyIGNvb3JkMSA9IHZlYzIoZmxvYXQoACksIChjLnkgLWNvb3JkMS55KSAvIG8ueSAvIGZsb2F0KAApKm8ueSk7ICAgIGlmIChjLnggPiBjb29yZDEueCAmJiBjLnggPCBjb29yZDIueCAmJiBjLnkgPiBjb29yZDEueSAmJiBjLnkgPCBjb29yZDIueSkgeyAgICAgIHZlYzQgd2F0ZXJDb2xvciA9IHRleHR1cmUod2F0ZXJNYXJrLCB2ZWMyKChjLnggLSBjb29yZDEueCkgIC8gby54IC8gZmxvYXQoACkgKiBvLngsIGZsb2F0KABvdXRDb2xvci5yZ2IgKz0gdmVjMygAKTsgICAgICAgdmVjMyBzbW9vdGhDb2xvciA9IG91dENvbG9yLnJnYiArIChvdXRDb2xvci5yZ2ItdmVjMyhoaWdoUGFzcykpKmFscGhhKjAuMTsgICAgICAgc21vb3RoQ29sb3IgPSBtYXgoc21vb3RoQ29sb3IsIHZlYzMoMC4wKSk7ICAgICAgIHNtb290aENvbG9yID0gY2xhbXAocG93KHNtb290aENvbG9yLCB2ZWMzKABnKz1HKGMsdmVjMigAICAgICAgdmVjMiBvZmZzZXQgPSB2ZWMyKABdID0gdl90ZXhDb29yZC54eSArIG9mZnNldCAqIHZlYzIoADsgACkpLCB2ZWMzKDAuMCksIHZlYzMoMS4wKSk7ICAgICAgdmVjMyBzY3JlZW4gPSB2ZWMzKDEuMCkgLSAodmVjMygxLjApLXNtb290aENvbG9yKSAqICh2ZWMzKDEuMCktb3V0Q29sb3IucmdiKTsgICAgICAgdmVjMyBsaWdodGVuID0gbWF4KHNtb290aENvbG9yLCBvdXRDb2xvci5yZ2IpOyAgICAgICB2ZWMzIGJlYXV0eUNvbG9yID0gbWl4KG1peChvdXRDb2xvci5yZ2IsIHNjcmVlbiwgYWxwaGEpLCBsaWdodGVuLCBhbHBoYSk7ICAgICAgb3V0Q29sb3IucmdiID0gbWl4KG91dENvbG9yLnJnYiwgYmVhdXR5Q29sb3IsIAAKICAgICAgY29uc3QgbWF0MyBzYXR1cmF0ZU1hdHJpeCA9IG1hdDMoMS4xMTAyLC0wLjA1OTgsLTAuMDYxLC0wLjA3NzQsMS4wODI2LC0wLjExODYsLTAuMDIyOCwtMC4wMjI4LDEuMTc3Mik7CiAgICAgIHZlYzMgd2FybUNvbG9yID0gb3V0Q29sb3IucmdiICogc2F0dXJhdGVNYXRyaXg7CiAgICAgIG91dENvbG9yLnJnYiA9IG1peChvdXRDb2xvci5yZ2IsIHdhcm1Db2xvciwgACAgICAgIHNhbXBsZUNvbG9yID0gc2FtcGxlQ29sb3IgLyA2Mi4wOyAgICAgICBmbG9hdCBoaWdoUGFzcyA9IG91dENvbG9yLmcgLSBzYW1wbGVDb2xvciArIDAuNTsgICAgICAgY29uc3QgaGlnaHAgdmVjMyBXID0gdmVjMygwLjI5OSwwLjU4NywwLjExNCk7ICAgICAgZmxvYXQgbHVtaW5hbmNlID0gZG90KG91dENvbG9yLnJnYiwgVyk7ICAgICAgIGZsb2F0IGFscGhhID0gcG93KGx1bWluYW5jZSwgAF0pLmcgKiAAKSkpOyAgICAgIG91dENvbG9yID0gbWl4KG91dENvbG9yLHdhdGVyQ29sb3IsICB3YXRlckNvbG9yLmEpOyAgICB9ICAgIAApOyAgICAAKTsgICAgICB2ZWMyIGJsdXJDb29yZGluYXRlc1syNF07ICAgICAgACAgICAgIGZsb2F0IHNhbXBsZUNvbG9yID0gb3V0Q29sb3IuZyAqIDIyLjA7ICAgICAgIAAjdmVyc2lvbiAzMDAgZXMKICAgIHByZWNpc2lvbiBoaWdocCBmbG9hdDsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGZyYW1lOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbWFzazsKICAgIHVuaWZvcm0gc2FtcGxlcjJEIGJnOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgd2F0ZXJNYXJrOwogICAgdW5pZm9ybSBzYW1wbGVyMkQgbGFzdE1hc2s7CiAgICB1bmlmb3JtIG1hdDQgdV9vZmZzZXRNYXRyaXg7CiAgICB1bmlmb3JtIHZlYzMgdV9jb2xvcjsKICAgIGluIHZlYzIgdl90ZXhDb29yZDsKICAgIG91dCB2ZWM0IG91dENvbG9yOwogICAgdmVjNCBHKHZlYzIgYyx2ZWMyIHMpewogICAgICByZXR1cm4gdGV4dHVyZShmcmFtZSx0ZXh0dXJlKG1hc2ssYytzKS5yPjAuMz9jOmMrcyk7CiAgICB9CiAgICB2b2lkIG1haW4oKSB7CiAgICAgIAAKICAgICAgdmVjMiBvZmZzZXRNYXNrVVYgPSAodV9vZmZzZXRNYXRyaXggKiB2ZWM0KGMsIDAsIDEpKS54eTsKICAgICAgZmxvYXQgaXNJbnNpZGVYID0gKG9mZnNldE1hc2tVVi54ID49IDAuMCkgJiYgKG9mZnNldE1hc2tVVi54IDw9IDEuMCkgPyAxLjAgOiAwLjA7CiAgICAgIGZsb2F0IGlzSW5zaWRlWSA9IChvZmZzZXRNYXNrVVYueSA+PSAwLjApICYmIChvZmZzZXRNYXNrVVYueSA8PSAxLjApID8gMS4wIDogMC4wOwogICAgICBmbG9hdCBpc0luc2lkZSA9IGlzSW5zaWRlWCAqIGlzSW5zaWRlWTsKICAgICAgZmxvYXQgbWFza2VkQWxwaGEgPSB0ZXh0dXJlKG1hc2ssIG9mZnNldE1hc2tVVikuciAqIGlzSW5zaWRlOwogICAgICBtYXNrZWRBbHBoYSA9IG1hc2tlZEFscGhhPDAuNT8yLjAqbWFza2VkQWxwaGEqbWFza2VkQWxwaGE6MS4wLTIuMCooMS4wLW1hc2tlZEFscGhhKSooMS4wLW1hc2tlZEFscGhhKTsKICAgICAgc3JjX2NvbG9yID0gdGV4dHVyZShmcmFtZSwgb2Zmc2V0TWFza1VWICwgaXNJbnNpZGUpOwogICAgICBvdXRDb2xvciA9IG1peCh0ZXh0dXJlKGJnLCBjKSwgc3JjX2NvbG9yLCBtYXNrZWRBbHBoYSk7CiAgICAACiAgICB2ZWM0IGcgPSB2ZWM0KDAuMCk7CiAgICAACiAgICAgIGMueSA9IDEuMCAtIGMueTsKICAgICAgdmVjNCBzcmNfY29sb3IgPSB0ZXh0dXJlKGZyYW1lLCBjKTsKICAgICAgZmxvYXQgYSA9IHRleHR1cmUobWFzaywgYykucjsKICAgICAgYSA9IGE8MC41PzIuMCphKmE6MS4wLTIuMCooMS4wLWEpKigxLjAtYSk7CiAgICAgIC8vIGZsb2F0IGEyID0gdGV4dHVyZShsYXN0TWFzaywgYykuYTsKICAgICAgLy8gYTIgPSBhMjwwLjU/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFjaGFyX3RyYWl0c0lEaUVFTlNfOWFsbG9jYXRvcklEaUVFRUUAAACAKAAAlBgAAE4xMGVtc2NyaXB0ZW4xMW1lbW9yeV92aWV3SWNFRQAAgCgAAOAYAABOMTBlbXNjcmlwdGVuMTFtZW1vcnlfdmlld0lhRUUAAIAoAAAIGQAATjEwZW1zY3JpcHRlbjExbWVtb3J5X3ZpZXdJaEVFAACAKAAAMBkAAE4xMGVtc2NyaXB0ZW4xMW1lbW9yeV92aWV3SXNFRQAAgCgAAFgZAABOMTBlbXNjcmlwdGVuMTFtZW1vcnlfdmlld0l0RUUAAIAoAACAGQAATjEwZW1zY3JpcHRlbjExbWVtb3J5X3ZpZXdJaUVFAACAKAAAqBkAAE4xMGVtc2NyaXB0ZW4xMW1lbW9yeV92aWV3SWpFRQAAgCgAANAZAABOMTBlbXNjcmlwdGVuMTFtZW1vcnlfdmlld0lsRUUAAIAoAAD4GQAATjEwZW1zY3JpcHRlbjExbWVtb3J5X3ZpZXdJbUVFAACAKAAAIBoAAE4xMGVtc2NyaXB0ZW4xMW1lbW9yeV92aWV3SXhFRQAAgCgAAEgaAABOMTBlbXNjcmlwdGVuMTFtZW1vcnlfdmlld0l5RUUAAIAoAABwGgAATjEwZW1zY3JpcHRlbjExbWVtb3J5X3ZpZXdJZkVFAACAKAAAmBoAAE4xMGVtc2NyaXB0ZW4xMW1lbW9yeV92aWV3SWRFRQAAgCgAAMAaAAD+gitlRxVnQAAAAAAAADhDAAD6/kIudr86O568mvcMvb39/////98/PFRVVVVVxT+RKxfPVVWlPxfQpGcREYE/AAAAAAAAyELvOfr+Qi7mPyTEgv+9v84/tfQM1whrrD/MUEbSq7KDP4Q6Tpvg11U/AEHmNgu7EPA/br+IGk87mzw1M/upPfbvP13c2JwTYHG8YYB3Pprs7z/RZocQel6QvIV/bugV4+8/E/ZnNVLSjDx0hRXTsNnvP/qO+SOAzou83vbdKWvQ7z9hyOZhTvdgPMibdRhFx+8/mdMzW+SjkDyD88bKPr7vP217g12mmpc8D4n5bFi17z/87/2SGrWOPPdHciuSrO8/0ZwvcD2+Pjyi0dMy7KPvPwtukIk0A2q8G9P+r2ab7z8OvS8qUlaVvFFbEtABk+8/VepOjO+AULzMMWzAvYrvPxb01bkjyZG84C2prpqC7z+vVVzp49OAPFGOpciYeu8/SJOl6hUbgLx7UX08uHLvPz0y3lXwH4+86o2MOPlq7z+/UxM/jImLPHXLb+tbY+8/JusRdpzZlrzUXASE4FvvP2AvOj737Jo8qrloMYdU7z+dOIbLguePvB3Z/CJQTe8/jcOmREFvijzWjGKIO0bvP30E5LAFeoA8ltx9kUk/7z+UqKjj/Y6WPDhidW56OO8/fUh08hhehzw/prJPzjHvP/LnH5grR4A83XziZUUr7z9eCHE/e7iWvIFj9eHfJO8/MasJbeH3gjzh3h/1nR7vP/q/bxqbIT28kNna0H8Y7z+0CgxygjeLPAsD5KaFEu8/j8vOiZIUbjxWLz6prwzvP7arsE11TYM8FbcxCv4G7z9MdKziAUKGPDHYTPxwAe8/SvjTXTndjzz/FmSyCPzuPwRbjjuAo4a88Z+SX8X27j9oUEvM7UqSvMupOjen8e4/ji1RG/gHmbxm2AVtruzuP9I2lD7o0XG895/lNNvn7j8VG86zGRmZvOWoE8Mt4+4/bUwqp0ifhTwiNBJMpt7uP4ppKHpgEpO8HICsBEXa7j9biRdIj6dYvCou9yEK1u4/G5pJZ5ssfLyXqFDZ9dHuPxGswmDtY0M8LYlhYAjO7j/vZAY7CWaWPFcAHe1Byu4/eQOh2uHMbjzQPMG1osbuPzASDz+O/5M83tPX8CrD7j+wr3q7zpB2PCcqNtXav+4/d+BU670dkzwN3f2ZsrzuP46jcQA0lI+8pyyddrK57j9Jo5PczN6HvEJmz6Latu4/XzgPvcbeeLyCT51WK7TuP/Zce+xGEoa8D5JdyqSx7j+O1/0YBTWTPNontTZHr+4/BZuKL7eYezz9x5fUEq3uPwlUHOLhY5A8KVRI3Qer7j/qxhlQhcc0PLdGWYomqe4/NcBkK+YylDxIIa0Vb6fuP592mWFK5Iy8Cdx2ueGl7j+oTe87xTOMvIVVOrB+pO4/rukriXhThLwgw8w0RqPuP1hYVnjdzpO8JSJVgjii7j9kGX6AqhBXPHOpTNRVoe4/KCJev++zk7zNO39mnqDuP4K5NIetEmq8v9oLdRKg7j/uqW2472djvC8aZTyyn+4/UYjgVD3cgLyElFH5fZ/uP88+Wn5kH3i8dF/s6HWf7j+wfYvASu6GvHSBpUian+4/iuZVHjIZhrzJZ0JW65/uP9PUCV7LnJA8P13eT2mg7j8dpU253DJ7vIcB63MUoe4/a8BnVP3slDwywTAB7aHuP1Vs1qvh62U8Yk7PNvOi7j9Cz7MvxaGIvBIaPlQnpO4/NDc78bZpk7wTzkyZiaXuPx7/GTqEXoC8rccjRhqn7j9uV3LYUNSUvO2SRJvZqO4/AIoOW2etkDyZZorZx6ruP7Tq8MEvt40826AqQuWs7j//58WcYLZlvIxEtRYyr+4/RF/zWYP2ezw2dxWZrrHuP4M9HqcfCZO8xv+RC1u07j8pHmyLuKldvOXFzbA3t+4/WbmQfPkjbLwPUsjLRLruP6r59CJDQ5K8UE7en4K97j9LjmbXbMqFvLoHynDxwO4/J86RK/yvcTyQ8KOCkcTuP7tzCuE10m08IyPjGWPI7j9jImIiBMWHvGXlXXtmzO4/1THi44YcizwzLUrsm9DuPxW7vNPRu5G8XSU+sgPV7j/SMe6cMcyQPFizMBOe2e4/s1pzboRphDy//XlVa97uP7SdjpfN34K8evPTv2vj7j+HM8uSdxqMPK3TWpmf6O4/+tnRSo97kLxmto0pB+7uP7qu3FbZw1W8+xVPuKLz7j9A9qY9DqSQvDpZ5Y1y+e4/NJOtOPTWaLxHXvvydv/uPzWKWGvi7pG8SgahMLAF7z/N3V8K1/90PNLBS5AeDO8/rJiS+vu9kbwJHtdbwhLvP7MMrzCubnM8nFKF3ZsZ7z+U/Z9cMuOOPHrQ/1+rIO8/rFkJ0Y/ghDxL0Vcu8SfvP2caTjivzWM8tecGlG0v7z9oGZJsLGtnPGmQ79wgN+8/0rXMgxiKgLz6w11VCz/vP2/6/z9drY+8fIkHSi1H7z9JqXU4rg2QvPKJDQiHT+8/pwc9poWjdDyHpPvcGFjvPw8iQCCekYK8mIPJFuNg7z+sksHVUFqOPIUy2wPmae8/S2sBrFk6hDxgtAHzIXPvPx8+tAch1YK8X5t7M5d87z/JDUc7uSqJvCmh9RRGhu8/04g6YAS2dDz2P4vnLpDvP3FynVHsxYM8g0zH+1Ga7z/wkdOPEvePvNqQpKKvpO8/fXQj4piujbzxZ44tSK/vPwggqkG8w448J1ph7hu67z8y66nDlCuEPJe6azcrxe8/7oXRMalkijxARW5bdtDvP+3jO+S6N468FL6crf3b7z+dzZFNO4l3PNiQnoHB5+8/icxgQcEFUzzxcY8rwvPvPwAAAAAAAAAAGQAKABkZGQAAAAAFAAAAAAAACQAAAAALAAAAAAAAAAAZABEKGRkZAwoHAAEACQsYAAAJBgsAAAsABhkAAAAZGRkAQbHHAAshDgAAAAAAAAAAGQAKDRkZGQANAAACAAkOAAAACQAOAAAOAEHrxwALAQwAQffHAAsVEwAAAAATAAAAAAkMAAAAAAAMAAAMAEGlyAALARAAQbHIAAsVDwAAAAQPAAAAAAkQAAAAAAAQAAAQAEHfyAALARIAQevIAAseEQAAAAARAAAAAAkSAAAAAAASAAASAAAaAAAAGhoaAEGiyQALDhoAAAAaGhoAAAAAAAAJAEHTyQALARQAQd/JAAsVFwAAAAAXAAAAAAkUAAAAAAAUAAAUAEGNygALARYAQZnKAAulCRUAAAAAFQAAAAAJFgAAAAAAFgAAFgAAMDEyMzQ1Njc4OUFCQ0RFRgAAAAAKAAAAZAAAAOgDAAAQJwAAoIYBAEBCDwCAlpgAAOH1BQDKmjsAAAAAAAAAADAwMDEwMjAzMDQwNTA2MDcwODA5MTAxMTEyMTMxNDE1MTYxNzE4MTkyMDIxMjIyMzI0MjUyNjI3MjgyOTMwMzEzMjMzMzQzNTM2MzczODM5NDA0MTQyNDM0NDQ1NDY0NzQ4NDk1MDUxNTI1MzU0NTU1NjU3NTg1OTYwNjE2MjYzNjQ2NTY2Njc2ODY5NzA3MTcyNzM3NDc1NzY3Nzc4Nzk4MDgxODI4Mzg0ODU4Njg3ODg4OTkwOTE5MjkzOTQ5NTk2OTc5ODk5TjEwX19jeHhhYml2MTE2X19zaGltX3R5cGVfaW5mb0UAAAAAqCgAADgmAAC4KQAATjEwX19jeHhhYml2MTE3X19jbGFzc190eXBlX2luZm9FAAAAqCgAAGgmAABcJgAATjEwX19jeHhhYml2MTE3X19wYmFzZV90eXBlX2luZm9FAAAAqCgAAJgmAABcJgAATjEwX19jeHhhYml2MTE5X19wb2ludGVyX3R5cGVfaW5mb0UAqCgAAMgmAAC8JgAATjEwX19jeHhhYml2MTIwX19mdW5jdGlvbl90eXBlX2luZm9FAAAAAKgoAAD4JgAAXCYAAE4xMF9fY3h4YWJpdjEyOV9fcG9pbnRlcl90b19tZW1iZXJfdHlwZV9pbmZvRQAAAKgoAAAsJwAAvCYAAAAAAACsJwAAIQAAACIAAAAjAAAAJAAAACUAAABOMTBfX2N4eGFiaXYxMjNfX2Z1bmRhbWVudGFsX3R5cGVfaW5mb0UAqCgAAIQnAABcJgAAdgAAAHAnAAC4JwAARG4AAHAnAADEJwAAYgAAAHAnAADQJwAAYwAAAHAnAADcJwAAaAAAAHAnAADoJwAAYQAAAHAnAAD0JwAAcwAAAHAnAAAAKAAAdAAAAHAnAAAMKAAAaQAAAHAnAAAYKAAAagAAAHAnAAAkKAAAbAAAAHAnAAAwKAAAbQAAAHAnAAA8KAAAeAAAAHAnAABIKAAAeQAAAHAnAABUKAAAZgAAAHAnAABgKAAAZAAAAHAnAABsKAAAAAAAAIwmAAAhAAAAJgAAACMAAAAkAAAAJwAAACgAAAApAAAAKgAAAAAAAADwKAAAIQAAACsAAAAjAAAAJAAAACcAAAAsAAAALQAAAC4AAABOMTBfX2N4eGFiaXYxMjBfX3NpX2NsYXNzX3R5cGVfaW5mb0UAAAAAqCgAAMgoAACMJgAAAAAAAOwmAAAhAAAALwAAACMAAAAkAAAAMAAAAAAAAAA8KQAAMQAAADIAAAAzAAAAU3Q5ZXhjZXB0aW9uAAAAAIAoAAAsKQAAAAAAAGgpAAAYAAAANAAAADUAAABTdDExbG9naWNfZXJyb3IAqCgAAFgpAAA8KQAAAAAAAJwpAAAYAAAANgAAADUAAABTdDEybGVuZ3RoX2Vycm9yAAAAAKgoAACIKQAAaCkAAFN0OXR5cGVfaW5mbwAAAACAKAAAqCkAQcDTAAsJCxUAAAAAAAAFAEHU0wALARsAQezTAAsOHAAAAB0AAABoKwAAAAQAQYTUAAsBAQBBlNQACwX/////CgBB2NQACwNgMQE=")||(Ve=ce,ce=I.locateFile?I.locateFile(Ve,f):f+Ve);var Ni=$=>{for(;$.length>0;)$.shift()(I)};I.noExitRuntime;function Co($){this.excPtr=$,this.ptr=$-24,this.set_type=function(j){RA[this.ptr+4>>2]=j},this.get_type=function(){return RA[this.ptr+4>>2]},this.set_destructor=function(j){RA[this.ptr+8>>2]=j},this.get_destructor=function(){return RA[this.ptr+8>>2]},this.set_caught=function(j){j=j?1:0,lA[this.ptr+12|0]=j},this.get_caught=function(){return lA[this.ptr+12|0]!=0},this.set_rethrown=function(j){j=j?1:0,lA[this.ptr+13|0]=j},this.get_rethrown=function(){return lA[this.ptr+13|0]!=0},this.init=function(j,vA){this.set_adjusted_ptr(0),this.set_type(j),this.set_destructor(vA)},this.set_adjusted_ptr=function(j){RA[this.ptr+16>>2]=j},this.get_adjusted_ptr=function(){return RA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(ba(this.get_type()))return RA[this.excPtr>>2];var j=this.get_adjusted_ptr();return j!==0?j:this.excPtr}}var to,so,ks,Gi=$=>{for(var j="",vA=$;tA[vA];)j+=to[tA[vA++]];return j},As={},Lo={},$i={},zt=$=>{throw new so($)},Ao=$=>{throw new ks($)},Ri=($,j,vA)=>{function jA(Pe){var rt=vA(Pe);rt.length!==$.length&&Ao("Mismatched type converter count");for(var ht=0;ht<$.length;++ht)Es($[ht],rt[ht])}$.forEach(function(Pe){$i[Pe]=j});var oe=new Array(j.length),ye=[],He=0;j.forEach((Pe,rt)=>{Lo.hasOwnProperty(Pe)?oe[rt]=Lo[Pe]:(ye.push(Pe),As.hasOwnProperty(Pe)||(As[Pe]=[]),As[Pe].push(()=>{oe[rt]=Lo[Pe],++He===ye.length&&jA(oe)}))}),ye.length===0&&jA(oe)};function Es($,j,vA={}){if(!("argPackAdvance"in j))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(jA,oe,ye={}){var He=oe.name;if(jA||zt(`type "${He}" must have a positive integer typeid pointer`),Lo.hasOwnProperty(jA)){if(ye.ignoreDuplicateRegistrations)return;zt(`Cannot register type '${He}' twice`)}if(Lo[jA]=oe,delete $i[jA],As.hasOwnProperty(jA)){var Pe=As[jA];delete As[jA],Pe.forEach(rt=>rt())}}($,j,vA)}var VA,Ee=$=>{zt($.$$.ptrType.registeredClass.name+" instance already deleted")},Je=!1,Ut=$=>{},ot=$=>{$.count.value-=1,$.count.value===0&&(j=>{j.smartPtr?j.smartPtrType.rawDestructor(j.smartPtr):j.ptrType.registeredClass.rawDestructor(j.ptr)})($)},ut=($,j,vA)=>{if(j===vA)return $;if(vA.baseClass===void 0)return null;var jA=ut($,j,vA.baseClass);return jA===null?null:vA.downcast(jA)},$t={},Zt=()=>Object.keys(pt).length,Ge=()=>{var $=[];for(var j in pt)pt.hasOwnProperty(j)&&$.push(pt[j]);return $},Xe=[],se=()=>{for(;Xe.length;){var $=Xe.pop();$.$$.deleteScheduled=!1,$.delete()}},ve=$=>{VA=$,Xe.length&&VA&&VA(se)},pt={},mo=($,j)=>(j=((vA,jA)=>{for(jA===void 0&&zt("ptr should not be undefined");vA.baseClass;)jA=vA.upcast(jA),vA=vA.baseClass;return jA})($,j),pt[j]),No=($,j)=>(j.ptrType&&j.ptr||Ao("makeClassHandle requires ptr and ptrType"),!!j.smartPtrType!=!!j.smartPtr&&Ao("Both smartPtrType and smartPtr must be specified"),j.count={value:1},Go(Object.create($,{$$:{value:j}})));function no($){var j=this.getPointee($);if(!j)return this.destructor($),null;var vA=mo(this.registeredClass,j);if(vA!==void 0){if(vA.$$.count.value===0)return vA.$$.ptr=j,vA.$$.smartPtr=$,vA.clone();var jA=vA.clone();return this.destructor($),jA}function oe(){return this.isSmartPointer?No(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:j,smartPtrType:this,smartPtr:$}):No(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var ye,He=this.registeredClass.getActualType(j),Pe=$t[He];if(!Pe)return oe.call(this);ye=this.isConst?Pe.constPointerType:Pe.pointerType;var rt=ut(j,this.registeredClass,ye.registeredClass);return rt===null?oe.call(this):this.isSmartPointer?No(ye.registeredClass.instancePrototype,{ptrType:ye,ptr:rt,smartPtrType:this,smartPtr:$}):No(ye.registeredClass.instancePrototype,{ptrType:ye,ptr:rt})}var Go=$=>typeof FinalizationRegistry>"u"?(Go=j=>j,$):(Je=new FinalizationRegistry(j=>{ot(j.$$)}),Ut=j=>Je.unregister(j),(Go=j=>{var vA=j.$$;if(vA.smartPtr){var jA={$$:vA};Je.register(j,jA,j)}return j})($));function An(){}var rn=($,j)=>Object.defineProperty(j,"name",{value:$}),ds=($,j,vA)=>{if($[j].overloadTable===void 0){var jA=$[j];$[j]=function(){return $[j].overloadTable.hasOwnProperty(arguments.length)||zt(`Function '${vA}' called with an invalid number of arguments (${arguments.length}) - expects one of (${$[j].overloadTable})!`),$[j].overloadTable[arguments.length].apply(this,arguments)},$[j].overloadTable=[],$[j].overloadTable[jA.argCount]=jA}};function an($,j,vA,jA,oe,ye,He,Pe){this.name=$,this.constructor=j,this.instancePrototype=vA,this.rawDestructor=jA,this.baseClass=oe,this.getActualType=ye,this.upcast=He,this.downcast=Pe,this.pureVirtualFunctions=[]}var So=($,j,vA)=>{for(;j!==vA;)j.upcast||zt(`Expected null or instance of ${vA.name}, got an instance of ${j.name}`),$=j.upcast($),j=j.baseClass;return $};function mA($,j){if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`);var vA=j.$$.ptrType.registeredClass;return So(j.$$.ptr,vA,this.registeredClass)}function qn($,j){var vA;if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),this.isSmartPointer?(vA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,vA),vA):0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&j.$$.ptrType.isConst&&zt(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);var jA=j.$$.ptrType.registeredClass;if(vA=So(j.$$.ptr,jA,this.registeredClass),this.isSmartPointer)switch(j.$$.smartPtr===void 0&&zt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:j.$$.smartPtrType===this?vA=j.$$.smartPtr:zt(`Cannot convert argument of type ${j.$$.smartPtrType?j.$$.smartPtrType.name:j.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:vA=j.$$.smartPtr;break;case 2:if(j.$$.smartPtrType===this)vA=j.$$.smartPtr;else{var oe=j.clone();vA=this.rawShare(vA,cn.toHandle(()=>oe.delete())),$!==null&&$.push(this.rawDestructor,vA)}break;default:zt("Unsupporting sharing policy")}return vA}function mr($,j){if(j===null)return this.isReference&&zt(`null is not a valid ${this.name}`),0;j.$$||zt(`Cannot pass "${as(j)}" as a ${this.name}`),j.$$.ptr||zt(`Cannot pass deleted object as a pointer of type ${this.name}`),j.$$.ptrType.isConst&&zt(`Cannot convert argument of type ${j.$$.ptrType.name} to parameter type ${this.name}`);var vA=j.$$.ptrType.registeredClass;return So(j.$$.ptr,vA,this.registeredClass)}function Cs($){return this.fromWireType(RA[$>>2])}function Zr($,j,vA,jA,oe,ye,He,Pe,rt,ht,_t){this.name=$,this.registeredClass=j,this.isReference=vA,this.isConst=jA,this.isSmartPointer=oe,this.pointeeType=ye,this.sharingPolicy=He,this.rawGetPointee=Pe,this.rawConstructor=rt,this.rawShare=ht,this.rawDestructor=_t,oe||j.baseClass!==void 0?this.toWireType=qn:jA?(this.toWireType=mA,this.destructorFunction=null):(this.toWireType=mr,this.destructorFunction=null)}var Yi,Rs,rr=[],en=$=>{var j=rr[$];return j||($>=rr.length&&(rr.length=$+1),rr[$]=j=Yi.get($)),j},wn=($,j,vA)=>$.includes("j")?((jA,oe,ye)=>{var He=I["dynCall_"+jA];return ye&&ye.length?He.apply(null,[oe].concat(ye)):He.call(null,oe)})($,j,vA):en(j).apply(null,vA),jt=($,j)=>{var vA,jA,oe,ye=($=Gi($)).includes("j")?(vA=$,jA=j,oe=[],function(){return oe.length=0,Object.assign(oe,arguments),wn(vA,jA,oe)}):en(j);return typeof ye!="function"&&zt(`unknown function pointer with signature ${$}: ${j}`),ye},yg=$=>{var j=Ea($),vA=Gi(j);return yn(j),vA},Pn=($,j)=>{var vA=[],jA={};throw j.forEach(function oe(ye){jA[ye]||Lo[ye]||($i[ye]?$i[ye].forEach(oe):(vA.push(ye),jA[ye]=!0))}),new Rs(`${$}: `+vA.map(yg).join([", "]))},bn=($,j)=>{for(var vA=[],jA=0;jA<$;jA++)vA.push(RA[j+4*jA>>2]);return vA},Js=$=>{for(;$.length;){var j=$.pop();$.pop()(j)}};function fr($,j,vA,jA,oe,ye){var He=j.length;He<2&&zt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Pe=j[1]!==null&&vA!==null,rt=!1,ht=1;ht($ instanceof Object||zt(`${vA} with invalid "this": ${$}`),$ instanceof j.registeredClass.constructor||zt(`${vA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||zt(`cannot call emscripten binding method ${vA} on deleted object`),So($.$$.ptr,$.$$.ptrType.registeredClass,j.registeredClass));function yr(){this.allocated=[void 0],this.freelist=[]}var fo=new yr,gn=$=>{$>=fo.reserved&&--fo.get($).refcount===0&&fo.free($)},Ml=()=>{for(var $=0,j=fo.reserved;j($||zt("Cannot use deleted val. handle = "+$),fo.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return fo.allocate({refcount:1,value:$})}}};function Dr($){return this.fromWireType(gA[$>>2])}var Us,Jc,fs,as=$=>{if($===null)return"null";var j=typeof $;return j==="object"||j==="array"||j==="function"?$.toString():""+$},wu=($,j)=>{switch(j){case 4:return function(vA){return this.fromWireType(HA[vA>>2])};case 8:return function(vA){return this.fromWireType(ZA[vA>>3])};default:throw new TypeError(`invalid float width (${j}): ${$}`)}},Wa=($,j,vA)=>{switch(j){case 1:return vA?jA=>lA[jA|0]:jA=>tA[jA|0];case 2:return vA?jA=>BA[jA>>1]:jA=>IA[jA>>1];case 4:return vA?jA=>gA[jA>>2]:jA=>RA[jA>>2];default:throw new TypeError(`invalid integer width (${j}): ${$}`)}},hs=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,sg=($,j,vA)=>{for(var jA=j+vA,oe=j;$[oe]&&!(oe>=jA);)++oe;if(oe-j>16&&$.buffer&&hs)return hs.decode($.subarray(j,oe));for(var ye="";j>10,56320|1023&ht)}}else ye+=String.fromCharCode((31&He)<<6|Pe)}else ye+=String.fromCharCode(He)}return ye},qI=($,j)=>$?sg(tA,$,j):"",es=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,eo=($,j)=>{for(var vA=$,jA=vA>>1,oe=jA+j/2;!(jA>=oe)&&IA[jA];)++jA;if((vA=jA<<1)-$>32&&es)return es.decode(tA.subarray($,vA));for(var ye="",He=0;!(He>=j/2);++He){var Pe=BA[$+2*He>>1];if(Pe==0)break;ye+=String.fromCharCode(Pe)}return ye},pc=($,j,vA)=>{if(vA===void 0&&(vA=2147483647),vA<2)return 0;for(var jA=j,oe=(vA-=2)<2*$.length?vA/2:$.length,ye=0;ye>1]=He,j+=2}return BA[j>>1]=0,j-jA},ng=$=>2*$.length,Dg=($,j)=>{for(var vA=0,jA="";!(vA>=j/4);){var oe=gA[$+4*vA>>2];if(oe==0)break;if(++vA,oe>=65536){var ye=oe-65536;jA+=String.fromCharCode(55296|ye>>10,56320|1023&ye)}else jA+=String.fromCharCode(oe)}return jA},ua=($,j,vA)=>{if(vA===void 0&&(vA=2147483647),vA<4)return 0;for(var jA=j,oe=jA+vA-4,ye=0;ye<$.length;++ye){var He=$.charCodeAt(ye);if(He>=55296&&He<=57343&&(He=65536+((1023&He)<<10)|1023&$.charCodeAt(++ye)),gA[j>>2]=He,(j+=4)+4>oe)break}return gA[j>>2]=0,j-jA},bo=$=>{for(var j=0,vA=0;vA<$.length;++vA){var jA=$.charCodeAt(vA);jA>=55296&&jA<=57343&&++vA,j+=4}return j},Xr=($,j)=>{var vA=Lo[$];return vA===void 0&&zt(j+" has unknown type "+yg($)),vA},To=($,j,vA)=>{var jA=[],oe=$.toWireType(jA,vA);return jA.length&&(RA[j>>2]=cn.toHandle(jA)),oe},Hc={},Kn=[],Hs=Reflect.construct,Sg=[null,[],[]],mc=($,j)=>{var vA=Sg[$];j===0||j===10?(($===1?N:L)(sg(vA,0)),vA.length=0):vA.push(j)};(()=>{for(var $=new Array(256),j=0;j<256;++j)$[j]=String.fromCharCode(j);to=$})(),so=I.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},ks=I.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign(An.prototype,{isAliasOf($){if(!(this instanceof An)||!($ instanceof An))return!1;var j=this.$$.ptrType.registeredClass,vA=this.$$.ptr;$.$$=$.$$;for(var jA=$.$$.ptrType.registeredClass,oe=$.$$.ptr;j.baseClass;)vA=j.upcast(vA),j=j.baseClass;for(;jA.baseClass;)oe=jA.upcast(oe),jA=jA.baseClass;return j===jA&&vA===oe},clone(){if(this.$$.ptr||Ee(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,j=Go(Object.create(Object.getPrototypeOf(this),{$$:{value:($=this.$$,{count:$.count,deleteScheduled:$.deleteScheduled,preservePointerOnDelete:$.preservePointerOnDelete,ptr:$.ptr,ptrType:$.ptrType,smartPtr:$.smartPtr,smartPtrType:$.smartPtrType})}}));return j.$$.count.value+=1,j.$$.deleteScheduled=!1,j},delete(){this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&zt("Object already scheduled for deletion"),Ut(this),ot(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)},isDeleted(){return!this.$$.ptr},deleteLater(){return this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&zt("Object already scheduled for deletion"),Xe.push(this),Xe.length===1&&VA&&VA(se),this.$$.deleteScheduled=!0,this}}),I.getInheritedInstanceCount=Zt,I.getLiveInheritedInstances=Ge,I.flushPendingDeletes=se,I.setDelayFunction=ve,Object.assign(Zr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:Cs,deleteObject($){$!==null&&$.delete()},fromWireType:no}),Rs=I.UnboundTypeError=(Us=Error,(fs=rn(Jc="UnboundTypeError",function($){this.name=Jc,this.message=$;var j=new Error($).stack;j!==void 0&&(this.stack=this.toString()+` +`+j.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(Us.prototype),fs.prototype.constructor=fs,fs.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},fs),Object.assign(yr.prototype,{get($){return this.allocated[$]},has($){return this.allocated[$]!==void 0},allocate($){var j=this.freelist.pop()||this.allocated.length;return this.allocated[j]=$,j},free($){this.allocated[$]=void 0,this.freelist.push($)}}),fo.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),fo.reserved=fo.allocated.length,I.count_emval_handles=Ml;var fn,Ga={w:($,j,vA)=>{throw new Co($).init(j,vA),$},q:($,j,vA,jA,oe)=>{},u:($,j,vA,jA)=>{Es($,{name:j=Gi(j),fromWireType:function(oe){return!!oe},toWireType:function(oe,ye){return ye?vA:jA},argPackAdvance:8,readValueFromPointer:function(oe){return this.fromWireType(tA[oe])},destructorFunction:null})},y:($,j,vA,jA,oe,ye,He,Pe,rt,ht,_t,Vt,ui)=>{_t=Gi(_t),ye=jt(oe,ye),Pe&&(Pe=jt(He,Pe)),ht&&(ht=jt(rt,ht)),ui=jt(Vt,ui);var It=(Yt=>{if(Yt===void 0)return"_unknown";var qi=(Yt=Yt.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return qi>=48&&qi<=57?`_${Yt}`:Yt})(_t);((Yt,qi,Wi)=>{I.hasOwnProperty(Yt)?(zt(`Cannot register public name '${Yt}' twice`),ds(I,Yt,Yt),I.hasOwnProperty(Wi)&&zt(`Cannot register multiple overloads of a function with the same number of arguments (${Wi})!`),I[Yt].overloadTable[Wi]=qi):I[Yt]=qi})(It,function(){Pn(`Cannot construct ${_t} due to unbound types`,[jA])}),Ri([$,j,vA],jA?[jA]:[],function(Yt){var qi,Wi;Yt=Yt[0],Wi=jA?(qi=Yt.registeredClass).instancePrototype:An.prototype;var qs=rn(_t,function(){if(Object.getPrototypeOf(this)!==vi)throw new so("Use 'new' to construct "+_t);if(zo.constructor_body===void 0)throw new so(_t+" has no accessible constructor");var Yn=zo.constructor_body[arguments.length];if(Yn===void 0)throw new so(`Tried to invoke ctor of ${_t} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(zo.constructor_body).toString()}) parameters instead!`);return Yn.apply(this,arguments)}),vi=Object.create(Wi,{constructor:{value:qs}});qs.prototype=vi;var zo=new an(_t,qs,vi,ui,qi,ye,Pe,ht);zo.baseClass&&(zo.baseClass.__derivedClasses===void 0&&(zo.baseClass.__derivedClasses=[]),zo.baseClass.__derivedClasses.push(zo));var Mg=new Zr(_t,zo,!0,!1,!1),ar=new Zr(_t+"*",zo,!1,!1,!1),Sr=new Zr(_t+" const*",zo,!1,!0,!1);return $t[$]={pointerType:ar,constPointerType:Sr},((Yn,vl,Ks)=>{I.hasOwnProperty(Yn)||Ao("Replacing nonexistant public symbol"),I[Yn].overloadTable!==void 0&&Ks!==void 0?I[Yn].overloadTable[Ks]=vl:(I[Yn]=vl,I[Yn].argCount=Ks)})(It,qs),[Mg,ar,Sr]})},x:($,j,vA,jA,oe,ye)=>{var He=bn(j,vA);oe=jt(jA,oe),Ri([],[$],function(Pe){var rt=`constructor ${(Pe=Pe[0]).name}`;if(Pe.registeredClass.constructor_body===void 0&&(Pe.registeredClass.constructor_body=[]),Pe.registeredClass.constructor_body[j-1]!==void 0)throw new so(`Cannot register multiple constructors with identical number of parameters (${j-1}) for class '${Pe.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Pe.registeredClass.constructor_body[j-1]=()=>{Pn(`Cannot construct ${Pe.name} due to unbound types`,He)},Ri([],He,ht=>(ht.splice(1,0,null),Pe.registeredClass.constructor_body[j-1]=fr(rt,ht,null,oe,ye),[])),[]})},i:($,j,vA,jA,oe,ye,He,Pe,rt)=>{var ht=bn(vA,jA);j=(_t=>{const Vt=(_t=_t.trim()).indexOf("(");return Vt!==-1?_t.substr(0,Vt):_t})(j=Gi(j)),ye=jt(oe,ye),Ri([],[$],function(_t){var Vt=`${(_t=_t[0]).name}.${j}`;function ui(){Pn(`Cannot call ${Vt} due to unbound types`,ht)}j.startsWith("@@")&&(j=Symbol[j.substring(2)]),Pe&&_t.registeredClass.pureVirtualFunctions.push(j);var It=_t.registeredClass.instancePrototype,Yt=It[j];return Yt===void 0||Yt.overloadTable===void 0&&Yt.className!==_t.name&&Yt.argCount===vA-2?(ui.argCount=vA-2,ui.className=_t.name,It[j]=ui):(ds(It,j,Vt),It[j].overloadTable[vA-2]=ui),Ri([],ht,function(qi){var Wi=fr(Vt,qi,_t,ye,He);return It[j].overloadTable===void 0?(Wi.argCount=vA-2,It[j]=Wi):It[j].overloadTable[vA-2]=Wi,[]}),[]})},k:($,j,vA,jA,oe,ye,He,Pe,rt,ht)=>{j=Gi(j),oe=jt(jA,oe),Ri([],[$],function(_t){var Vt=`${(_t=_t[0]).name}.${j}`,ui={get(){Pn(`Cannot access ${Vt} due to unbound types`,[vA,He])},enumerable:!0,configurable:!0};return ui.set=rt?()=>Pn(`Cannot access ${Vt} due to unbound types`,[vA,He]):It=>zt(Vt+" is a read-only property"),Object.defineProperty(_t.registeredClass.instancePrototype,j,ui),Ri([],rt?[vA,He]:[vA],function(It){var Yt=It[0],qi={get(){var qs=xn(this,_t,Vt+" getter");return Yt.fromWireType(oe(ye,qs))},enumerable:!0};if(rt){rt=jt(Pe,rt);var Wi=It[1];qi.set=function(qs){var vi=xn(this,_t,Vt+" setter"),zo=[];rt(ht,vi,Wi.toWireType(zo,qs)),Js(zo)}}return Object.defineProperty(_t.registeredClass.instancePrototype,j,qi),[]}),[]})},t:($,j)=>{Es($,{name:j=Gi(j),fromWireType:vA=>{var jA=cn.toValue(vA);return gn(vA),jA},toWireType:(vA,jA)=>cn.toHandle(jA),argPackAdvance:8,readValueFromPointer:Dr,destructorFunction:null})},p:($,j,vA)=>{Es($,{name:j=Gi(j),fromWireType:jA=>jA,toWireType:(jA,oe)=>oe,argPackAdvance:8,readValueFromPointer:wu(j,vA),destructorFunction:null})},g:($,j,vA,jA,oe)=>{j=Gi(j);var ye=rt=>rt;if(jA===0){var He=32-8*vA;ye=rt=>rt<>>He}var Pe=j.includes("unsigned");Es($,{name:j,fromWireType:ye,toWireType:Pe?function(rt,ht){return this.name,ht>>>0}:function(rt,ht){return this.name,ht},argPackAdvance:8,readValueFromPointer:Wa(j,vA,jA!==0),destructorFunction:null})},a:($,j,vA)=>{var jA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][j];function oe(ye){var He=RA[ye>>2],Pe=RA[ye+4>>2];return new jA(lA.buffer,Pe,He)}Es($,{name:vA=Gi(vA),fromWireType:oe,argPackAdvance:8,readValueFromPointer:oe},{ignoreDuplicateRegistrations:!0})},o:($,j)=>{var vA=(j=Gi(j))==="std::string";Es($,{name:j,fromWireType(jA){var oe,ye=RA[jA>>2],He=jA+4;if(vA)for(var Pe=He,rt=0;rt<=ye;++rt){var ht=He+rt;if(rt==ye||tA[ht]==0){var _t=qI(Pe,ht-Pe);oe===void 0?oe=_t:(oe+="\0",oe+=_t),Pe=ht+1}}else{var Vt=new Array(ye);for(rt=0;rt{for(var ui=0,It=0;It=55296&&Yt<=57343?(ui+=4,++It):ui+=3}return ui})(oe):oe.length;var Pe=ys(4+ye+1),rt=Pe+4;if(RA[Pe>>2]=ye,vA&&He)((Vt,ui,It,Yt)=>{if(!(Yt>0))return 0;for(var qi=It,Wi=It+Yt-1,qs=0;qs=55296&&vi<=57343&&(vi=65536+((1023&vi)<<10)|1023&Vt.charCodeAt(++qs)),vi<=127){if(It>=Wi)break;ui[It++]=vi}else if(vi<=2047){if(It+1>=Wi)break;ui[It++]=192|vi>>6,ui[It++]=128|63&vi}else if(vi<=65535){if(It+2>=Wi)break;ui[It++]=224|vi>>12,ui[It++]=128|vi>>6&63,ui[It++]=128|63&vi}else{if(It+3>=Wi)break;ui[It++]=240|vi>>18,ui[It++]=128|vi>>12&63,ui[It++]=128|vi>>6&63,ui[It++]=128|63&vi}}ui[It]=0})(oe,tA,rt,ye+1);else if(He)for(var ht=0;ht255&&(yn(rt),zt("String has UTF-16 code units that do not fit in 8 bits")),tA[rt+ht]=_t}else for(ht=0;ht{var jA,oe,ye,He,Pe;vA=Gi(vA),j===2?(jA=eo,oe=pc,He=ng,ye=()=>IA,Pe=1):j===4&&(jA=Dg,oe=ua,He=bo,ye=()=>RA,Pe=2),Es($,{name:vA,fromWireType:rt=>{for(var ht,_t=RA[rt>>2],Vt=ye(),ui=rt+4,It=0;It<=_t;++It){var Yt=rt+4+It*j;if(It==_t||Vt[Yt>>Pe]==0){var qi=jA(ui,Yt-ui);ht===void 0?ht=qi:(ht+="\0",ht+=qi),ui=Yt+j}}return yn(rt),ht},toWireType:(rt,ht)=>{typeof ht!="string"&&zt(`Cannot pass non-string to C++ string type ${vA}`);var _t=He(ht),Vt=ys(4+_t+j);return RA[Vt>>2]=_t>>Pe,oe(ht,Vt+4,_t+j),rt!==null&&rt.push(yn,Vt),Vt},argPackAdvance:8,readValueFromPointer:Dr,destructorFunction(rt){yn(rt)}})},v:($,j)=>{Es($,{isVoid:!0,name:j=Gi(j),argPackAdvance:0,fromWireType:()=>{},toWireType:(vA,jA)=>{}})},j:($,j,vA)=>($=cn.toValue($),j=Xr(j,"emval::as"),To(j,vA,$)),e:($,j,vA,jA,oe)=>{var ye,He;return($=Kn[$])(j=cn.toValue(j),j[vA=(He=Hc[ye=vA])===void 0?Gi(ye):He],jA,oe)},d:gn,f:($,j,vA)=>{var jA=((ht,_t)=>{for(var Vt=new Array(ht),ui=0;ui>2],"parameter "+ui);return Vt})($,j),oe=jA.shift();$--;var ye,He,Pe=new Array($),rt=`methodCaller<(${jA.map(ht=>ht.name).join(", ")}) => ${oe.name}>`;return ye=rn(rt,(ht,_t,Vt,ui)=>{for(var It=0,Yt=0;Yt<$;++Yt)Pe[Yt]=jA[Yt].readValueFromPointer(ui+It),It+=jA[Yt].argPackAdvance;var qi=vA===1?Hs(_t,Pe):_t.apply(ht,Pe);for(Yt=0;Yt<$;++Yt)jA[Yt].deleteObject&&jA[Yt].deleteObject(Pe[Yt]);return To(oe,Vt,qi)}),He=Kn.length,Kn.push(ye),He},c:$=>{$>4&&(fo.get($).refcount+=1)},b:$=>{var j=cn.toValue($);Js(j),gn($)},h:($,j)=>{var vA=($=Xr($,"_emval_take_value")).readValueFromPointer(j);return cn.toHandle(vA)},m:()=>{ct("")},s:($,j,vA)=>tA.copyWithin($,j,j+vA),r:$=>{tA.length,ct("OOM")},n:($,j,vA,jA)=>{for(var oe=0,ye=0;ye>2],Pe=RA[j+4>>2];j+=8;for(var rt=0;rt>2]=oe,0}},In=function(){var $={a:Ga};function j(vA,jA){var oe,ye;return In=vA.exports,_=In.z,oe=_.buffer,I.HEAP8=lA=new Int8Array(oe),I.HEAP16=BA=new Int16Array(oe),I.HEAPU8=tA=new Uint8Array(oe),I.HEAPU16=IA=new Uint16Array(oe),I.HEAP32=gA=new Int32Array(oe),I.HEAPU32=RA=new Uint32Array(oe),I.HEAPF32=HA=new Float32Array(oe),I.HEAPF64=ZA=new Float64Array(oe),Yi=In.C,ye=In.A,ae.unshift(ye),function(){if(lt--,I.monitorRunDependencies&&I.monitorRunDependencies(lt),lt==0&&wt){var He=wt;wt=null,He()}}(),In}if(lt++,I.monitorRunDependencies&&I.monitorRunDependencies(lt),I.instantiateWasm)try{return I.instantiateWasm($,j)}catch(vA){L(`Module.instantiateWasm callback failed with error: ${vA}`),c(vA)}return oi(0,ce,$,function(vA){j(vA.instance)}).catch(c),{}}(),ys=$=>(ys=In.B)($),Ea=$=>(Ea=In.D)($),yn=$=>(yn=In.E)($),ba=$=>(ba=In.F)($);I.dynCall_jiji=($,j,vA,jA,oe)=>(I.dynCall_jiji=In.G)($,j,vA,jA,oe),I._vertexShaderSource=10688;function Sa(){function $(){fn||(fn=!0,I.calledRun=!0,KA||(Ni(ae),n(I),I.onRuntimeInitialized&&I.onRuntimeInitialized(),function(){if(I.postRun)for(typeof I.postRun=="function"&&(I.postRun=[I.postRun]);I.postRun.length;)We(I.postRun.shift());Ni(gt)}()))}lt>0||(function(){if(I.preRun)for(typeof I.preRun=="function"&&(I.preRun=[I.preRun]);I.preRun.length;)dt(I.preRun.shift());Ni(me)}(),lt>0||(I.setStatus?(I.setStatus("Running..."),setTimeout(function(){setTimeout(function(){I.setStatus("")},1),$()},1)):$()))}if(wt=function $(){fn||Sa(),fn||(wt=$)},I.preInit)for(typeof I.preInit=="function"&&(I.preInit=[I.preInit]);I.preInit.length>0;)I.preInit.pop()();return Sa(),i.ready}})(),GcA=NcA,o3=0,jX=class WX{constructor(i){this.core=i,VL(this,"seq"),VL(this,"_core"),VL(this,"log"),VL(this,"beautyParams"),o3+=1,this.seq=o3,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${o3}`}),this.log.info("created")}getName(){return WX.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return _cA(this._core);case"stop":return TcA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await GcA()),this._core.room.videoManager.renderMode="webgl";const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async update(i){const n=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,c=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,I=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:n,brightness:c,ruddy:I})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};VL(jX,"Name","BasicBeauty");var zX=jX,bcA=zX;const kcA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:zX,default:bcA},Symbol.toStringTag,{value:"Module"})),LcA=HU(kcA);var UcA=Object.defineProperty,FcA=(t,i,n)=>i in t?UcA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,BY=(t,i,n)=>FcA(t,typeof i!="symbol"?i+"":i,n),OcA={name:"option",required:!0,properties:{sourceLanguage:{type:"string",required:!0},translationLanguages:{type:["string","array"],required:!1},userIdsToTranscribe:{type:["string","array"],required:!1},transcriberRobotId:{type:"string",required:!1}}},PcA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},xcA=new Set([2002,4003]),ZX=class XX{constructor(i){this.core=i,BY(this,"disableRandomCall",!0),BY(this,"activeTranscriberMap",new Map),BY(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return XX.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return OcA;case"update":return{};case"stop":return PcA}}async start(i){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});const{sourceLanguage:C,translationLanguages:f,userIdsToTranscribe:w="all",transcriberRobotId:_}=i,N=_||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,L={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:N,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:C,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};f&&f.length>0&&(L.translationParams.mode=1,L.translationParams.targetLangs=Array.isArray(f)?f:[f]),w==="all"?L.subscribeParams.subUsers=[]:Array.isArray(w)?L.subscribeParams.subUsers=w.map(q=>({userId:q,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):w&&(L.subscribeParams.subUsers=[{userId:w,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)}]);try{this._log.info(`start_cloud_transcription ${JSON.stringify(L)}`);const q=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:L,retries:0}),{code:lA,data:tA}=q.data;if(lA!==0){const IA=((n=q.data)==null?void 0:n.message)||"";throw this._log.error("start_cloud_transcription failed",{extraCode:lA,reason:IA,data:tA}),new c({code:I.SERVER_ERROR,extraCode:lA,message:IA})}const{taskId:BA}=tA;if(!BA)throw this._log.error("taskId is required",{data:q.data}),new c({code:I.SERVER_ERROR,message:"taskId is required"});return this.activeTranscriberMap.set(BA,i),this._log.info(`start_cloud_transcription success ${BA}, activeSize: ${this.activeTranscriberMap.size}`),BA}catch(q){throw this._log.error("start_cloud_transcription failed",{error:q}),q}}async update(){}async stop({transcriberRobotId:i}){var n;const{RtcError:c,ErrorCode:I}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new c({code:I.ENV_NOT_SUPPORTED});try{const C=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(C.data.code!==0){const f=C.data.code,w=((n=C.data)==null?void 0:n.message)||"";if(!xcA.has(f))throw this._log.error("stop_cloud_transcription failed",{extraCode:f,reason:w,data:C.data.data}),new c({code:I.SERVER_ERROR,extraCode:f,message:w});this._log.warn("stop_cloud_transcription ignored error",{extraCode:f,reason:w,data:C.data.data})}this.activeTranscriberMap.delete(i)}catch(C){throw this._log.error("stop_cloud_transcription failed",{error:C}),C}}destroy(){this.activeTranscriberMap.clear()}};BY(ZX,"Name","RealtimeTranscriber");var $X=ZX,YcA=$X;const VcA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:$X,default:YcA},Symbol.toStringTag,{value:"Module"})),JcA=HU(VcA);var HcA=Object.create,jU=Object.defineProperty,qcA=Object.defineProperties,A7=Object.getOwnPropertyDescriptor,KcA=Object.getOwnPropertyDescriptors,e7=Object.getOwnPropertyNames,LY=Object.getOwnPropertySymbols,jcA=Object.getPrototypeOf,I4=Object.prototype.hasOwnProperty,t7=Object.prototype.propertyIsEnumerable,tW=(t,i,n)=>i in t?jU(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n,Rn=(t,i)=>{for(var n in i||(i={}))I4.call(i,n)&&tW(t,n,i[n]);if(LY)for(var n of LY(i))t7.call(i,n)&&tW(t,n,i[n]);return t},gB=(t,i)=>qcA(t,KcA(i)),WcA=(t,i)=>{var n={};for(var c in t)I4.call(t,c)&&i.indexOf(c)<0&&(n[c]=t[c]);if(t!=null&&LY)for(var c of LY(t))i.indexOf(c)<0&&t7.call(t,c)&&(n[c]=t[c]);return n},WU=(t,i)=>function(){return i||(0,t[e7(t)[0]])((i={exports:{}}).exports,i),i.exports},u4=(t,i)=>{for(var n in i)jU(t,n,{get:i[n],enumerable:!0})},zcA=(t,i,n,c)=>{if(i&&typeof i=="object"||typeof i=="function")for(let I of e7(i))I4.call(t,I)||I===n||jU(t,I,{get:()=>i[I],enumerable:!(c=A7(i,I))||c.enumerable});return t},mT=(t,i,n)=>(n=t!=null?HcA(jcA(t)):{},zcA(jU(n,"default",{value:t,enumerable:!0}),t)),Cc=(t,i,n,c)=>{for(var I,C=A7(i,n),f=t.length-1;f>=0;f--)(I=t[f])&&(C=I(i,n,C)||C);return C&&jU(i,n,C),C},Be=(t,i,n)=>tW(t,typeof i!="symbol"?i+"":i,n),zU=WU({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var n=Object.prototype.hasOwnProperty,c="~";function I(){}function C(N,L,q){this.fn=N,this.context=L,this.once=q||!1}function f(N,L,q,lA,tA){if(typeof q!="function")throw new TypeError("The listener must be a function");var BA=new C(q,lA||N,tA),IA=c?c+L:L;return N._events[IA]?N._events[IA].fn?N._events[IA]=[N._events[IA],BA]:N._events[IA].push(BA):(N._events[IA]=BA,N._eventsCount++),N}function w(N,L){--N._eventsCount===0?N._events=new I:delete N._events[L]}function _(){this._events=new I,this._eventsCount=0}Object.create&&(I.prototype=Object.create(null),new I().__proto__||(c=!1)),_.prototype.eventNames=function(){var N,L,q=[];if(this._eventsCount===0)return q;for(L in N=this._events)n.call(N,L)&&q.push(c?L.slice(1):L);return Object.getOwnPropertySymbols?q.concat(Object.getOwnPropertySymbols(N)):q},_.prototype.listeners=function(N){var L=c?c+N:N,q=this._events[L];if(!q)return[];if(q.fn)return[q.fn];for(var lA=0,tA=q.length,BA=new Array(tA);lA1&&(f[_[0]]=void 0),f};t.parseParams=function(f){return f.split(/;\s?/).reduce(C,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(f){return f.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(f){for(var w=[],_=f.split(" ").map(i),N=0;N<_.length;N+=3)w.push({component:_[N],ip:_[N+1],port:_[N+2]});return w},t.parseImageAttributes=function(f){return f.split(" ").map(function(w){return w.substring(1,w.length-1).split(",").reduce(C,{})})},t.parseSimulcastStreamList=function(f){return f.split(";").map(function(w){return w.split(",").map(function(_){var N,L=!1;return _[0]!=="~"?N=i(_):(N=i(_.substring(1,_.length)),L=!0),{scid:N,paused:L}})})}}}),XcA=WU({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(t,i){var n=E4(),c=/%[sdv%]/g,I=function(_){var N=1,L=arguments,q=L.length;return _.replace(c,function(lA){if(N>=q)return lA;var tA=L[N];switch(N+=1,lA){case"%%":return"%";case"%s":return String(tA);case"%d":return Number(tA);case"%v":return""}})},C=function(_,N,L){var q=[_+"="+(N.format instanceof Function?N.format(N.push?L:L[N.name]):N.format)];if(N.names)for(var lA=0;lA({type:"object",required:i,properties:{canvasColor:{required:!1,type:["string",CanvasGradient,CanvasPattern]},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},frameRate:{required:!1,type:"number",notLessThanZero:!0,min:1,max:60}},validate(r,l,I){const{RtcError:h,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(!r)return;const{width:_,height:G}=r;if(_&&G&&_*G>8294400)throw new h({code:f.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),kX=t=>({required:!1,type:["string",HTMLElement,null],validate(i,r,l){const{RtcError:I,ErrorCode:h,ErrorCodeDictionary:f}=t.errorModule;if(t.utils.isString(i)&&!document.getElementById(i))throw new I({code:h.INVALID_PARAMETER,extraCode:f.INVALID_ELEMENT_ID,fnName:l,messageParams:{key:r}})}}),xU=(t,i=!0)=>({type:"object",required:i,properties:Rn({},DcA),validate(r,l,I){const{RtcError:h,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(r){if(r.fillMode&&!["contain","cover","fill"].includes(r.fillMode))throw new h({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:I});if(r.rotation&&![0,90,180,270].includes(r.rotation))throw new h({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:I})}}}),LX=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},cameraId:{required:!1,type:"string"},videoTrack:{required:!1,instanceof:MediaStreamTrack},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},layout:Rn({},xU(t))}}}),UX=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},captureElement:{required:!1,type:HTMLElement},preferDisplaySurface:{required:!1,type:"string"},layout:Rn({},xU(t))},validate(i,r,l){const{RtcError:I,ErrorCode:h,ErrorCodeDictionary:f}=t.errorModule;if(!t.rtcDectection.isScreenCaptureApiAvailable())throw new I({code:h.ENV_NOT_SUPPORTED,fnName:l,extraCode:f.NOT_SUPPORTED_SCREEN_SHARE})}}}),FX=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},content:{required:!0,type:"string"},font:{required:!1,type:"string"},color:{required:!1,type:["string",CanvasGradient,CanvasPattern]},layout:Rn({},xU(t))}}}),OX=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},xU(t))}}}),PX=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},xU(t))}}});function ScA(t){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:Rn({},kX(t)),canvasInfo:Rn({},bX(t,!0)),camera:Rn({},LX(t)),screen:Rn({},UX(t)),text:Rn({},FX(t)),image:Rn({},OX(t)),video:Rn({},PX(t))},validate(i,r,l,I){const{RtcError:h,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(t.environment.isMobile())throw new h({code:f.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:_}=i;if(_&&!t.utils.isFunction(_))throw new h({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,fnName:l,messageParams:{key:"onScreenShareStop",value:typeof _,rule:{type:"Function"}}})}}}function McA(t){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:Rn({},kX(t)),canvasInfo:Rn({},bX(t)),camera:Rn({},LX(t)),screen:Rn({},UX(t)),text:Rn({},FX(t)),image:Rn({},OX(t)),video:Rn({},PX(t))}}}function vcA(t){return{name:"StopVideoMixerOptions",required:!1}}var xX=(t=>(t[t.INVALID_PARAMETER=4096]="INVALID_PARAMETER",t[t.INVALID_OPERATION=4097]="INVALID_OPERATION",t[t.NOT_SUPPORTED=4098]="NOT_SUPPORTED",t[t.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",t[t.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",t[t.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",t[t.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",t[t.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",t[t.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",t[t.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",t[t.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",t[t.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",t[t.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",t[t.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",t[t.CLIENT_BANNED=16448]="CLIENT_BANNED",t[t.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",t[t.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",t[t.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",t[t.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",t[t.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",t[t.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",t[t.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",t[t.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",t[t.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",t[t.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",t[t.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",t[t.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",t[t.API_CALL_ABORTED=16461]="API_CALL_ABORTED",t[t.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",t[t.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",t[t.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",t[t.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",t[t.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",t[t.UNKNOWN=65535]="UNKNOWN",t))(xX||{}),qg=xX,RcA=function(t){for(const i in qg)if(qg[i]===t)return i;return"UNKNOWN"},wcA=class extends Error{constructor({name:t="RtcError",message:i,code:r=qg.UNKNOWN,extraCode:l=0,constraint:I}){const h=`<${RcA(r)} 0x${r.toString(16)}>`,f=`${i}${I?` constraint: ${I}`:""}${i?.includes(h)?"":` ${h}`}`;super(f),de(this,"code"),de(this,"extraCode"),de(this,"message"),de(this,"originMessage"),de(this,"name"),de(this,"constraint"),this.code=r,this.extraCode=l,this.name=t,this.message=f,this.constraint=I,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},ml=wcA,_cA=0,jW=function(){return Date.now()+_cA},YX=function(){const t=new Date;return t.setTime(jW()),t.toLocaleString()},TcA=function(t){let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},NcA={};qW(NcA,{REPORT_TYPE:()=>g7,buildSSOPackage:()=>XW,bytes2ms:()=>nlA,calculateScaleResolutionDownNumber:()=>r7,concatArrayBuffers:()=>TlA,convertObjectNumberToInt:()=>s7,copyProperties:()=>slA,deepClone:()=>vY,deepCloneBasic:()=>W3,deepMerge:()=>t7,delay:()=>rT,fibonacci:()=>ZW,formatedTime:()=>DlA,getConstructorName:()=>IlA,getContainerFromElement:()=>flA,getEnv:()=>XcA,getFirst16Bits:()=>GlA,getInternalVersion:()=>ClA,getLast16Bits:()=>NlA,getLoggerUrl:()=>WW,getMediaStreamTrackInfo:()=>RlA,getMuteStateFromFlag:()=>e7,getNetworkType:()=>zW,getNumNetworkType:()=>olA,getReconnectionTimeout:()=>glA,getStringByteLength:()=>SlA,getTestSignalDomain:()=>AlA,getTurnServer:()=>QlA,getUint32Version:()=>o7,getValueType:()=>Nv,getViewListFromView:()=>mlA,glog:()=>alA,ipv4ToUint32:()=>plA,isArray:()=>Ah,isAudioWorkletSupported:()=>ulA,isBoolean:()=>fv,isConstructor:()=>A7,isEmpty:()=>BlA,isFunction:()=>mv,isLangChinese:()=>zy,isMediaStreamTrack:()=>clA,isNumber:()=>Gv,isObject:()=>Cv,isOverseaSdkAppId:()=>MY,isPlainObject:()=>nT,isPortrait:()=>i7,isPromise:()=>$X,isRemoteTrack:()=>llA,isRotate90Or270:()=>a7,isSetSinkIdSupported:()=>ElA,isString:()=>ih,isUndefined:()=>$n,isVideoMixerOutputTrack:()=>$W,loadImage:()=>MlA,loadVideo:()=>wlA,ms2bytes:()=>rlA,ms2samples:()=>XX,normalizeUrl:()=>vlA,performanceNow:()=>Yc,promiseAny:()=>dlA,samples2ms:()=>ZX,setNetworkTypeFromWebRTC:()=>ilA,stringify:()=>Zy,stringifyIncludeValue:()=>j3,throttlePromise:()=>n7});var SY="5.0.0",VX=typeof importScripts<"u",JX=typeof registerProcessor<"u",GcA="web.sdk.qcloud.com",x3=`https://${GcA}/trtc/webrtc/doc`,sZ="https://cloud.tencent.com/document/product/647/85386",nZ="https://trtc.io/document/56025",bcA="https://yun.tim.qq.com",kcA="https://apisgp.my-imcloud.com",LcA="trtc_error_assistance",HX={LOG:"jssdk_log"},Jj={QCLOUD:"qcloud"},G_=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(G_||{}),qX={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},UcA=6048e5,FcA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},OcA=FcA["480p_2"],$t={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},rZ=1,PcA=2,xcA=4,aZ=8,gZ=64,cZ=16,YcA=256,tU={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},VcA="unified-plan",b_=5,KX="default",O1=2e3,jX=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],JcA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},HcA=function(t,i,r,l){return new(r||(r=Promise))(function(I,h){function f(G){try{_(l.next(G))}catch(U){h(U)}}function w(G){try{_(l.throw(G))}catch(U){h(U)}}function _(G){var U;G.done?I(G.value):(U=G.value,U instanceof r?U:new r(function(j){j(U)})).then(f,w)}_((l=l.apply(t,[])).next())})},Y3=Symbol(32),V3=Symbol(16),J3=Symbol(8),Z_=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(t,i){return i&&this.consume(),this.need=t,this.flush()}read(t){return HcA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,r)=>{var l;this.reject=r,this.resolve=I=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(I)},this.demand(t,!0)||(l=this.pull)===null||l===void 0||l.call(this,t)})})}readU32(){return this.read(Y3)}readU16(){return this.read(V3)}readU8(){return this.read(J3)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null;const i=this.buffer.subarray(this.consumed);let r=0;const l=I=>i.length<(r=I);if(typeof this.need=="number"){if(l(this.need))return;t=i.subarray(0,r)}else if(this.need===Y3){if(l(4))return;t=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===V3){if(l(2))return;t=i[0]<<8|i[1]}else if(this.need===J3){if(l(1))return;t=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(l(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,r)),t=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(l(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,r)),t=this.need}return this.consumed+=r,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,255&t]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,255&t]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){const i=this.buffer.length,r=i+t;if(r<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,r);else{const l=new Uint8Array(r);l.set(this.buffer),this.buffer=l}return this.buffer.subarray(i,r)}return this.buffer=new Uint8Array(t),this.buffer}};Z_.U32=Y3,Z_.U16=V3,Z_.U8=J3;var qcA=128;function Hj(t){const i=new Z_;for(;t>=128;)i.malloc(1)[0]=255&t|qcA,t>>>=7;return i.malloc(1)[0]=255&t,i.buffer||new Uint8Array(0)}function H3(t,i=0){const r=new Z_,l=i<<3;switch(typeof t){case"boolean":const I=r.malloc(2);I[0]=l,I[1]=t?1:0;break;case"number":r.malloc(1)[0]=l,r.write(Hj(t));break;case"string":r.malloc(1)[0]=2|l;const h=new TextEncoder().encode(t);r.write(Hj(h.length));const f=r.malloc(h.length);for(let _=0;_>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeByte(t){this.buffer.push(255&t)}writeBytes(t){for(let i=0;i>>24&255,t[r+1]=i>>>16&255,t[r+2]=i>>>8&255,t[r+3]=255&i}function gd(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function uZ(t,i){return t[i]}function yL(t,i,r){return new TextDecoder().decode(KcA(t,i,r))}function KcA(t,i,r){return t.slice(i,i+r)}var qj=0,q3=2654435769,K3=16,EZ=4,iU=2,oU=7;function jcA(t,i,r,l="AVQualityReportSvc.C2S",I=2e3,h=2,f=30){return{version:I,encryption:h,d2:"",d2Len:0,uinType:f,uin:"",uinLen:0,reqHead:{seqNumber:r,appId:t,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:l,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function WcA(t,i){const r=new lZ,l=jcA(i,t,qj);qj=qj+1&2147483647,r.writeInt32(0),r.writeInt32(l.version),r.writeByte(l.encryption);const I=new TextEncoder().encode(l.d2);r.writeInt32(I.length+4),I&&r.writeBytes(I),r.writeByte(l.uinType);const h=new TextEncoder().encode(l.uin);r.writeInt32(h.length+4),h.length&&r.writeBytes(h);const f=new lZ;f.writeInt32(0),f.writeInt32(l.reqHead.seqNumber),f.writeInt32(l.reqHead.appId),f.writeByte(l.reqHead.appId>>>24&255),f.writeByte(l.reqHead.appId>>>16&255),f.writeByte(l.reqHead.appId>>>8&255),f.writeByte(255&l.reqHead.appId);for(let WA=4;WA<16;WA++)f.writeByte(0);const w=new TextEncoder().encode(l.reqHead.a2);f.writeInt32(w.length+4),w.length&&f.writeBytes(w);const _=new TextEncoder().encode(l.reqHead.serviceCmd);f.writeInt32(_.length+4),_.length&&f.writeBytes(_);const G=new TextEncoder().encode(l.reqHead.cookie);f.writeInt32(G.length+4),G.length&&f.writeBytes(G);const U=new TextEncoder().encode(l.reqHead.imei);f.writeInt32(U.length+4),U.length&&f.writeBytes(U);const j=new TextEncoder().encode(l.reqHead.ksid);f.writeInt32(j.length+4),j.length&&f.writeBytes(j);const lA=new TextEncoder().encode(l.reqHead.clientVersionInfo);f.writeInt16(lA.length+2),lA.length&&f.writeBytes(lA);const sA=f.length;f.data[0]=sA>>>24&255,f.data[1]=sA>>>16&255,f.data[2]=sA>>>8&255,f.data[3]=255&sA,ih(t)&&(t=new TextEncoder().encode(t)),f.writeInt32(t.length+4),t.length&&f.writeBytes(t);let mA=new Uint8Array(f.data),IA=null;l.encryption===1?IA=new TextEncoder().encode(l.uin):l.encryption===2&&(IA=new Uint8Array(16)),IA&&(mA=zcA(mA,IA)),r.writeBytes(mA);const cA=new Uint8Array(r.data),TA=cA.length;return cA[0]=TA>>>24&255,cA[1]=TA>>>16&255,cA[2]=TA>>>8&255,cA[3]=255&TA,cA}function zcA(t,i){const r=t.length;let l=(r+1+iU+oU)%8;l&&(l=8-l);const I=new Uint8Array(r+1+iU+oU+l);let h=0;const f=new Uint8Array(8),w=new Uint8Array(8),_=new Uint8Array(8);let G=0;f[0]=248&Math.floor(256*Math.random())|l,G=1;for(let j=0;j>>=0,I+=(h<<4)+f[0]^h+w^(h>>>5)+f[1],I>>>=0,h+=(I<<4)+f[2]^I+w^(I>>>5)+f[3],h>>>=0;IZ(r,I,l),IZ(r,h,l+4)}var XcA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},$cA=".rtc.qq.com",AlA=function(t){return t.includes(".")?t:`${t}${$cA}`},MY=t=>Number(t)<14e8,WW=function(t,i){let r;return r=MY(t)?kcA:bcA,`${r}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${t}&cmdtype=${i}`},WX="unknown";function zW(){tlA();const{userAgent:t,connection:i}=navigator;let r=(t.match(/NetType\/\S+/)||[])[0]||"";r=r.toLowerCase().replace("nettype/",""),r==="3gnet"&&(r="3g");const l=i&&i.type&&i.type.toLowerCase();let I=i&&i.effectiveType&&i.effectiveType.toLowerCase();return I==="slow-2"&&(I="2g"),l?zX(l,I):WX}function elA(){Wo.warn("netType changed",zW())}var dZ=!1;function tlA(){var t;dZ||(dZ=!0,(t=navigator.connection)==null||t.addEventListener("typechange",elA))}function zX(t,i){if(qX[t])return t;switch(t){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function ilA(t){WX=zX(t)}function olA(){return qX[zW()]}function slA(t,i){for(const r of Reflect.ownKeys(i))if(r!=="constructor"&&r!=="prototype"&&r!=="name"){const l=Object.getOwnPropertyDescriptor(i,r)||"";Object.defineProperty(t,r,l)}return t}function nlA(t,i=48e3){return ZX(t/4,i)}function ZX(t,i=48e3){return 1e3*t/i}function rlA(t,i=48e3){return 4*XX(t,i)}function XX(t,i=48e3){return t*i/1e3}var alA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},zy=()=>{let t=navigator.language;return t=t.substring(0,2),t==="zh"},nT=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function ZW(t,i=1,r=1){return t<=1?r:ZW(t-1,r,i+r)}function glA(t){return t>8?3e4:1e3*ZW(t)}function Nv(t){return Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var mv=t=>typeof t=="function",$n=t=>t===void 0,ih=t=>typeof t=="string",Gv=t=>typeof t=="number",fv=t=>typeof t=="boolean",Cv=t=>Nv(t)==="object",Ah=t=>Nv(t)==="array",clA=t=>Nv(t)==="MediaStreamTrack".toLowerCase(),llA=t=>t.isRemote,$X=t=>Nv(t)==="promise",A7=t=>mv(t)&&t.prototype.constructor===t,IlA=t=>A7(t)?t.prototype.constructor.name:"",ulA=typeof AudioWorkletNode<"u",ElA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function dlA(t){return new Promise((i,r)=>{const l=[];t.forEach(I=>{I.then(i).catch(h=>{l.push(h),l.length===t.length&&r(l)})})})}function Yc(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var CZ=t=>+t<10?`0${t}`:t,ClA=t=>{const i=t.match(/^\d+\.\d+\.\d+/)[0];if(!i)return t;const r=i.split("."),l=CZ(r[1])+CZ(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),`${r.join(".")}.${l}`},hlA=Object.prototype.hasOwnProperty;function BlA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(nT(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(hlA.call(t,i))return!1;return!0}return!1}function e7(t,i){return{userId:i,hasAudio:!!(t&aZ),hasVideo:!!(t&rZ),hasAuxiliary:!!(t&xcA),hasSmall:!!(t&PcA),audioMuted:!!(t&gZ),videoMuted:!!(t&cZ),audioAvailable:!(!(t&aZ)||t&gZ),videoAvailable:!(!(t&rZ)||t&cZ),hasDatachannel:!!(t&YcA)}}function QlA(t){const i={urls:t.url.startsWith("turn:")||t.url.startsWith("turns:")?t.url:`turn:${t.url}`};return $n(t.username)||$n(t.credential)||(i.username=t.username,i.credential=t.credential,i.credentialType="password",$n(t.credentialType)||(i.credentialType=t.credentialType)),i}function plA(t,i=!0){if(!ih(t))return 0;const r=t.split(".");return i?(Number(r[0])<<24|Number(r[1])<<16|Number(r[2])<<8|Number(r[3]))>>>0:(Number(r[3])<<24|Number(r[2])<<16|Number(r[1])<<8|Number(r[0]))>>>0}var t7=function(t,i,r,l){if(!Cv(t)||!Cv(i))return 0;let I=0;const h=Object.keys(i);let f;for(let w=0,_=h.length;w<_;w++)if(f=h[w],!($n(i[f])||r&&r.includes(f)))if(Cv(t[f])&&Cv(i[f]))I+=t7(t[f],i[f],r,l);else{if(l&&l.includes(i[f]))continue;t[f]!==i[f]&&(t[f]=vY(i[f]),I+=1)}return I};function vY(t){if(Ah(t)){const i=[];return t.forEach((r,l)=>{i[l]=vY(r)}),i}if(Cv(t)){const i={};return Object.keys(t).forEach(r=>{i[r]=vY(t[r])}),i}return t}var mlA=t=>{let i=[];if(Ah(t))i=[...t];else if(ih(t)){const r=document.getElementById(t);r&&i.push(r)}else t&&i.push(t);return i},flA=t=>ih(t)?document.getElementById(t):t,ylA=t=>{const i=r=>r<10?`0${r}`:`${r}`;return`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${i(t.getHours())}:${i(t.getMinutes())}:${i(t.getSeconds())}`},DlA=()=>ylA(new Date);function Zy(t,{keysToInclude:i,keysToExclude:r}){try{if(Ah(t))return`[${t.map(f=>Zy(f,{keysToInclude:i,keysToExclude:r})).join(",")}]`;if(!nT(t)||!Ah(i)&&!Ah(r))return JSON.stringify(t);const l={},I=new Set(i),h=new Set(r);return Object.keys(t).forEach(f=>{(h.size===0&&I.has(f)||I.size===0&&!h.has(f))&&(l[f]=nT(t[f])||Ah(t[f])?JSON.parse(Zy(t[f],{keysToExclude:r,keysToInclude:i})):t[f])}),JSON.stringify(l)}catch{return"{}"}}function j3(t,i=!1){const r=[];return Object.keys(t).forEach(l=>{i===t[l]&&r.push(l)}),Zy(t,{keysToInclude:r})}function SlA(t){return t.replace(/[\u4e00-\u9fa5]/g,"aa").length}var i7=()=>{var t,i,r,l;return(t=window.screen)!=null&&t.orientation?!!((l=(r=(i=window.screen)==null?void 0:i.orientation)==null?void 0:r.type)!=null&&l.includes("portrait")):window.orientation===0||window.orientation===180},MlA=async t=>new Promise((i,r)=>{let l;if(ih(t))l=new Image,l.crossOrigin="anonymous",l.src=t;else if(l=t,l.complete)return void i(l);l.onload=()=>i(l),l.onerror=()=>{r(new ml({code:qg.INVALID_PARAMETER,message:`load image failed, url: ${t}`}))}}),o7=t=>{const i=t.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},s7=t=>(Object.keys(t).forEach(i=>{Gv(t[i])&&(i.startsWith("uint")||i.startsWith("int"))?t[i]=Math.floor(t[i]):(nT(t[i])||Ah(t[i]))&&s7(t[i])}),t);function rT(t,i){return new Promise(r=>{const l=setTimeout(r,t);i&&i(l)})}function n7(t,i){let r=null;return function(...l){return r||(r=t.apply(i||this,l),r.finally(()=>r=null),r)}}function vlA(t){return t.replace(/(^|[^:])\/{2,}/g,"$1/")}function RlA(t){var i;try{const{width:r,height:l,frameRate:I,sampleRate:h,sampleSize:f,channelCount:w}=(i=t.getSettings)==null?void 0:i.call(t),_=t.kind===$t.AUDIO?`${h}x${f}@${w}`:`${r}x${l}@${I}`,G=t.stats?` stats: ${JSON.stringify(t.stats).replaceAll('"',"")}`:"";return`${t.id} ${t.readyState} muted:${t.muted} ${t.kind} ${t.label} ${_}${G}`}catch{return""}}function r7(t,i){return t.width*t.height===i.width*i.height?1:i7()&&i.width>i.height&&t.height>i.width?Math.max(t.width/i.height,t.height/i.width,1):Math.max(t.width/i.width,t.height/i.height,1)}function a7(t){return t===90||t===270}async function wlA(t){return new Promise((i,r)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.src=t,l.muted=!0,l.loop=!0,l.playsInline=!0,l.play().then(()=>i(l)),l.onerror=()=>{r(l.error)}})}function W3(t,i=new WeakMap){if(typeof t!="object"||t===null)return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const r=[];return i.set(t,r),t.forEach((l,I)=>{r[I]=W3(l,i)}),r}if(Object.prototype.toString.call(t)==="[object Object]"){const r={};return i.set(t,r),Reflect.ownKeys(t).forEach(l=>{r[l]=W3(t[l],i)}),r}return t}var g7=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(g7||{});function _lA(t,i,r,l){let I={data:t,random:Math.floor(Math.random()*2147483648),sdkAppId:r};return $n(l)||(I=nB(Rn({},I),{gzip:+l})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(I)}}}function XW(t,i,r,l){try{const I=_lA(t,i,r,l);return WcA(H3(I),r)}catch{return JSON.stringify(t)}}function TlA(t,i){const r=new Uint8Array(t.byteLength+i.byteLength);return r.set(new Uint8Array(t),0),r.set(new Uint8Array(i),t.byteLength),r.buffer}function NlA(t){return(65535&t)>>>0}function GlA(t){return(4294901760&t)>>>0}function $W(t){return!!(t&&t instanceof CanvasCaptureMediaStreamTrack&&t.canvas.id.includes("trtc_mix"))}function blA(t){const i=klA(t);return i?.busiBuff}function klA(t){try{const i={};let r=0;i.totalLength=gd(t,r),r+=4,i.version=gd(t,r),r+=4,i.encryption=uZ(t,r),r+=1,i.uinType=uZ(t,r),r+=1,i.uinLength=gd(t,r),r+=4,i.uin=i.uinLength>4?yL(t,r,i.uinLength-4):"",r+=i.uinLength-4;const l=t.slice(r);if(i.encryption===2){const I=new Uint8Array(16).fill(0);t=LlA(l,I),i.decrypted=!0,r=0}else t=l,r=0;return i.rspHeadLength=gd(t,r),r+=4,i.seqNo=gd(t,r),r+=4,i.retCode=gd(t,r),r+=4,i.retStrLength=gd(t,r),r+=4,i.retStr=i.retStrLength?yL(t,r,i.retStrLength-4):"",r+=i.retStrLength-4,i.serviceCmdLength=gd(t,r),r+=4,i.serviceCmd=i.serviceCmdLength?yL(t,r,i.serviceCmdLength-4):"",r+=i.serviceCmdLength-4,i.cookieLength=gd(t,r),r+=4,i.cookie=i.cookieLength?yL(t,r,i.cookieLength-4):"",r+=i.cookieLength-4,i.flag=gd(t,r),r+=4,i.busiBuffLength=gd(t,r),r+=4,i.busiBuff=i.busiBuffLength?yL(t,r,i.busiBuffLength-4):"",r+=i.busiBuffLength-4,i}catch{}}function c7(t,i){let r=t[0]<<24|t[1]<<16|t[2]<<8|t[3],l=t[4]<<24|t[5]<<16|t[6]<<8|t[7];r>>>=0,l>>>=0;let I=q3*K3>>>0;for(let h=0;h>>5)+i[3],l>>>=0,r-=(l<>>5)+i[1],r>>>=0,I-=q3,I>>>=0;return new Uint8Array([r>>>24&255,r>>>16&255,r>>>8&255,255&r,l>>>24&255,l>>>16&255,l>>>8&255,255&l])}function LlA(t,i){let r=0;const l=new Uint8Array(8).fill(0);let I=c7(new Uint8Array(t.slice(0,8)),i);const h=7&I[0],f=t.length-1-h-iU-oU,w=new Uint8Array(f);let _=0,G=l,U=t.slice(0,8);r=8;let j=1;j+=h;for(let sA=1;sA<=iU;)if(j<8)j++,sA++;else if(j===8){const mA=jj(t,r,G,U,I,i);G=mA.ivPreCrypt,U=mA.ivCurCrypt,I=mA.debiBuf,r=mA.bufPos,j=0}let lA=f;for(;lA>0;)if(j<8)w[_++]=I[j]^G[j],j++,lA--;else if(j===8){const sA=jj(t,r,G,U,I,i);G=sA.ivPreCrypt,U=sA.ivCurCrypt,I=sA.debiBuf,r=sA.bufPos,j=0}for(let sA=1;sA<=oU;)if(j<8)I[j],G[j],j++,sA++;else if(j===8){if(r>=t.length)break;const mA=jj(t,r,G,U,I,i);if(!mA.success)break;G=mA.ivPreCrypt,U=mA.ivCurCrypt,I=mA.debiBuf,r=mA.bufPos,j=0}return w}function jj(t,i,r,l,I,h){if(i+8>t.length)return{success:!1};const f=new Uint8Array(l),w=t.slice(i,i+8),_=new Uint8Array(8);for(let G=0;G<8;G++)_[G]=I[G]^w[G];return{success:!0,ivPreCrypt:f,ivCurCrypt:w,debiBuf:c7(_,h),bufPos:i+8}}var hZ=typeof TextDecoder<"u"?new TextDecoder:void 0;function l7({url:t,body:i,method:r="POST",timeout:l,priority:I}){return new Promise((h,f)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:I}).then(_=>_.clone().json().then(G=>({data:G}),()=>_.arrayBuffer().then(G=>({data:blA(new Uint8Array(G))||(hZ?hZ.decode(G):G)})))).then(h,f);const w=new XMLHttpRequest;w.onreadystatechange=()=>{if(w.readyState===4)if(w.status>=200&&w.status<300)try{const _=JSON.parse(w.response);h({data:_})}catch{h({data:w.response})}else f({status:w.status,statusText:w.statusText||"request failed!"})},w.timeout=l||5e3,w.open(r,t,!0),w.send(i)})}var UlA=Object.prototype.hasOwnProperty,k_=t=>typeof t=="function",D_=t=>t===void 0,FlA=t=>typeof t=="boolean",Wj=t=>t.isRemote,OlA=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const r=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof r=="function"&&r instanceof r&&Function.prototype.toString.call(r)===Function.prototype.toString.call(Object)};function PlA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(OlA(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(UlA.call(t,i))return!1;return!0}return!1}var xlA=0,YlA=1,BZ=2;function VlA({retryFunction:t,settings:i,onError:r,onRetrying:l,onRetryFailed:I,onRetrySuccess:h,context:f}){return function(...w){const{retries:_=5,timeout:G=1e3}=i;let U=0,j=-1,lA=xlA;const sA=async(mA,IA)=>{const cA=f||this;try{const TA=await t.apply(cA,w);U>0&&h&&h.call(this,U),U=0,mA(TA)}catch(TA){const WA=()=>{clearTimeout(j),U=0,lA=BZ,IA(TA)},ue=()=>{lA!==BZ&&U<(k_(_)?_():_)?(U++,lA=YlA,k_(l)&&l.call(this,U,WA),j=window.setTimeout(()=>{j=-1,sA(mA,IA)},k_(G)?G(U):G)):(WA(),k_(I)&&I.call(this,TA))};k_(r)?r.call(this,{error:TA,retry:ue,reject:IA,retryFuncArgs:w,retriedCount:U}):ue()}};return new Promise(sA)}}var A4=VlA,zj=class I7{constructor(i){de(this,"_parentPath"),de(this,"userId"),de(this,"remoteUserId"),de(this,"id"),de(this,"sdkAppId"),de(this,"type"),de(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!FlA(i.isLocal)||i.isLocal,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){const r=new I7({id:i.id,userId:D_(i.userId)?this.userId:i.userId,sdkAppId:D_(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:D_(i.type)?this.type:i.type,isLocal:D_(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:D_(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return r.bindParent(this),r}bindParent(i){const r=i.getFullId();this._parentPath!==r&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=r,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,r){const l=this.isLocal?this.userId:this.remoteUserId,I=this.getFullId();r.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${I}${l?`|${l}`:""}]`),Wo.log(i,r,D_(this.userId)||PlA(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}},wQ=typeof navigator>"u"?"":navigator.userAgent,Ys=t=>new RegExp(t,"i").test(wQ),Qc=t=>{if(Ys(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=wQ.match(i);if(r&&r[1])return r[1]}return""},EV=t=>{if(Ys(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=wQ.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},QZ=/AppleWebKit\/([\d.]+)/i.exec(wQ);QZ&&parseFloat(QZ[1]);var e4=Ys("iPad"),u7=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ys("Macintosh"),dV=Ys("iPhone")&&!e4,JlA=Ys("iPod"),Mu=dV||e4||JlA||u7,RY=()=>{try{return Mu&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return Mu}},aC=Ys("Android"),E7=function(){if(aC){const t=wQ.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),r=t[2]&&parseFloat(t[2]);if(i&&r)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();aC&&Ys("webkit")&&E7<2.3;var sC=Ys("Firefox"),d7=Qc("Firefox"),C7=EV("Firefox"),YU=Ys("Edge"),h7=Qc("Edge"),CV=Ys("Edg"),B7=Qc("Edg"),HlA=EV("Edg"),t4=Ys("SogouMobileBrowser"),Q7=Qc("SogouMobileBrowser"),i4=Ys("MetaSr\\s"),p7=Qc("MetaSr\\s"),Bm=Ys("TBS"),m7=Qc("TBS"),CT=Ys("XWEB"),f7=Qc("XWEB");Ys("MSIE\\s8\\.0");var qlA=Ys("MSIE\\/\\d+");(function(){if(qlA){const t=/MSIE\s(\d+)\.\d/.exec(wQ);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(wQ)&&/rv:11.0/.test(wQ)&&(i=11),i}return NaN})();var VU=Ys("(micromessenger|webbrowser)"),y7=Qc("MicroMessenger"),hV=!Bm&&Ys("MQQBrowser")&&Ys("COVC"),BV=!Bm&&Ys("MQQBrowser")&&!Ys("COVC"),wY=BV||hV?Qc("MQQBrowser"):"",o4=!Bm&&Ys(" QQBrowser"),D7=Qc(" QQBrowser"),s4=!Bm&&Ys("QQBrowserLite"),S7=Qc("QQBrowserLite"),n4=!Bm&&Ys("MQBHD"),M7=Qc("MQBHD"),v7=Ys("Windows"),QV=!Mu&&Ys("MAC OS X"),R7=!aC&&Ys("Linux"),w7=Ys("CrOS");Ys("MicroMessenger");var KlA=Ys("UCBrowser");Ys("Electron");var r4=Ys("MiuiBrowser"),_7=Qc("MiuiBrowser"),a4=Ys("HuaweiBrowser"),T7=Ys("Huawei")||Ys("HUAWEI"),jlA=Ys("Honor")||Ys("HONOR"),N7=Qc("HuaweiBrowser"),g4=Ys("SamsungBrowser"),G7=Qc("SamsungBrowser"),pV=Ys("HeyTapBrowser"),b7=Qc("HeyTapBrowser"),c4=Ys("VivoBrowser"),k7=Qc("VivoBrowser"),l4=Ys("OpenHarmony");Qc("OpenHarmony");var L7=()=>EV("Chrome"),_Y=Ys("CriOS"),tD=Ys("Chrome"),I4=!YU&&!i4&&!t4&&!Bm&&!CT&&!CV&&!o4&&!r4&&!a4&&!g4&&!pV&&!c4&&tD,WlA=Ys("HeadlessChrome"),iD=L7(),Zj=tD&&iD>=128&&iD<=143,U7=Qc("Chrome");EV("Electron");var ld=!tD&&!BV&&!hV&&!s4&&!n4&&Ys("Safari"),F7=ld||Mu,JU=Qc("Version"),MQ=(()=>{if(u7)return JU;if(Mu){const t=wQ.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();function zlA(t,i){const r=t.split(".").map(I=>Number(I)),l=i.split(".").map(I=>Number(I));for(let I=0;If)return!1}return!1}function O7(t,i,r=!1){const l=t.split(".").map(h=>Number(h)),I=i.split(".").map(h=>Number(h));for(let h=0;hw)return!0;if(f{const t=Number(MQ.split(".")[0]);return t===14||t===13})(),$lA=_Y&&JU==="11.1.1",TY=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),S_=(()=>{let t;return()=>{if(t===void 0)try{t=!!window.localStorage}catch{t=!1}return t}})(),yv=AIA();function AIA(){const t=new Map([[sC,["Firefox",d7]],[CV,["Edg",B7]],[I4,["Chrome",U7]],[_Y,["ChiOS",Qc("CriOS")]],[ld&&!_Y,["Safari",JU]],[Bm,["TBS",m7]],[CT,["XWEB",f7]],[VU&&dV,["WeChat",y7]],[o4,["QQ(Win)",D7]],[BV,["QQ(Mobile)",wY]],[hV,["QQ(Mobile X5)",wY]],[s4,["QQ(Mac)",S7]],[n4,["QQ(iPad)",M7]],[r4,["MI",_7]],[a4,["HW",N7]],[g4,["Samsung",G7]],[pV,["OPPO",b7]],[c4,["VIVO",k7]],[YU,["EDGE",h7]],[t4,["SogouMobile",Q7]],[i4,["Sogou",p7]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}function eIA(){return aC||Mu||dV||e4||l4}var tIA="";function P7(){return iIA()||""}function iIA(){const t=wQ.match(/;\s*([^;)]+)\s+Build\//);return t?.[1]?t[1].trim():null}var pZ=new Map([[aC,"Android"],[Mu,"iOS"],[v7,"Windows"],[QV,"MacOS"],[R7,"Linux"],[w7,"ChromeOS"]]),x7=function(){return pZ.get(!0)?pZ.get(!0):"unknown"};function u4(){return v7?1:aC?2:QV?3:Mu?4:R7?5:w7?6:l4?7:0}function oIA(){return VU||CT?4:tD?1:ld?2:sC?3:0}var Y7=()=>{let t=x7();return Mu?t+=`/${MQ}`:aC&&(t+=`/${E7}`),t+=`/${yv.name}/${ld&&!_Y?yv.version:yv.version.split(".")[0]}`,t},sIA=dT(PU()),nIA=new sIA.default,ps=nIA,V7=(t=>(t.ROOM_DESTROY="1",t.JOIN_START="21",t.JOIN_SCHEDULE_SUCCESS="22",t.JOIN_SIGNAL_CONNECTION_START="23",t.JOIN_SIGNAL_CONNECTION_END="24",t.JOIN_SEND_CMD="25",t.JOIN_RECEIVED_CMD_RES="26",t.JOIN_SUCCESS="27",t.JOIN_FAILED="28",t.LEAVE_START="51",t.LEAVE_SEND_CMD="52",t.LEAVE_SUCCESS="53",t.PUBLISH_START="61",t.SEND_FIRST_VIDEO_FRAME="62",t.PUBLISH_FAILED="63",t.SUBSCRIBE_START="81",t.SUBSCRIBE_SUCCESS="82",t.SUBSCRIBE_FAILED="84",t.UNSUBSCRIBE_SUCCESS="83",t.LOCAL_TRACK_CAPTURE_START="101",t.LOCAL_TRACK_CAPTURE_SUCCESS="102",t.LOCAL_TRACK_CAPTURE_FAILED="103",t.LOCAL_TRACK_PUBLISHED="104",t.LOCAL_TRACK_UNPUBLISHED="105",t.LOCAL_TRACK_REPLACED="106",t.SWITCH_DEVICE_SUCCESS="107",t.TRACK_MUTED="108",t.TRACK_UNMUTED="109",t.REMOTE_TRACK_SUBSCRIBED="110",t.REMOTE_TRACK_UNSUBSCRIBED="111",t.LOCAL_TRACK_RECAPTURE="112",t.LOCAL_AUDIO_STARTED="113",t.LOCAL_AUDIO_STOPPED="114",t.REMOTE_AUDIO_STARTED="115",t.REMOTE_AUDIO_STOPPED="116",t.LOCAL_TRACK_STOPPED="117",t.LOCAL_VIDEO_TRACK_PREPROCESSED="118",t.PLAY_TRACK_START="151",t.PLAYER_STATE_CHANGED="152",t.VIDEO_LOADED_DATA="153",t.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",t.AUDIO_CONTEXT_LONG_SUSPENDED="155",t.REMOTE_VIDEO_PLAY_START="156",t.REMOTE_VIDEO_PLAY_FINISH="157",t.SIGNAL_CONNECTION_STATE_CHANGED="201",t.PEER_CONNECTION_STATE_CHANGED="202",t.SINGLE_CONNECTION_STAT="203",t.SPC_RECONNECTED="204",t.HEARTBEAT_REPORT="251",t.RECEIVED_PUBLISHED_USER_LIST="252",t.REMOTE_PUBLISH_STATE_CHANGED="253",t.AUDIO_LEVEL_INTERVAL="260",t.NETWORK_QUALITY="261",t.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",t.QUALITY_LIMITATION_CHANGED="263",t.LOG="264",t.AUDIO_PROCESSOR_DEBUG="265",t.SSO_SWITCH="266",t.SEI_MESSAGE="267",t.USER_PAUSE_IN_PIP="268",t.USER_RESUME_IN_PIP="269",t.ENTER_PICTURE_IN_PICTURE="270",t.LEAVE_PICTURE_IN_PICTURE="271",t.SWITCH_ROOM_START="401",t.SWITCH_ROOM_SUCCESS="407",t.SWITCH_ROOM_FAILED="408",t))(V7||{}),mn=V7,rIA=class{constructor(){de(this,"enable",!1),de(this,"ssoFailCount",0),ps.on("22",({schedule:t})=>{var i;(i=t?.config)!=null&&i.sso&&ps.emit("266",{enable:!0})}),ps.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&ps.emit("266",{enable:!1})}},z3=new rIA,aIA="%cTRTC%c%s",gIA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",cIA="display: inline",J7=class H7{constructor(){de(this,"_isEnableUploadLog",!0),de(this,"_localJoinedUser",new Map),de(this,"_queue",[]),de(this,"_timeoutId",-1),de(this,"_logLevel",1),de(this,"_logLevelToUpload",2),VX||JX||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){ps.on(mn.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var r;(r=i?.config)!=null&&r.logLevelToUpload&&G_[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),ps.on(mn.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),ps.on(mn.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){const i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let r=0;for(;r{i.map.has(I)?i.map.get(I).logs.push(l):i.map.set(I,{userId:I,sdkAppId:h,logs:[l]})});else if(ih(l.userId)&&Gv(l.sdkAppId)){const{userId:I,sdkAppId:h}=l;i.map.has(I)?i.map.get(I).logs.push(l):i.map.set(I,{userId:I,sdkAppId:h,logs:[l]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,r)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:r}=this.getLogsToUpload();if(i.size===0)return;try{const I=[...i.values()];for(let h=0;hlA.log).join(` -`)},U=JSON.stringify(G),j=z3.enable?XW(G,2002,w):U;await this.uploadLogWithRetry(j,w,j instanceof Uint8Array,U),_.forEach(lA=>lA.uploaded=!0)}}catch{}const l=r.filter(I=>!I.uploaded);l.length>0&&(this._queue=l.concat(this._queue))}uploadLogWithRetry(i,r,l,I){return A4({retryFunction:()=>l7({url:WW(r,HX.LOG),body:i,timeout:5e3,priority:"low"}).then(h=>{l&&h.data!=="ok"&&(z3.handleUploadFailed(),this.uploadLogWithRetry(I,r,!1,I))}),settings:{retries:3,timeout:2e3},onError:({retry:h})=>{h()}})()}getPrefix(i){const r=new Date;return r.setTime(jW()),`[${TcA(r)}] <${G_[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){$n(G_[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(ih(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,r,l=!0,I,h){const f={log:r.reduce((w,_)=>`${w} ${this.logChunkToString(_)}`.trim(),""),level:i,userId:I,sdkAppId:h,forAllJoinedClients:l};ps.emit(mn.LOG,{log:f}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(f)}log(i,r,l=!0,I,h){var f;if(r.unshift(this.getPrefix(i)),this.addLogToQueue(i,r,l,I,h),i{const i=16*Math.random()|0;return(t=="x"?i:3&i|8).toString(16)})},q7=IIA,uIA=class{constructor(){de(this,"_prefix","TRTC"),de(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){S_()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{const i=localStorage.getItem(t);if(!i)return!1;const r=JSON.parse(i);if(r&&r.expiresInlocalStorage.removeItem(t)))}doFlush(){if(S_())try{for(const[t,i]of this._queue)localStorage.setItem(t,JSON.stringify(i))}catch(t){Wo.warn(t)}}getItem(t){if(!S_())return null;try{const i=localStorage.getItem(this.getRealKey(t));if(!i)return null;const r=JSON.parse(i);return r&&r.expiresIn>=Date.now()?r.value:null}catch(i){Wo.warn(i)}}setItem(t,i){if(S_())try{const r={expiresIn:Date.now()+UcA,value:i};this._queue.set(this.getRealKey(t),r)}catch(r){Wo.warn(r)}}deleteItem(t){if(!S_())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(i){return Wo.warn(i),!1}}clear(){if(S_())try{localStorage.clear()}catch(t){Wo.warn(t)}}},K7=new uIA,EIA={};qW(EIA,{HTTPS_API:()=>vIA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>a$,IS_GET_CAPABILITIES_SUPPORTED:()=>r$,IS_GET_SETTINGS_SUPPORTED:()=>bY,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>LIA,IS_INSERTABLE_STREAM_SUPPORTED:()=>g$,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>YIA,IS_RTC_RTP_SENDER_SUPPORTED:()=>HU,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>c$,IS_SEI_SUPPORTED:()=>UIA,IS_SPC_SUPPORTED:()=>NIA,basis:()=>OIA,capabilityCheck:()=>PIA,checkSystemRequirementsInternal:()=>Z7,decodeSupportStatus:()=>z7,detectH264SupportedByFakeStreaming:()=>X7,detectVideoCodecCapabilities:()=>VIA,detectVideoDecoderCapabilities:()=>C$,detectVideoEncoderCapabilities:()=>d$,encodeSupportStatus:()=>h4,getBrowserInfo:()=>pIA,getDisplayResolution:()=>$7,getH264ProfileLevelIds:()=>h$,isAddTransceiverSupported:()=>fV,isBrowserSupported:()=>E4,isCanvasCaptureStreamAPISupported:()=>t$,isCanvasSmallStreamSupported:()=>i$,isGetReceiversSupported:()=>_IA,isGetSendersSupported:()=>n$,isGetTransceiversSupported:()=>TIA,isGetUserMediaSupported:()=>A$,isMediaDevicesSupported:()=>C4,isMediaSessionSupported:()=>I$,isMediaStreamTrackGeneratorSupported:()=>fIA,isMediaStreamTrackProcessorSupported:()=>mIA,isReplaceTrackSupported:()=>bIA,isRequestVideoFrameCallbackSupported:()=>p4,isSIMDSupported:()=>FIA,isScaleResolutionDownBySupported:()=>o$,isScreenCaptureApiAvailable:()=>B4,isSelectedCandidatePair:()=>RIA,isSetParametersSupported:()=>kIA,isSetSinkIdSupported:()=>SIA,isSmallStreamSupported:()=>s$,isStopTransceiverSupported:()=>GIA,isTRTCSupported:()=>DIA,isUnifiedPlanDefault:()=>wIA,isUsedInHttpProtocol:()=>mV,isWebAudioSupported:()=>e$,isWebCodecSupported:()=>l$,isWebCodecsSupported:()=>d4,isWebRTCSupported:()=>Q4,isWebTransportSupported:()=>u$});var NY={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},x_={AVOID_REPEATED_CALL:t=>`previous ${t.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:t,rule:i,fnName:r,value:l})=>`'${t||i.name}' is a required param when calling ${r}(), received: ${l}.`,INVALID_PARAMETER_TYPE({key:t,rule:i,fnName:r,value:l}){const I=`${t||i.name}`;let h="";return h=Array.isArray(i.type)?i.type.join("|"):i.type,`'${I}' must be type of ${h} when calling ${r}(), received type: ${Nv(l)}.`},INVALID_PARAMETER_EMPTY:({key:t,rule:i,fnName:r,value:l})=>`'${t||i.name}' cannot be '${l}' when calling ${r}().`,INVALID_PARAMETER_INSTANCE:({key:t,rule:i,fnName:r,value:l})=>`'${`${t||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${r}(), received type: ${Nv(l)}.`,INVALID_PARAMETER_RANGE:({key:t,rule:i,fnName:r,value:l})=>`'${t||i.name}' must be one of ${i.values.join("|")} when calling ${r}(), received: ${l}.`,INVALID_PARAMETER_MIN:({key:t,rule:i,fnName:r,value:l})=>`the min value of ${t||i.name} is ${i.min}, received: ${l}.`,INVALID_PARAMETER_MAX:({key:t,rule:i,fnName:r,value:l})=>`the max value of ${t||i.name} is ${i.max}, received: ${l}.`,API_CALL_TIMEOUT:t=>`${t.commandDesc||t.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:t=>`SignalChannel setup failure: (errorCode: ${t.errorCode}, errorMsg: ${t.errorMsg} }).`,ERROR_MESSAGE(t){let i=`${t.type} failed`;return t.message&&(i=`${i}: ${t.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:t=>`exchange sdp failed ${t.errMsg}.`,UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:t=>`'${t}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:t=>`'${t}' must be an integer between [1, 4294967294] when useStringRoomId is false.`,INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:({error:t,code:i})=>`Failed to join room - ${t} code: ${i}`,REJOIN_ROOM_FAILED:t=>`reJoin room: ${t.roomId} failed, please check your network.`,INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:t=>`duplicate ${t} stream publishing, please unpublish your prev ${t} stream and then re-publish.`,INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:({message:t,userId:i,streamType:r})=>`failed to subscribe ${i} ${r} stream, reason: ${t}.`,INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:t=>`switchRole failed, errCode: ${t.code} errMsg: ${t.message}.`,CLIENT_BANNED:t=>`client was banned because of ${t.message}.`,INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:t=>`startPublishCDNStream failed, errMsg: ${t.message}.`,STOP_PUBLISH_CDN_FAILED:t=>`stopPublishCDNStream failed, errMsg: ${t.message}.`,INVALID_STREAM_ID:t=>`'${t}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`,START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:t=>`cannot replace ${t.kind} track because stream has not ${t.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:t=>`startMixTranscode failed, errMsg: ${t.message}.`,STOP_MIX_TRANSCODE_FAILED:t=>`stopMixTranscode failed, errMsg: ${t.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:t,rule:i,fnName:r,value:l})=>`'${t||i.name}' cannot be less than 0 when calling ${r}().`,MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:t=>`'${t}' is required and must be between 1 and 15.`,MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:t,fnName:i})=>`'${t}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:t,fnName:i,type:r})=>`the element corresponding to '${t}' must be instanceof HTMLElement when calling ${i}(), received: ${r}.`,PLAY_FAILED:t=>`${t.media} play failed, browser exception: ${t.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:t=>`${t}Track is not supported on your browser.`,NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:t=>`${t.signalResponse} failed, response code is ${t.code} , errMsg: ${t.message}.`,CATCH_HANDLER_ERROR:({name:t,event:i})=>`an error was caught in ${t}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:t})=>`experimental api ${t} does not exist.`,REPEAT_JOIN:t=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:({funName:t})=>`failed to call ${t}() because client was destroyed.`,SEI_NOT_SUPPORT:t=>"not support to sendSEIMessage"+(t===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:t,name:i,timesInSecond:r,maxSizeInSecond:l})=>`api ${i} call ${t?"size":"times"} is over ${t?`${l} bytes`:r} in a second.`,CONNECTION_ABORTED:t=>`connection aborted due to: ${t}`,API_CALL_ABORTED(t){let i;return i=t.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${t.userId} ${t.streamType} stream aborted, reason: remote user ${t.userId} unpublished stream.`:`API aborted, reason: ${t.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:t=>`'streamType' is required when 'userId' is not '*', calling ${t}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:t=>`switchPlaybackQuality timeout: waiting for first frame of user ${t.userId}.`},mZ=(t,i)=>i?`${x3}/${t}/${i}`:`${x3}/${t}/index.html`,dIA=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let t=localStorage==null?void 0:localStorage.getItem(LcA);if(t){t=JSON.parse(t);const i=document.createElement("script");i.type="text/javascript",i.text=t.message,document.body.appendChild(i);const r=window.TRTC_ERROR_INFO,l=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:r,TRTC_ERROR_LINK:l}}return{}};function GY(t){const{key:i,data:r,link:l,addDocLink:I=!0}=t;let h="",f="",w="";mv(x_[i])?h=x_[i](r):ih(x_[i])&&(h=x_[i]);const{TRTC_ERROR_INFO:_,TRTC_ERROR_LINK:G}=dIA();l?w=`${l.className}.html#${l.fnName}`:G&&G[i]&&(mv(G[i])?w=G[i](r):ih(G[i])&&(w=G[i]));let U=h;return zy()&&(_&&_[i]&&(mv(_[i])?f=_[i](r):ih(_[i])&&(f=_[i])),f&&(U=I?`${f} -请查看文档: ${mZ("zh-cn",w)} +`}}}),$cA=WU({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/index.js"(t){var i=ZcA(),n=XcA(),c=E4();t.grammar=c,t.write=n,t.parse=i.parse,t.parseParams=i.parseParams,t.parseFmtpConfig=i.parseFmtpConfig,t.parsePayloads=i.parsePayloads,t.parseRemoteCandidates=i.parseRemoteCandidates,t.parseImageAttributes=i.parseImageAttributes,t.parseSimulcastStreamList=i.parseSimulcastStreamList}}),AlA={x:{required:!0,type:"number"},y:{required:!0,type:"number"},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},zIndex:{required:!0,type:"number"},fillMode:{required:!1,type:"string"},mirror:{required:!1,type:"boolean"},rotation:{required:!1,type:"number"},hidden:{required:!1,type:"boolean"}},i7=(t,i=!1)=>({type:"object",required:i,properties:{canvasColor:{required:!1,type:["string",CanvasGradient,CanvasPattern]},width:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},height:{required:!0,type:"number",notLessThanZero:!0,min:1,max:3840},frameRate:{required:!1,type:"number",notLessThanZero:!0,min:1,max:60}},validate(n,c,I){const{RtcError:C,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(!n)return;const{width:_,height:N}=n;if(_&&N&&_*N>8294400)throw new C({code:f.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),o7=t=>({required:!1,type:["string",HTMLElement,null],validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:f}=t.errorModule;if(t.utils.isString(i)&&!document.getElementById(i))throw new I({code:C.INVALID_PARAMETER,extraCode:f.INVALID_ELEMENT_ID,fnName:c,messageParams:{key:n}})}}),ZU=(t,i=!0)=>({type:"object",required:i,properties:Rn({},AlA),validate(n,c,I){const{RtcError:C,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(n){if(n.fillMode&&!["contain","cover","fill"].includes(n.fillMode))throw new C({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:I});if(n.rotation&&![0,90,180,270].includes(n.rotation))throw new C({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:I})}}}),s7=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},cameraId:{required:!1,type:"string"},videoTrack:{required:!1,instanceof:MediaStreamTrack},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},layout:Rn({},ZU(t))}}}),n7=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},profile:{required:!1,type:["string","object"],properties:{width:{type:"number"},height:{type:"number"},frameRate:{type:"number"},bitrate:{type:"number"}}},captureElement:{required:!1,type:HTMLElement},preferDisplaySurface:{required:!1,type:"string"},layout:Rn({},ZU(t))},validate(i,n,c){const{RtcError:I,ErrorCode:C,ErrorCodeDictionary:f}=t.errorModule;if(!t.rtcDectection.isScreenCaptureApiAvailable())throw new I({code:C.ENV_NOT_SUPPORTED,fnName:c,extraCode:f.NOT_SUPPORTED_SCREEN_SHARE})}}}),r7=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},content:{required:!0,type:"string"},font:{required:!1,type:"string"},color:{required:!1,type:["string",CanvasGradient,CanvasPattern]},layout:Rn({},ZU(t))}}}),a7=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},ZU(t))}}}),g7=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},ZU(t))}}});function elA(t){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:Rn({},o7(t)),canvasInfo:Rn({},i7(t,!0)),camera:Rn({},s7(t)),screen:Rn({},n7(t)),text:Rn({},r7(t)),image:Rn({},a7(t)),video:Rn({},g7(t))},validate(i,n,c,I){const{RtcError:C,ErrorCode:f,ErrorCodeDictionary:w}=t.errorModule;if(t.environment.isMobile())throw new C({code:f.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:_}=i;if(_&&!t.utils.isFunction(_))throw new C({code:f.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,fnName:c,messageParams:{key:"onScreenShareStop",value:typeof _,rule:{type:"Function"}}})}}}function tlA(t){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:Rn({},o7(t)),canvasInfo:Rn({},i7(t)),camera:Rn({},s7(t)),screen:Rn({},n7(t)),text:Rn({},r7(t)),image:Rn({},a7(t)),video:Rn({},g7(t))}}}function ilA(t){return{name:"StopVideoMixerOptions",required:!1}}var c7=(t=>(t[t.INVALID_PARAMETER=4096]="INVALID_PARAMETER",t[t.INVALID_OPERATION=4097]="INVALID_OPERATION",t[t.NOT_SUPPORTED=4098]="NOT_SUPPORTED",t[t.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",t[t.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",t[t.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",t[t.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",t[t.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",t[t.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",t[t.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",t[t.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",t[t.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",t[t.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",t[t.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",t[t.CLIENT_BANNED=16448]="CLIENT_BANNED",t[t.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",t[t.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",t[t.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",t[t.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",t[t.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",t[t.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",t[t.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",t[t.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",t[t.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",t[t.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",t[t.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",t[t.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",t[t.API_CALL_ABORTED=16461]="API_CALL_ABORTED",t[t.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",t[t.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",t[t.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",t[t.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",t[t.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",t[t.UNKNOWN=65535]="UNKNOWN",t))(c7||{}),qg=c7,olA=function(t){for(const i in qg)if(qg[i]===t)return i;return"UNKNOWN"},slA=class extends Error{constructor({name:t="RtcError",message:i,code:n=qg.UNKNOWN,extraCode:c=0,constraint:I}){const C=`<${olA(n)} 0x${n.toString(16)}>`,f=`${i}${I?` constraint: ${I}`:""}${i?.includes(C)?"":` ${C}`}`;super(f),Be(this,"code"),Be(this,"extraCode"),Be(this,"message"),Be(this,"originMessage"),Be(this,"name"),Be(this,"constraint"),this.code=n,this.extraCode=c,this.name=t,this.message=f,this.constraint=I,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},fl=slA,nlA=0,d4=function(){return Date.now()+nlA},l7=function(){const t=new Date;return t.setTime(d4()),t.toLocaleString()},rlA=function(t){let i=String(t.getMilliseconds());return"padStart"in String.prototype&&(i=i.toString().padStart(3,"0")),`${t.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/,"$1")}:${i}`},alA={};u4(alA,{REPORT_TYPE:()=>N7,buildSSOPackage:()=>Q4,bytes2ms:()=>LlA,calculateScaleResolutionDownNumber:()=>_7,concatArrayBuffers:()=>rIA,convertObjectNumberToInt:()=>R7,copyProperties:()=>klA,deepClone:()=>OY,deepCloneBasic:()=>lW,deepMerge:()=>S7,delay:()=>IT,fibonacci:()=>B4,formatedTime:()=>AIA,getConstructorName:()=>YlA,getContainerFromElement:()=>XlA,getEnv:()=>RlA,getFirst16Bits:()=>gIA,getInternalVersion:()=>qlA,getLast16Bits:()=>aIA,getLoggerUrl:()=>C4,getMediaStreamTrackInfo:()=>oIA,getMuteStateFromFlag:()=>D7,getNetworkType:()=>h4,getNumNetworkType:()=>blA,getReconnectionTimeout:()=>OlA,getStringByteLength:()=>eIA,getTestSignalDomain:()=>_lA,getTurnServer:()=>WlA,getUint32Version:()=>v7,getValueType:()=>kv,getViewListFromView:()=>ZlA,glog:()=>FlA,ipv4ToUint32:()=>zlA,isArray:()=>oh,isAudioWorkletSupported:()=>VlA,isBoolean:()=>Sv,isConstructor:()=>y7,isEmpty:()=>jlA,isFunction:()=>Dv,isLangChinese:()=>Zy,isMediaStreamTrack:()=>PlA,isNumber:()=>Lv,isObject:()=>Qv,isOverseaSdkAppId:()=>FY,isPlainObject:()=>lT,isPortrait:()=>M7,isPromise:()=>f7,isRemoteTrack:()=>xlA,isRotate90Or270:()=>T7,isSetSinkIdSupported:()=>JlA,isString:()=>rh,isUndefined:()=>er,isVideoMixerOutputTrack:()=>p4,loadImage:()=>tIA,loadVideo:()=>sIA,ms2bytes:()=>UlA,ms2samples:()=>m7,normalizeUrl:()=>iIA,performanceNow:()=>Yc,promiseAny:()=>HlA,samples2ms:()=>p7,setNetworkTypeFromWebRTC:()=>GlA,stringify:()=>Xy,stringifyIncludeValue:()=>cW,throttlePromise:()=>w7});var UY="5.0.0",I7=typeof importScripts<"u",u7=typeof registerProcessor<"u",glA="web.sdk.qcloud.com",iW=`https://${glA}/trtc/webrtc/doc`,RZ="https://cloud.tencent.com/document/product/647/85386",wZ="https://trtc.io/document/56025",clA="https://yun.tim.qq.com",llA="https://apisgp.my-imcloud.com",IlA="trtc_error_assistance",E7={LOG:"jssdk_log"},s3={QCLOUD:"qcloud"},L_=(t=>(t[t.TRACE=0]="TRACE",t[t.DEBUG=1]="DEBUG",t[t.INFO=2]="INFO",t[t.WARN=3]="WARN",t[t.ERROR=4]="ERROR",t[t.NONE=5]="NONE",t))(L_||{}),d7={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},ulA=6048e5,ElA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},dlA=ElA["480p_2"],ei={CANVAS:"canvas",AUDIO:"audio",VIDEO:"video",SCREEN:"screen",SMALL:"small",BIG:"big",AUXILIARY:"auxiliary",SMALL_VIDEO:"smallVideo",FACING_MODE_USER:"user",FACING_MODE_ENVIRONMENT:"environment",MUTE:"mute",UNMUTE:"unmute",ENDED:"ended",PLAYING:"playing",PAUSE:"pause",ERROR:"error",LOADSTART:"loadstart",LOADEDDATA:"loadeddata",LOADEDMETADATA:"loadedmetadata",AUDIO_INPUT:"audioinput",VIDEO_INPUT:"videoinput",DETAIL:"detail",TEXT:"text",MAIN:"main",BACKUP:"backup",BANNED:"banned",KICK:"kick",USER_TIME_OUT:"user_time_out",ROOM_DISBAND:"room_disband",SEI_MESSAGE:"sei-message",ADD:"add",REMOVE:"remove",REPLACE:"replace",TRACK:"track",SUBSCRIBE:"subscribe",UNSUBSCRIBE:"unsubscribe",TRANSCEIVER_DIRECTION_SENDONLY:"sendonly",TRANSCEIVER_DIRECTION_RECVONLY:"recvonly",ENTER_PICTURE_IN_PICTURE:"enterpictureinpicture",LEAVE_PICTURE_IN_PICTURE:"leavepictureinpicture",FULLSCREEN_CHANGE:"fullscreenchange",RESIZE:"resize",TIME_UPDATE:"timeupdate"},_Z=1,ClA=2,hlA=4,TZ=8,NZ=64,GZ=16,BlA=256,lU={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},QlA="unified-plan",U_=5,C7="default",W1=2e3,h7=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],plA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},mlA=function(t,i,n,c){return new(n||(n=Promise))(function(I,C){function f(N){try{_(c.next(N))}catch(L){C(L)}}function w(N){try{_(c.throw(N))}catch(L){C(L)}}function _(N){var L;N.done?I(N.value):(L=N.value,L instanceof n?L:new n(function(q){q(L)})).then(f,w)}_((c=c.apply(t,[])).next())})},oW=Symbol(32),sW=Symbol(16),nW=Symbol(8),AT=class{constructor(t){this.g=t,this.consumed=0,t&&(this.need=t.next().value)}setG(t){this.g=t,this.demand(t.next().value,!0)}consume(){this.buffer&&this.consumed&&(this.buffer.copyWithin(0,this.consumed),this.buffer=this.buffer.subarray(0,this.buffer.length-this.consumed),this.consumed=0)}demand(t,i){return i&&this.consume(),this.need=t,this.flush()}read(t){return mlA(this,void 0,void 0,function*(){return this.lastReadPromise&&(yield this.lastReadPromise),this.lastReadPromise=new Promise((i,n)=>{var c;this.reject=n,this.resolve=I=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(I)},this.demand(t,!0)||(c=this.pull)===null||c===void 0||c.call(this,t)})})}readU32(){return this.read(oW)}readU16(){return this.read(sW)}readU8(){return this.read(nW)}close(){var t;this.g&&this.g.return(),this.buffer&&this.buffer.subarray(0,0),(t=this.reject)===null||t===void 0||t.call(this,new Error("EOF")),delete this.lastReadPromise}flush(){if(!this.buffer||!this.need)return;let t=null;const i=this.buffer.subarray(this.consumed);let n=0;const c=I=>i.length<(n=I);if(typeof this.need=="number"){if(c(this.need))return;t=i.subarray(0,n)}else if(this.need===oW){if(c(4))return;t=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===sW){if(c(2))return;t=i[0]<<8|i[1]}else if(this.need===nW){if(c(1))return;t=i[0]}else if("buffer"in this.need){if("byteOffset"in this.need){if(c(this.need.byteLength-this.need.byteOffset))return;new Uint8Array(this.need.buffer,this.need.byteOffset).set(i.subarray(0,n)),t=this.need}else if(this.g)return void this.g.throw(new Error("Unsupported type"))}else{if(c(this.need.byteLength))return;new Uint8Array(this.need).set(i.subarray(0,n)),t=this.need}return this.consumed+=n,this.g?this.demand(this.g.next(t).value,!0):this.resolve&&this.resolve(t),t}write(t){if(t instanceof Uint8Array?this.malloc(t.length).set(t):"buffer"in t?this.malloc(t.byteLength).set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):this.malloc(t.byteLength).set(new Uint8Array(t)),!this.g&&!this.resolve)return new Promise(i=>this.pull=i);this.flush()}writeU32(t){this.malloc(4).set([t>>24&255,t>>16&255,t>>8&255,255&t]),this.flush()}writeU16(t){this.malloc(2).set([t>>8&255,255&t]),this.flush()}writeU8(t){this.malloc(1)[0]=t,this.flush()}malloc(t){if(this.buffer){const i=this.buffer.length,n=i+t;if(n<=this.buffer.buffer.byteLength-this.buffer.byteOffset)this.buffer=new Uint8Array(this.buffer.buffer,this.buffer.byteOffset,n);else{const c=new Uint8Array(n);c.set(this.buffer),this.buffer=c}return this.buffer.subarray(i,n)}return this.buffer=new Uint8Array(t),this.buffer}};AT.U32=oW,AT.U16=sW,AT.U8=nW;var flA=128;function n3(t){const i=new AT;for(;t>=128;)i.malloc(1)[0]=255&t|flA,t>>>=7;return i.malloc(1)[0]=255&t,i.buffer||new Uint8Array(0)}function rW(t,i=0){const n=new AT,c=i<<3;switch(typeof t){case"boolean":const I=n.malloc(2);I[0]=c,I[1]=t?1:0;break;case"number":n.malloc(1)[0]=c,n.write(n3(t));break;case"string":n.malloc(1)[0]=2|c;const C=new TextEncoder().encode(t);n.write(n3(C.length));const f=n.malloc(C.length);for(let _=0;_>>24&255),this.buffer.push(t>>>16&255),this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeInt16(t){this.buffer.push(t>>>8&255),this.buffer.push(255&t)}writeByte(t){this.buffer.push(255&t)}writeBytes(t){for(let i=0;i>>24&255,t[n+1]=i>>>16&255,t[n+2]=i>>>8&255,t[n+3]=255&i}function ad(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function LZ(t,i){return t[i]}function wL(t,i,n){return new TextDecoder().decode(ylA(t,i,n))}function ylA(t,i,n){return t.slice(i,i+n)}var r3=0,aW=2654435769,gW=16,UZ=4,IU=2,uU=7;function DlA(t,i,n,c="AVQualityReportSvc.C2S",I=2e3,C=2,f=30){return{version:I,encryption:C,d2:"",d2Len:0,uinType:f,uin:"",uinLen:0,reqHead:{seqNumber:n,appId:t,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:c,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:i}}function SlA(t,i){const n=new bZ,c=DlA(i,t,r3);r3=r3+1&2147483647,n.writeInt32(0),n.writeInt32(c.version),n.writeByte(c.encryption);const I=new TextEncoder().encode(c.d2);n.writeInt32(I.length+4),I&&n.writeBytes(I),n.writeByte(c.uinType);const C=new TextEncoder().encode(c.uin);n.writeInt32(C.length+4),C.length&&n.writeBytes(C);const f=new bZ;f.writeInt32(0),f.writeInt32(c.reqHead.seqNumber),f.writeInt32(c.reqHead.appId),f.writeByte(c.reqHead.appId>>>24&255),f.writeByte(c.reqHead.appId>>>16&255),f.writeByte(c.reqHead.appId>>>8&255),f.writeByte(255&c.reqHead.appId);for(let HA=4;HA<16;HA++)f.writeByte(0);const w=new TextEncoder().encode(c.reqHead.a2);f.writeInt32(w.length+4),w.length&&f.writeBytes(w);const _=new TextEncoder().encode(c.reqHead.serviceCmd);f.writeInt32(_.length+4),_.length&&f.writeBytes(_);const N=new TextEncoder().encode(c.reqHead.cookie);f.writeInt32(N.length+4),N.length&&f.writeBytes(N);const L=new TextEncoder().encode(c.reqHead.imei);f.writeInt32(L.length+4),L.length&&f.writeBytes(L);const q=new TextEncoder().encode(c.reqHead.ksid);f.writeInt32(q.length+4),q.length&&f.writeBytes(q);const lA=new TextEncoder().encode(c.reqHead.clientVersionInfo);f.writeInt16(lA.length+2),lA.length&&f.writeBytes(lA);const tA=f.length;f.data[0]=tA>>>24&255,f.data[1]=tA>>>16&255,f.data[2]=tA>>>8&255,f.data[3]=255&tA,rh(t)&&(t=new TextEncoder().encode(t)),f.writeInt32(t.length+4),t.length&&f.writeBytes(t);let BA=new Uint8Array(f.data),IA=null;c.encryption===1?IA=new TextEncoder().encode(c.uin):c.encryption===2&&(IA=new Uint8Array(16)),IA&&(BA=MlA(BA,IA)),n.writeBytes(BA);const gA=new Uint8Array(n.data),RA=gA.length;return gA[0]=RA>>>24&255,gA[1]=RA>>>16&255,gA[2]=RA>>>8&255,gA[3]=255&RA,gA}function MlA(t,i){const n=t.length;let c=(n+1+IU+uU)%8;c&&(c=8-c);const I=new Uint8Array(n+1+IU+uU+c);let C=0;const f=new Uint8Array(8),w=new Uint8Array(8),_=new Uint8Array(8);let N=0;f[0]=248&Math.floor(256*Math.random())|c,N=1;for(let q=0;q>>=0,I+=(C<<4)+f[0]^C+w^(C>>>5)+f[1],I>>>=0,C+=(I<<4)+f[2]^I+w^(I>>>5)+f[3],C>>>=0;kZ(n,I,c),kZ(n,C,c+4)}var RlA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},wlA=".rtc.qq.com",_lA=function(t){return t.includes(".")?t:`${t}${wlA}`},FY=t=>Number(t)<14e8,C4=function(t,i){let n;return n=FY(t)?llA:clA,`${n}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${t}&cmdtype=${i}`},B7="unknown";function h4(){NlA();const{userAgent:t,connection:i}=navigator;let n=(t.match(/NetType\/\S+/)||[])[0]||"";n=n.toLowerCase().replace("nettype/",""),n==="3gnet"&&(n="3g");const c=i&&i.type&&i.type.toLowerCase();let I=i&&i.effectiveType&&i.effectiveType.toLowerCase();return I==="slow-2"&&(I="2g"),c?Q7(c,I):B7}function TlA(){Wo.warn("netType changed",h4())}var FZ=!1;function NlA(){var t;FZ||(FZ=!0,(t=navigator.connection)==null||t.addEventListener("typechange",TlA))}function Q7(t,i){if(d7[t])return t;switch(t){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function GlA(t){B7=Q7(t)}function blA(){return d7[h4()]}function klA(t,i){for(const n of Reflect.ownKeys(i))if(n!=="constructor"&&n!=="prototype"&&n!=="name"){const c=Object.getOwnPropertyDescriptor(i,n)||"";Object.defineProperty(t,n,c)}return t}function LlA(t,i=48e3){return p7(t/4,i)}function p7(t,i=48e3){return 1e3*t/i}function UlA(t,i=48e3){return 4*m7(t,i)}function m7(t,i=48e3){return t*i/1e3}var FlA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Zy=()=>{let t=navigator.language;return t=t.substring(0,2),t==="zh"},lT=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function B4(t,i=1,n=1){return t<=1?n:B4(t-1,n,i+n)}function OlA(t){return t>8?3e4:1e3*B4(t)}function kv(t){return Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Dv=t=>typeof t=="function",er=t=>t===void 0,rh=t=>typeof t=="string",Lv=t=>typeof t=="number",Sv=t=>typeof t=="boolean",Qv=t=>kv(t)==="object",oh=t=>kv(t)==="array",PlA=t=>kv(t)==="MediaStreamTrack".toLowerCase(),xlA=t=>t.isRemote,f7=t=>kv(t)==="promise",y7=t=>Dv(t)&&t.prototype.constructor===t,YlA=t=>y7(t)?t.prototype.constructor.name:"",VlA=typeof AudioWorkletNode<"u",JlA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function HlA(t){return new Promise((i,n)=>{const c=[];t.forEach(I=>{I.then(i).catch(C=>{c.push(C),c.length===t.length&&n(c)})})})}function Yc(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var OZ=t=>+t<10?`0${t}`:t,qlA=t=>{const i=t.match(/^\d+\.\d+\.\d+/)[0];if(!i)return t;const n=i.split("."),c=OZ(n[1])+OZ(n[2]);return n[1]-15>0&&(n[1]="15"),n[2]-15>0&&(n[2]="15"),`${n.join(".")}.${c}`},KlA=Object.prototype.hasOwnProperty;function jlA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(lT(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(KlA.call(t,i))return!1;return!0}return!1}function D7(t,i){return{userId:i,hasAudio:!!(t&TZ),hasVideo:!!(t&_Z),hasAuxiliary:!!(t&hlA),hasSmall:!!(t&ClA),audioMuted:!!(t&NZ),videoMuted:!!(t&GZ),audioAvailable:!(!(t&TZ)||t&NZ),videoAvailable:!(!(t&_Z)||t&GZ),hasDatachannel:!!(t&BlA)}}function WlA(t){const i={urls:t.url.startsWith("turn:")||t.url.startsWith("turns:")?t.url:`turn:${t.url}`};return er(t.username)||er(t.credential)||(i.username=t.username,i.credential=t.credential,i.credentialType="password",er(t.credentialType)||(i.credentialType=t.credentialType)),i}function zlA(t,i=!0){if(!rh(t))return 0;const n=t.split(".");return i?(Number(n[0])<<24|Number(n[1])<<16|Number(n[2])<<8|Number(n[3]))>>>0:(Number(n[3])<<24|Number(n[2])<<16|Number(n[1])<<8|Number(n[0]))>>>0}var S7=function(t,i,n,c){if(!Qv(t)||!Qv(i))return 0;let I=0;const C=Object.keys(i);let f;for(let w=0,_=C.length;w<_;w++)if(f=C[w],!(er(i[f])||n&&n.includes(f)))if(Qv(t[f])&&Qv(i[f]))I+=S7(t[f],i[f],n,c);else{if(c&&c.includes(i[f]))continue;t[f]!==i[f]&&(t[f]=OY(i[f]),I+=1)}return I};function OY(t){if(oh(t)){const i=[];return t.forEach((n,c)=>{i[c]=OY(n)}),i}if(Qv(t)){const i={};return Object.keys(t).forEach(n=>{i[n]=OY(t[n])}),i}return t}var ZlA=t=>{let i=[];if(oh(t))i=[...t];else if(rh(t)){const n=document.getElementById(t);n&&i.push(n)}else t&&i.push(t);return i},XlA=t=>rh(t)?document.getElementById(t):t,$lA=t=>{const i=n=>n<10?`0${n}`:`${n}`;return`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()} ${i(t.getHours())}:${i(t.getMinutes())}:${i(t.getSeconds())}`},AIA=()=>$lA(new Date);function Xy(t,{keysToInclude:i,keysToExclude:n}){try{if(oh(t))return`[${t.map(f=>Xy(f,{keysToInclude:i,keysToExclude:n})).join(",")}]`;if(!lT(t)||!oh(i)&&!oh(n))return JSON.stringify(t);const c={},I=new Set(i),C=new Set(n);return Object.keys(t).forEach(f=>{(C.size===0&&I.has(f)||I.size===0&&!C.has(f))&&(c[f]=lT(t[f])||oh(t[f])?JSON.parse(Xy(t[f],{keysToExclude:n,keysToInclude:i})):t[f])}),JSON.stringify(c)}catch{return"{}"}}function cW(t,i=!1){const n=[];return Object.keys(t).forEach(c=>{i===t[c]&&n.push(c)}),Xy(t,{keysToInclude:n})}function eIA(t){return t.replace(/[\u4e00-\u9fa5]/g,"aa").length}var M7=()=>{var t,i,n,c;return(t=window.screen)!=null&&t.orientation?!!((c=(n=(i=window.screen)==null?void 0:i.orientation)==null?void 0:n.type)!=null&&c.includes("portrait")):window.orientation===0||window.orientation===180},tIA=async t=>new Promise((i,n)=>{let c;if(rh(t))c=new Image,c.crossOrigin="anonymous",c.src=t;else if(c=t,c.complete)return void i(c);c.onload=()=>i(c),c.onerror=()=>{n(new fl({code:qg.INVALID_PARAMETER,message:`load image failed, url: ${t}`}))}}),v7=t=>{const i=t.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},R7=t=>(Object.keys(t).forEach(i=>{Lv(t[i])&&(i.startsWith("uint")||i.startsWith("int"))?t[i]=Math.floor(t[i]):(lT(t[i])||oh(t[i]))&&R7(t[i])}),t);function IT(t,i){return new Promise(n=>{const c=setTimeout(n,t);i&&i(c)})}function w7(t,i){let n=null;return function(...c){return n||(n=t.apply(i||this,c),n.finally(()=>n=null),n)}}function iIA(t){return t.replace(/(^|[^:])\/{2,}/g,"$1/")}function oIA(t){var i;try{const{width:n,height:c,frameRate:I,sampleRate:C,sampleSize:f,channelCount:w}=(i=t.getSettings)==null?void 0:i.call(t),_=t.kind===ei.AUDIO?`${C}x${f}@${w}`:`${n}x${c}@${I}`,N=t.stats?` stats: ${JSON.stringify(t.stats).replaceAll('"',"")}`:"";return`${t.id} ${t.readyState} muted:${t.muted} ${t.kind} ${t.label} ${_}${N}`}catch{return""}}function _7(t,i){return t.width*t.height===i.width*i.height?1:M7()&&i.width>i.height&&t.height>i.width?Math.max(t.width/i.height,t.height/i.width,1):Math.max(t.width/i.width,t.height/i.height,1)}function T7(t){return t===90||t===270}async function sIA(t){return new Promise((i,n)=>{const c=document.createElement("video");c.crossOrigin="anonymous",c.src=t,c.muted=!0,c.loop=!0,c.playsInline=!0,c.play().then(()=>i(c)),c.onerror=()=>{n(c.error)}})}function lW(t,i=new WeakMap){if(typeof t!="object"||t===null)return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const n=[];return i.set(t,n),t.forEach((c,I)=>{n[I]=lW(c,i)}),n}if(Object.prototype.toString.call(t)==="[object Object]"){const n={};return i.set(t,n),Reflect.ownKeys(t).forEach(c=>{n[c]=lW(t[c],i)}),n}return t}var N7=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(N7||{});function nIA(t,i,n,c){let I={data:t,random:Math.floor(Math.random()*2147483648),sdkAppId:n};return er(c)||(I=gB(Rn({},I),{gzip:+c})),{uint32_sdkappid:0,uint64_from_uin:0,uint32_timestamp:0,uint32_seq:0,msg_common_info:{msg_device_info:{enum_device_type:0,str_device_brand:"",str_device_model:"",str_device_board:"",str_device_cpu_abi:""},msg_system_info:{enum_os_type:0,str_os_version:"",msg_network_info:0},msg_network_info:{enum_network_type:0}},msg_report_content:{uint32_type:i,bytes_report_data:JSON.stringify(I)}}}function Q4(t,i,n,c){try{const I=nIA(t,i,n,c);return SlA(rW(I),n)}catch{return JSON.stringify(t)}}function rIA(t,i){const n=new Uint8Array(t.byteLength+i.byteLength);return n.set(new Uint8Array(t),0),n.set(new Uint8Array(i),t.byteLength),n.buffer}function aIA(t){return(65535&t)>>>0}function gIA(t){return(4294901760&t)>>>0}function p4(t){return!!(t&&t instanceof CanvasCaptureMediaStreamTrack&&t.canvas.id.includes("trtc_mix"))}function cIA(t){const i=lIA(t);return i?.busiBuff}function lIA(t){try{const i={};let n=0;i.totalLength=ad(t,n),n+=4,i.version=ad(t,n),n+=4,i.encryption=LZ(t,n),n+=1,i.uinType=LZ(t,n),n+=1,i.uinLength=ad(t,n),n+=4,i.uin=i.uinLength>4?wL(t,n,i.uinLength-4):"",n+=i.uinLength-4;const c=t.slice(n);if(i.encryption===2){const I=new Uint8Array(16).fill(0);t=IIA(c,I),i.decrypted=!0,n=0}else t=c,n=0;return i.rspHeadLength=ad(t,n),n+=4,i.seqNo=ad(t,n),n+=4,i.retCode=ad(t,n),n+=4,i.retStrLength=ad(t,n),n+=4,i.retStr=i.retStrLength?wL(t,n,i.retStrLength-4):"",n+=i.retStrLength-4,i.serviceCmdLength=ad(t,n),n+=4,i.serviceCmd=i.serviceCmdLength?wL(t,n,i.serviceCmdLength-4):"",n+=i.serviceCmdLength-4,i.cookieLength=ad(t,n),n+=4,i.cookie=i.cookieLength?wL(t,n,i.cookieLength-4):"",n+=i.cookieLength-4,i.flag=ad(t,n),n+=4,i.busiBuffLength=ad(t,n),n+=4,i.busiBuff=i.busiBuffLength?wL(t,n,i.busiBuffLength-4):"",n+=i.busiBuffLength-4,i}catch{}}function G7(t,i){let n=t[0]<<24|t[1]<<16|t[2]<<8|t[3],c=t[4]<<24|t[5]<<16|t[6]<<8|t[7];n>>>=0,c>>>=0;let I=aW*gW>>>0;for(let C=0;C>>5)+i[3],c>>>=0,n-=(c<>>5)+i[1],n>>>=0,I-=aW,I>>>=0;return new Uint8Array([n>>>24&255,n>>>16&255,n>>>8&255,255&n,c>>>24&255,c>>>16&255,c>>>8&255,255&c])}function IIA(t,i){let n=0;const c=new Uint8Array(8).fill(0);let I=G7(new Uint8Array(t.slice(0,8)),i);const C=7&I[0],f=t.length-1-C-IU-uU,w=new Uint8Array(f);let _=0,N=c,L=t.slice(0,8);n=8;let q=1;q+=C;for(let tA=1;tA<=IU;)if(q<8)q++,tA++;else if(q===8){const BA=g3(t,n,N,L,I,i);N=BA.ivPreCrypt,L=BA.ivCurCrypt,I=BA.debiBuf,n=BA.bufPos,q=0}let lA=f;for(;lA>0;)if(q<8)w[_++]=I[q]^N[q],q++,lA--;else if(q===8){const tA=g3(t,n,N,L,I,i);N=tA.ivPreCrypt,L=tA.ivCurCrypt,I=tA.debiBuf,n=tA.bufPos,q=0}for(let tA=1;tA<=uU;)if(q<8)I[q],N[q],q++,tA++;else if(q===8){if(n>=t.length)break;const BA=g3(t,n,N,L,I,i);if(!BA.success)break;N=BA.ivPreCrypt,L=BA.ivCurCrypt,I=BA.debiBuf,n=BA.bufPos,q=0}return w}function g3(t,i,n,c,I,C){if(i+8>t.length)return{success:!1};const f=new Uint8Array(c),w=t.slice(i,i+8),_=new Uint8Array(8);for(let N=0;N<8;N++)_[N]=I[N]^w[N];return{success:!0,ivPreCrypt:f,ivCurCrypt:w,debiBuf:G7(_,C),bufPos:i+8}}var PZ=typeof TextDecoder<"u"?new TextDecoder:void 0;function b7({url:t,body:i,method:n="POST",timeout:c,priority:I}){return new Promise((C,f)=>{if("fetch"in window)return fetch(t,{method:n,body:i,priority:I}).then(_=>_.clone().json().then(N=>({data:N}),()=>_.arrayBuffer().then(N=>({data:cIA(new Uint8Array(N))||(PZ?PZ.decode(N):N)})))).then(C,f);const w=new XMLHttpRequest;w.onreadystatechange=()=>{if(w.readyState===4)if(w.status>=200&&w.status<300)try{const _=JSON.parse(w.response);C({data:_})}catch{C({data:w.response})}else f({status:w.status,statusText:w.statusText||"request failed!"})},w.timeout=c||5e3,w.open(n,t,!0),w.send(i)})}var uIA=Object.prototype.hasOwnProperty,F_=t=>typeof t=="function",v_=t=>t===void 0,EIA=t=>typeof t=="boolean",c3=t=>t.isRemote,dIA=function(t){if(!t||typeof t!="object"||Object.prototype.toString.call(t)!="[object Object]")return!1;const i=Object.getPrototypeOf(t);if(i===null)return!0;const n=Object.prototype.hasOwnProperty.call(i,"constructor")&&i.constructor;return typeof n=="function"&&n instanceof n&&Function.prototype.toString.call(n)===Function.prototype.toString.call(Object)};function CIA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(dIA(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(uIA.call(t,i))return!1;return!0}return!1}var hIA=0,BIA=1,xZ=2;function QIA({retryFunction:t,settings:i,onError:n,onRetrying:c,onRetryFailed:I,onRetrySuccess:C,context:f}){return function(...w){const{retries:_=5,timeout:N=1e3}=i;let L=0,q=-1,lA=hIA;const tA=async(BA,IA)=>{const gA=f||this;try{const RA=await t.apply(gA,w);L>0&&C&&C.call(this,L),L=0,BA(RA)}catch(RA){const HA=()=>{clearTimeout(q),L=0,lA=xZ,IA(RA)},ZA=()=>{lA!==xZ&&L<(F_(_)?_():_)?(L++,lA=BIA,F_(c)&&c.call(this,L,HA),q=window.setTimeout(()=>{q=-1,tA(BA,IA)},F_(N)?N(L):N)):(HA(),F_(I)&&I.call(this,RA))};F_(n)?n.call(this,{error:RA,retry:ZA,reject:IA,retryFuncArgs:w,retriedCount:L}):ZA()}};return new Promise(tA)}}var m4=QIA,l3=class k7{constructor(i){Be(this,"_parentPath"),Be(this,"userId"),Be(this,"remoteUserId"),Be(this,"id"),Be(this,"sdkAppId"),Be(this,"type"),Be(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!EIA(i.isLocal)||i.isLocal,this.type=this.isLocal?"":i.type}getFullId(){return this._parentPath&&this.id?`${this._parentPath}-${this.id}`:this._parentPath?this._parentPath:this.id}createChild(i){const n=new k7({id:i.id,userId:v_(i.userId)?this.userId:i.userId,sdkAppId:v_(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:v_(i.type)?this.type:i.type,isLocal:v_(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:v_(i.remoteUserId)?this.remoteUserId:i.remoteUserId});return n.bindParent(this),n}bindParent(i){const n=i.getFullId();this._parentPath!==n&&(this.debug(`bind logger parent: ${i.id}`),this._parentPath=n,this.userId=i.userId||this.userId,this.sdkAppId=i.sdkAppId||this.sdkAppId)}setUserId(i){this.userId=i}setSdkAppId(i){this.sdkAppId=i}log(i,n){const c=this.isLocal?this.userId:this.remoteUserId,I=this.getFullId();n.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${I}${c?`|${c}`:""}]`),Wo.log(i,n,v_(this.userId)||CIA(this.userId),this.userId,this.sdkAppId)}info(...i){this.log(2,i)}debug(...i){this.log(1,i)}warn(...i){this.log(3,i)}error(...i){this.log(4,i)}},NQ=typeof navigator>"u"?"":navigator.userAgent,Vs=t=>new RegExp(t,"i").test(NQ),Qc=t=>{if(Vs(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),n=NQ.match(i);if(n&&n[1])return n[1]}return""},RV=t=>{if(Vs(t)){const i=new RegExp(`${t}\\/(\\d+)`),n=NQ.match(i);if(n&&n[1])return parseFloat(n[1])}return NaN},YZ=/AppleWebKit\/([\d.]+)/i.exec(NQ);YZ&&parseFloat(YZ[1]);var f4=Vs("iPad"),L7=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Vs("Macintosh"),wV=Vs("iPhone")&&!f4,pIA=Vs("iPod"),vu=wV||f4||pIA||L7,PY=()=>{try{return vu&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return vu}},cC=Vs("Android"),U7=function(){if(cC){const t=NQ.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(t){const i=t[1]&&parseFloat(t[1]),n=t[2]&&parseFloat(t[2]);if(i&&n)return parseFloat(`${t[1]}.${t[2]}`);if(i)return i}}return NaN}();cC&&Vs("webkit")&&U7<2.3;var rC=Vs("Firefox"),F7=Qc("Firefox"),O7=RV("Firefox"),XU=Vs("Edge"),P7=Qc("Edge"),_V=Vs("Edg"),x7=Qc("Edg"),mIA=RV("Edg"),y4=Vs("SogouMobileBrowser"),Y7=Qc("SogouMobileBrowser"),D4=Vs("MetaSr\\s"),V7=Qc("MetaSr\\s"),mm=Vs("TBS"),J7=Qc("TBS"),fT=Vs("XWEB"),H7=Qc("XWEB");Vs("MSIE\\s8\\.0");var fIA=Vs("MSIE\\/\\d+");(function(){if(fIA){const t=/MSIE\s(\d+)\.\d/.exec(NQ);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(NQ)&&/rv:11.0/.test(NQ)&&(i=11),i}return NaN})();var $U=Vs("(micromessenger|webbrowser)"),q7=Qc("MicroMessenger"),TV=!mm&&Vs("MQQBrowser")&&Vs("COVC"),NV=!mm&&Vs("MQQBrowser")&&!Vs("COVC"),xY=NV||TV?Qc("MQQBrowser"):"",S4=!mm&&Vs(" QQBrowser"),K7=Qc(" QQBrowser"),M4=!mm&&Vs("QQBrowserLite"),j7=Qc("QQBrowserLite"),v4=!mm&&Vs("MQBHD"),W7=Qc("MQBHD"),z7=Vs("Windows"),GV=!vu&&Vs("MAC OS X"),Z7=!cC&&Vs("Linux"),X7=Vs("CrOS");Vs("MicroMessenger");var yIA=Vs("UCBrowser");Vs("Electron");var R4=Vs("MiuiBrowser"),$7=Qc("MiuiBrowser"),w4=Vs("HuaweiBrowser"),A$=Vs("Huawei")||Vs("HUAWEI"),DIA=Vs("Honor")||Vs("HONOR"),e$=Qc("HuaweiBrowser"),_4=Vs("SamsungBrowser"),t$=Qc("SamsungBrowser"),bV=Vs("HeyTapBrowser"),i$=Qc("HeyTapBrowser"),T4=Vs("VivoBrowser"),o$=Qc("VivoBrowser"),N4=Vs("OpenHarmony");Qc("OpenHarmony");var s$=()=>RV("Chrome"),YY=Vs("CriOS"),sD=Vs("Chrome"),G4=!XU&&!D4&&!y4&&!mm&&!fT&&!_V&&!S4&&!R4&&!w4&&!_4&&!bV&&!T4&&sD,SIA=Vs("HeadlessChrome"),nD=s$(),I3=sD&&nD>=128&&nD<=143,n$=Qc("Chrome");RV("Electron");var ld=!sD&&!NV&&!TV&&!M4&&!v4&&Vs("Safari"),r$=ld||vu,AF=Qc("Version"),wQ=(()=>{if(L7)return AF;if(vu){const t=NQ.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();function MIA(t,i){const n=t.split(".").map(I=>Number(I)),c=i.split(".").map(I=>Number(I));for(let I=0;If)return!1}return!1}function a$(t,i,n=!1){const c=t.split(".").map(C=>Number(C)),I=i.split(".").map(C=>Number(C));for(let C=0;Cw)return!0;if(f{const t=Number(wQ.split(".")[0]);return t===14||t===13})(),wIA=YY&&AF==="11.1.1",VY=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),R_=(()=>{let t;return()=>{if(t===void 0)try{t=!!window.localStorage}catch{t=!1}return t}})(),Mv=_IA();function _IA(){const t=new Map([[rC,["Firefox",F7]],[_V,["Edg",x7]],[G4,["Chrome",n$]],[YY,["ChiOS",Qc("CriOS")]],[ld&&!YY,["Safari",AF]],[mm,["TBS",J7]],[fT,["XWEB",H7]],[$U&&wV,["WeChat",q7]],[S4,["QQ(Win)",K7]],[NV,["QQ(Mobile)",xY]],[TV,["QQ(Mobile X5)",xY]],[M4,["QQ(Mac)",j7]],[v4,["QQ(iPad)",W7]],[R4,["MI",$7]],[w4,["HW",e$]],[_4,["Samsung",t$]],[bV,["OPPO",i$]],[T4,["VIVO",o$]],[XU,["EDGE",P7]],[y4,["SogouMobile",Y7]],[D4,["Sogou",V7]]]);let i="unknown",n="unknown";return t.has(!0)&&([i,n]=t.get(!0)),{name:i,version:n}}function TIA(){return cC||vu||wV||f4||N4}var NIA="";function g$(){return GIA()||""}function GIA(){const t=NQ.match(/;\s*([^;)]+)\s+Build\//);return t?.[1]?t[1].trim():null}var VZ=new Map([[cC,"Android"],[vu,"iOS"],[z7,"Windows"],[GV,"MacOS"],[Z7,"Linux"],[X7,"ChromeOS"]]),c$=function(){return VZ.get(!0)?VZ.get(!0):"unknown"};function b4(){return z7?1:cC?2:GV?3:vu?4:Z7?5:X7?6:N4?7:0}function bIA(){return $U||fT?4:sD?1:ld?2:rC?3:0}var l$=()=>{let t=c$();return vu?t+=`/${wQ}`:cC&&(t+=`/${U7}`),t+=`/${Mv.name}/${ld&&!YY?Mv.version:Mv.version.split(".")[0]}`,t},kIA=mT(zU()),LIA=new kIA.default,ms=LIA,I$=(t=>(t.ROOM_DESTROY="1",t.JOIN_START="21",t.JOIN_SCHEDULE_SUCCESS="22",t.JOIN_SIGNAL_CONNECTION_START="23",t.JOIN_SIGNAL_CONNECTION_END="24",t.JOIN_SEND_CMD="25",t.JOIN_RECEIVED_CMD_RES="26",t.JOIN_SUCCESS="27",t.JOIN_FAILED="28",t.LEAVE_START="51",t.LEAVE_SEND_CMD="52",t.LEAVE_SUCCESS="53",t.PUBLISH_START="61",t.SEND_FIRST_VIDEO_FRAME="62",t.PUBLISH_FAILED="63",t.SUBSCRIBE_START="81",t.SUBSCRIBE_SUCCESS="82",t.SUBSCRIBE_FAILED="84",t.UNSUBSCRIBE_SUCCESS="83",t.LOCAL_TRACK_CAPTURE_START="101",t.LOCAL_TRACK_CAPTURE_SUCCESS="102",t.LOCAL_TRACK_CAPTURE_FAILED="103",t.LOCAL_TRACK_PUBLISHED="104",t.LOCAL_TRACK_UNPUBLISHED="105",t.LOCAL_TRACK_REPLACED="106",t.SWITCH_DEVICE_SUCCESS="107",t.TRACK_MUTED="108",t.TRACK_UNMUTED="109",t.REMOTE_TRACK_SUBSCRIBED="110",t.REMOTE_TRACK_UNSUBSCRIBED="111",t.LOCAL_TRACK_RECAPTURE="112",t.LOCAL_AUDIO_STARTED="113",t.LOCAL_AUDIO_STOPPED="114",t.REMOTE_AUDIO_STARTED="115",t.REMOTE_AUDIO_STOPPED="116",t.LOCAL_TRACK_STOPPED="117",t.LOCAL_VIDEO_TRACK_PREPROCESSED="118",t.PLAY_TRACK_START="151",t.PLAYER_STATE_CHANGED="152",t.VIDEO_LOADED_DATA="153",t.AUTOPLAY_DIALOG_CLICK_CONFIRM="154",t.AUDIO_CONTEXT_LONG_SUSPENDED="155",t.REMOTE_VIDEO_PLAY_START="156",t.REMOTE_VIDEO_PLAY_FINISH="157",t.SIGNAL_CONNECTION_STATE_CHANGED="201",t.PEER_CONNECTION_STATE_CHANGED="202",t.SINGLE_CONNECTION_STAT="203",t.SPC_RECONNECTED="204",t.HEARTBEAT_REPORT="251",t.RECEIVED_PUBLISHED_USER_LIST="252",t.REMOTE_PUBLISH_STATE_CHANGED="253",t.AUDIO_LEVEL_INTERVAL="260",t.NETWORK_QUALITY="261",t.VIDEO_CODEC_IMPLEMENTATION_CHANGED="262",t.QUALITY_LIMITATION_CHANGED="263",t.LOG="264",t.AUDIO_PROCESSOR_DEBUG="265",t.SSO_SWITCH="266",t.SEI_MESSAGE="267",t.USER_PAUSE_IN_PIP="268",t.USER_RESUME_IN_PIP="269",t.ENTER_PICTURE_IN_PICTURE="270",t.LEAVE_PICTURE_IN_PICTURE="271",t.SWITCH_ROOM_START="401",t.SWITCH_ROOM_SUCCESS="407",t.SWITCH_ROOM_FAILED="408",t))(I$||{}),mn=I$,UIA=class{constructor(){Be(this,"enable",!1),Be(this,"ssoFailCount",0),ms.on("22",({schedule:t})=>{var i;(i=t?.config)!=null&&i.sso&&ms.emit("266",{enable:!0})}),ms.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&ms.emit("266",{enable:!1})}},IW=new UIA,FIA="%cTRTC%c%s",OIA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",PIA="display: inline",u$=class E${constructor(){Be(this,"_isEnableUploadLog",!0),Be(this,"_localJoinedUser",new Map),Be(this,"_queue",[]),Be(this,"_timeoutId",-1),Be(this,"_logLevel",1),Be(this,"_logLevelToUpload",2),I7||u7||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){ms.on(mn.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var n;(n=i?.config)!=null&&n.logLevelToUpload&&L_[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),ms.on(mn.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),ms.on(mn.LEAVE_SUCCESS,({room:i})=>{this.deleteJoinedUser(i.userId)})}startUpload(){this._timeoutId===-1&&this.uploadInterval()}addJoinedUser(i){this._localJoinedUser.set(i.userId,i),this.startUpload()}deleteJoinedUser(i){this._localJoinedUser.delete(i)}uploadInterval(){this.upload().catch(()=>{}),this._timeoutId=window.setTimeout(()=>this.uploadInterval(),5e3)}getLogsToUpload(){const i={map:new Map,splicedQueue:[]};if(this._queue[0].forAllJoinedClients&&this._localJoinedUser.size===0)return i;let n=0;for(;n{i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})});else if(rh(c.userId)&&Lv(c.sdkAppId)){const{userId:I,sdkAppId:C}=c;i.map.has(I)?i.map.get(I).logs.push(c):i.map.set(I,{userId:I,sdkAppId:C,logs:[c]})}}return i.map.size>0&&(i.splicedQueue=this._queue.splice(0,n)),i}async upload(){if(this._queue.length===0||!this._isEnableUploadLog)return;const{map:i,splicedQueue:n}=this.getLogsToUpload();if(i.size===0)return;try{const I=[...i.values()];for(let C=0;ClA.log).join(` +`)},L=JSON.stringify(N),q=IW.enable?Q4(N,2002,w):L;await this.uploadLogWithRetry(q,w,q instanceof Uint8Array,L),_.forEach(lA=>lA.uploaded=!0)}}catch{}const c=n.filter(I=>!I.uploaded);c.length>0&&(this._queue=c.concat(this._queue))}uploadLogWithRetry(i,n,c,I){return m4({retryFunction:()=>b7({url:C4(n,E7.LOG),body:i,timeout:5e3,priority:"low"}).then(C=>{c&&C.data!=="ok"&&(IW.handleUploadFailed(),this.uploadLogWithRetry(I,n,!1,I))}),settings:{retries:3,timeout:2e3},onError:({retry:C})=>{C()}})()}getPrefix(i){const n=new Date;return n.setTime(d4()),`[${rlA(n)}] <${L_[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){er(L_[i])||(this._logLevel!==i&&this.info("setLogLevel",i),this._logLevel=i)}enableUploadLog(){this._isEnableUploadLog=!0}disableUploadLog(){this.warn("disableUploadLog"),this._isEnableUploadLog=!1}logChunkToString(i){if(rh(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,n,c=!0,I,C){const f={log:n.reduce((w,_)=>`${w} ${this.logChunkToString(_)}`.trim(),""),level:i,userId:I,sdkAppId:C,forAllJoinedClients:c};ms.emit(mn.LOG,{log:f}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(f)}log(i,n,c=!0,I,C){var f;if(n.unshift(this.getPrefix(i)),this.addLogToQueue(i,n,c,I,C),i{const i=16*Math.random()|0;return(t=="x"?i:3&i|8).toString(16)})},d$=YIA,VIA=class{constructor(){Be(this,"_prefix","TRTC"),Be(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){R_()&&(setInterval(this.doFlush.bind(this),2e4),Object.keys(localStorage).filter(t=>{if(t.startsWith(this._prefix))try{const i=localStorage.getItem(t);if(!i)return!1;const n=JSON.parse(i);if(n&&n.expiresInlocalStorage.removeItem(t)))}doFlush(){if(R_())try{for(const[t,i]of this._queue)localStorage.setItem(t,JSON.stringify(i))}catch(t){Wo.warn(t)}}getItem(t){if(!R_())return null;try{const i=localStorage.getItem(this.getRealKey(t));if(!i)return null;const n=JSON.parse(i);return n&&n.expiresIn>=Date.now()?n.value:null}catch(i){Wo.warn(i)}}setItem(t,i){if(R_())try{const n={expiresIn:Date.now()+ulA,value:i};this._queue.set(this.getRealKey(t),n)}catch(n){Wo.warn(n)}}deleteItem(t){if(!R_())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(i){return Wo.warn(i),!1}}clear(){if(R_())try{localStorage.clear()}catch(t){Wo.warn(t)}}},C$=new VIA,JIA={};u4(JIA,{HTTPS_API:()=>iuA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>T$,IS_GET_CAPABILITIES_SUPPORTED:()=>_$,IS_GET_SETTINGS_SUPPORTED:()=>qY,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>IuA,IS_INSERTABLE_STREAM_SUPPORTED:()=>N$,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>BuA,IS_RTC_RTP_SENDER_SUPPORTED:()=>eF,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>G$,IS_SEI_SUPPORTED:()=>uuA,IS_SPC_SUPPORTED:()=>auA,basis:()=>duA,capabilityCheck:()=>CuA,checkSystemRequirementsInternal:()=>p$,decodeSupportStatus:()=>Q$,detectH264SupportedByFakeStreaming:()=>m$,detectVideoCodecCapabilities:()=>QuA,detectVideoDecoderCapabilities:()=>O$,detectVideoEncoderCapabilities:()=>F$,encodeSupportStatus:()=>F4,getBrowserInfo:()=>zIA,getDisplayResolution:()=>f$,getH264ProfileLevelIds:()=>P$,isAddTransceiverSupported:()=>LV,isBrowserSupported:()=>k4,isCanvasCaptureStreamAPISupported:()=>S$,isCanvasSmallStreamSupported:()=>M$,isGetReceiversSupported:()=>nuA,isGetSendersSupported:()=>w$,isGetTransceiversSupported:()=>ruA,isGetUserMediaSupported:()=>y$,isMediaDevicesSupported:()=>U4,isMediaSessionSupported:()=>k$,isMediaStreamTrackGeneratorSupported:()=>XIA,isMediaStreamTrackProcessorSupported:()=>ZIA,isReplaceTrackSupported:()=>cuA,isRequestVideoFrameCallbackSupported:()=>x4,isSIMDSupported:()=>EuA,isScaleResolutionDownBySupported:()=>v$,isScreenCaptureApiAvailable:()=>O4,isSelectedCandidatePair:()=>ouA,isSetParametersSupported:()=>luA,isSetSinkIdSupported:()=>euA,isSmallStreamSupported:()=>R$,isStopTransceiverSupported:()=>guA,isTRTCSupported:()=>AuA,isUnifiedPlanDefault:()=>suA,isUsedInHttpProtocol:()=>kV,isWebAudioSupported:()=>D$,isWebCodecSupported:()=>b$,isWebCodecsSupported:()=>L4,isWebRTCSupported:()=>P4,isWebTransportSupported:()=>L$});var JY={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},J_={AVOID_REPEATED_CALL:t=>`previous ${t.name}() is ongoing, please avoid repeated calls.`,INVALID_PARAMETER_REQUIRED:({key:t,rule:i,fnName:n,value:c})=>`'${t||i.name}' is a required param when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_TYPE({key:t,rule:i,fnName:n,value:c}){const I=`${t||i.name}`;let C="";return C=Array.isArray(i.type)?i.type.join("|"):i.type,`'${I}' must be type of ${C} when calling ${n}(), received type: ${kv(c)}.`},INVALID_PARAMETER_EMPTY:({key:t,rule:i,fnName:n,value:c})=>`'${t||i.name}' cannot be '${c}' when calling ${n}().`,INVALID_PARAMETER_INSTANCE:({key:t,rule:i,fnName:n,value:c})=>`'${`${t||i.name}`}' must be instanceof ${`${i.instanceOf.name||i.instanceOf}`} when calling ${n}(), received type: ${kv(c)}.`,INVALID_PARAMETER_RANGE:({key:t,rule:i,fnName:n,value:c})=>`'${t||i.name}' must be one of ${i.values.join("|")} when calling ${n}(), received: ${c}.`,INVALID_PARAMETER_MIN:({key:t,rule:i,fnName:n,value:c})=>`the min value of ${t||i.name} is ${i.min}, received: ${c}.`,INVALID_PARAMETER_MAX:({key:t,rule:i,fnName:n,value:c})=>`the max value of ${t||i.name} is ${i.max}, received: ${c}.`,API_CALL_TIMEOUT:t=>`${t.commandDesc||t.command} timeout observed.`,SIGNAL_CHANNEL_RECONNECTION_FAILED:"signal channel reconnection failed, please check your network.",SIGNAL_CHANNEL_SETUP_FAILED:t=>`SignalChannel setup failure: (errorCode: ${t.errorCode}, errorMsg: ${t.errorMsg} }).`,ERROR_MESSAGE(t){let i=`${t.type} failed`;return t.message&&(i=`${i}: ${t.message}.`),i},EXCHANGE_SDP_TIMEOUT:"exchange sdp timeout.",DOWNLINK_RECONNECTION_FAILED:"downlink reconnection failed, please check your network and re-join room.",EXCHANGE_SDP_FAILED:t=>`exchange sdp failed ${t.errMsg}.`,UPDATE_OFFER_TIMEOUT:"update offer timeout observed.",UPLINK_RECONNECTION_FAILED:"uplink reconnection failed, please check your network and publish again.",INVALID_RECORDID:"recordId must be an integer number.",INVALID_PURE_AUDIO:"pureAudioPushMode must be 1 or 2.",INVALID_STREAMID:"streamId must be a sting literal within 64 bytes, and not be empty.",INVALID_USER_DEFINE_RECORDID:"userDefineRecordId must be a sting literal contains (a-zA-Z),(0-9), underline and hyphen, within 64 bytes, and not be empty.",INVALID_USER_DEFINE_PUSH_ARGS:"userDefinePushArgs must be a sting literal within 256 bytes, and not be empty.",INVALID_PROXY:'proxy server url must start with "wss://".',INVALID_JOIN:"duplicate join() called.",INVALID_ROOMID_STRING:t=>`'${t}' must be validate string when useStringRoomId is true.`,INVALID_ROOMID_INTEGER:t=>`'${t}' must be an integer between [1, 4294967294] when useStringRoomId is false.`,INVALID_SIGNAL_CHANNEL:"SignalChannel is not ready yet.",JOIN_ROOM_TIMEOUT:"join room timeout.",JOIN_ROOM_FAILED:({error:t,code:i})=>`Failed to join room - ${t} code: ${i}`,REJOIN_ROOM_FAILED:t=>`reJoin room: ${t.roomId} failed, please check your network.`,INVALID_DESTROY:"please call leave() before destroy().",INVALID_PUBLISH:"please call join() before publish().",INVALID_UNPUBLISH:"stream has not been published yet.",INVALID_AUDIENCE:'no permission to publish() under live/audience, please call switchRole("anchor") firstly before publish().',INVALID_INITIALIZE:"cannot publish stream because stream is not initialized, is switching device, or has been closed.",INVALID_DUPLICATE_PUBLISHING:t=>`duplicate ${t} stream publishing, please unpublish your prev ${t} stream and then re-publish.`,INVALID_SUBSCRIBE_UNDEFINED:"stream is undefined or null.",INVALID_SUBSCRIBE_LOCAL:"stream cannot be LocalStream.",INVALID_REMOTE_STREAM:"remoteStream does not exist because it has been unpublished by remote peer.",SUBSCRIBE_FAILED:({message:t,userId:i,streamType:n})=>`failed to subscribe ${i} ${n} stream, reason: ${t}.`,INVALID_ROLE:"switchRole can only be called in live mode.",INVALID_PARAMETER_SWITCH_ROLE:"role could only be set to a value as anchor or audience.",INVALID_OPERATION_SWITCH_ROLE:"please call join() before switchRole().",SWITCH_ROLE_TIMEOUT:"switchRole timeout.",SWITCH_ROLE_FAILED:t=>`switchRole failed, errCode: ${t.code} errMsg: ${t.message}.`,CLIENT_BANNED:t=>`client was banned because of ${t.message}.`,INVALID_OPERATION_START_PUBLISH_CDN:"please call startPublishCDNStream() after join room and publish the local stream.",INVALID_OPERATION_STOP_PUBLISH_CDN:"please call startPublishCDNStream() before stopPublishCDNStream().",START_PUBLISH_CDN_FAILED:t=>`startPublishCDNStream failed, errMsg: ${t.message}.`,STOP_PUBLISH_CDN_FAILED:t=>`stopPublishCDNStream failed, errMsg: ${t.message}.`,INVALID_STREAM_ID:t=>`'${t}' can only consist of uppercase and lowercase english letters (a-zA-Z), numbers (0-9), hyphens and underscores.`,START_MIX_TRANSCODE:"please call startMixTranscode() after join().",STOP_MIX_TRANSCODE:"please call stopMixTranscode() after startMixTranscode().",INVALID_AUDIO_VOLUME:"interval must be a number.",ENABLE_SMALL_STREAM_PUBLISHED:"Cannot enable small stream after localStream published.",DISABLE_SMALL_STREAM_PUBLISHED:"Cannot disable small stream after localStream published.",NOT_SUPPORTED_SMALL_STREAM:"your browser does not support opening small stream.",INVALID_SMALL_STREAM_PROFILE:"small stream profile is invalid.",INVALID_PARAMETER_REMOTE_STREAM:"remoteStream is invalid.",INVALID_OPERATION_CHANGE_SMALL:"cannot switch to the small stream without subscribing to the video of remoteStream.",REMOTE_NOT_PUBLISH_SMALL_STREAM:"remote peer does not publish small stream.",INVALID_SWITCH_DEVICE:"cannot switch device on current stream.",INVALID_SWITCH_DEVICE_PUBLISHING:"cannot switch device when publishing localStream.",INVALID_REPLACE_TRACK:"cannot replace track when publishing localStream.",INVALID_INITIALIZE_LOCAL_STREAM:"local stream has not initialized yet.",INVALID_ADD_TRACK_REPETITIVE:"previous addTrack is ongoing, please avoid repetitive execution.",INVALID_ADD_TRACK_REMOVING:"cannot add track when a track is removing.",INVALID_ADD_TRACK_PUBLISHING:"cannot add track when publishing localStream.",INVALID_STREAM_INITIALIZED:"your local stream haven't been initialized yet.",INVALID_ADD_TRACK_NUMBER:"a Stream has at most one audio track and one video track.",INVALID_REMOVE_AUDIO_TRACK:"remove audio track is not supported on your browser.",INVALID_REMOVE_AUDIO_ADDING:"cannot remove track when a track is adding.",INVALID_REMOVE_AUDIO_ON:"previous removeTrack is ongoing, please avoid repetitive execution.",INVALID_REMOVE_TRACK_PUBLISHING:"cannot remove track when publishing localStream.",INVALID_REMOVE_TRACK_NOT_TRACK:"localStream has not this track.",INVALID_REMOVE_TRACK_NUMBER:"remove the only video track is not supported, please use replaceTrack or muteVideo.",INVALID_REPLACE_TRACK_NO_TRACK:t=>`cannot replace ${t.kind} track because stream has not ${t.kind} track`,NOT_BUG_PACKAGE:"You need to buy packages, refer to tencent console.",START_MIX_TRANSCODE_FAILED:t=>`startMixTranscode failed, errMsg: ${t.message}.`,STOP_MIX_TRANSCODE_FAILED:t=>`stopMixTranscode failed, errMsg: ${t.message}.`,MIX_TRANSCODE_NOT_STARTED:"mixTranscode has not been started.",CANNOT_LESS_THAN_ZERO:({key:t,rule:i,fnName:n,value:c})=>`'${t||i.name}' cannot be less than 0 when calling ${n}().`,MIX_PARAMS_VIDEO_FRAMERATE:"'config.videoFramerate' should be an integer between 0 and 30, excluding 0.",MIX_PARAMS_VIDEO_GOP:"'config.videoGOP' should be an integer between 1 and 8.",MIX_PARAMS_AUDIO_BITRATE:"'config.audioBitrate' should be an integer between 32 and 192.",MIX_PARAMS_USER_Z_ORDER:t=>`'${t}' is required and must be between 1 and 15.`,MIX_PARAMS_NOT_SELF:"'config.mixUsers' must contain self.",MIX_PARAMS_USER_STREAM:"'config.videoWidth' and 'config.videoHeight' of output stream should be contain all mix stream.",INVALID_PLAY:"duplicate play() call observed, please stop() firstly.",INVALID_ELEMENT_ID:({key:t,fnName:i})=>`'${t}' is not found in the document object when calling ${i}().`,INVALID_ELEMENT_ID_TYPE:({key:t,fnName:i,type:n})=>`the element corresponding to '${t}' must be instanceof HTMLElement when calling ${i}(), received: ${n}.`,PLAY_FAILED:t=>`${t.media} play failed, browser exception: ${t.error.toString()}`,INVALID_USERID:"userId cannot be all spaces.",INVALID_CREATE_STREAM_SOURCE:"LocalStream must be created by createStream() with either audio/video or audioSource/videoSource, but can not be mixed with audio/video and audioSource/videoSource.",INVALID_CREATE_STREAM_SCREEN:"screen/video cannot be both true.",INVALID_CREATE_STREAM_AUDIO:"audio/screenAudio cannot be both true.",INVALID_CREATE_STREAM_SCREEN_AUDIO:"when screen is true, screenAudio can be configured.",NOT_SUPPORTED_HTTP:"http protocol does not support the ability to capture microphone, camera and screen. please use https to deploy your page.",NOT_SUPPORTED_WEBRTC:"your browser or environment does not support full WebRTC capabilities.",NOT_SUPPORTED_PROFILE:"your browser does not support setVideoProfile.",NOT_SUPPORTED_MEDIA:"your browser or environment does not support navigator.mediaDevices.",NOT_SUPPORTED_H264ENCODE:"your device does not support H.264 encoding.",NOT_SUPPORTED_H264DECODE:"your device does not support H.264 decoding.",NOT_SUPPORTED_TRACK:t=>`${t}Track is not supported on your browser.`,NOT_SUPPORTED_SWITCH_DEVICE:"switchDevice is not supported on your browser.",NOT_SUPPORTED_CAPTURE:"Your browser or environment does not support screen sharing, please check whether the browser version.",MICROPHONE_NOT_FOUND:"no microphone detected, please check your microphone.",CAMERA_NOT_FOUND:"no camera detected, please check your camera.",SIGNAL_RESPONSE_FAILED:t=>`${t.signalResponse} failed, response code is ${t.code} , errMsg: ${t.message}.`,CATCH_HANDLER_ERROR:({name:t,event:i})=>`an error was caught in ${t}.on('${i}', handler), please check your code in 'handler'.`,API_NOT_EXIST:({name:t})=>`experimental api ${t} does not exist.`,REPEAT_JOIN:t=>"please avoid repeated join.",CONNECTION_CLOSED:"remoteStream has been unsubscribed or unpublished by remote user.",SUBSCRIBE_ALL_FALSE:"cannot subscribe when both audio & video are false, use client.unsubscribe() instead",CLIENT_DESTROYED:({funName:t})=>`failed to call ${t}() because client was destroyed.`,SEI_NOT_SUPPORT:t=>"not support to sendSEIMessage"+(t===!1?" without using h264 codec":""),SEI_DISABLED:"SEI is disabled",SEI_BEFORE_PUBLISH:"please call sendSEIMessage() after publish() success",SEI_NOT_VIDEO:"cannot send sei when localStream has not video.",CALL_FREQUENCY_LIMIT:({isSize:t,name:i,timesInSecond:n,maxSizeInSecond:c})=>`api ${i} call ${t?"size":"times"} is over ${t?`${c} bytes`:n} in a second.`,CONNECTION_ABORTED:t=>`connection aborted due to: ${t}`,API_CALL_ABORTED(t){let i;return i=t.message.includes("REMOTE_STREAM_NOT_EXIST")?`Subscribe ${t.userId} ${t.streamType} stream aborted, reason: remote user ${t.userId} unpublished stream.`:`API aborted, reason: ${t.message}`,i},DUPLICATE_AUX:"only one auxiliary stream can be published in a room.",NOT_SUPPORTED_AUX:"publish auxiliary stream is not supported on your browser.",INVALID_PARAMETER_STREAMTYPE:t=>`'streamType' is required when 'userId' is not '*', calling ${t}()`,SWITCH_PLAYBACK_QUALITY_TIMEOUT:t=>`switchPlaybackQuality timeout: waiting for first frame of user ${t.userId}.`},JZ=(t,i)=>i?`${iW}/${t}/${i}`:`${iW}/${t}/index.html`,HIA=()=>{if(window.TRTC_ERROR_INFO&&window.TRTC_ERROR_LINK)return{TRTC_ERROR_INFO:window.TRTC_ERROR_INFO,TRTC_ERROR_LINK:window.TRTC_ERROR_LINK};let t=localStorage==null?void 0:localStorage.getItem(IlA);if(t){t=JSON.parse(t);const i=document.createElement("script");i.type="text/javascript",i.text=t.message,document.body.appendChild(i);const n=window.TRTC_ERROR_INFO,c=window.TRTC_ERROR_LINK;return document.body.removeChild(i),{TRTC_ERROR_INFO:n,TRTC_ERROR_LINK:c}}return{}};function HY(t){const{key:i,data:n,link:c,addDocLink:I=!0}=t;let C="",f="",w="";Dv(J_[i])?C=J_[i](n):rh(J_[i])&&(C=J_[i]);const{TRTC_ERROR_INFO:_,TRTC_ERROR_LINK:N}=HIA();c?w=`${c.className}.html#${c.fnName}`:N&&N[i]&&(Dv(N[i])?w=N[i](n):rh(N[i])&&(w=N[i]));let L=C;return Zy()&&(_&&_[i]&&(Dv(_[i])?f=_[i](n):rh(_[i])&&(f=_[i])),f&&(L=I?`${f} +请查看文档: ${JZ("zh-cn",w)} `:`${f} -`,U+=h)),I&&(U+=` -Refer to: ${mZ("en",w)} -`),U}var fZ=dT(ycA()),CIA=1,hIA=0,j7=class{constructor(t=!0){de(this,"countMap",new Map),de(this,"distributionMap",new Map),de(this,"version"),de(this,"log",Wo.createLogger({id:"kv"})),t&&(ps.on("102",({track:i,cost:r})=>{this.addSuccessEvent({key:i.kind===$t.AUDIO?501700:511700,cost:r})}),ps.on("103",({track:i,error:r})=>{this.addFailedEvent({key:i.kind===$t.AUDIO?501700:511700,error:r})}),ps.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,i){const r={msg_sdk_basic_info:{uint32_sdk_version:o7(this.version||SY),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([l,I])=>({uint32_key:l,uint32_count:I})),stats_distribution:[...this.distributionMap.entries()].map(([l,I])=>({uint32_key:l,distribution_items:[...I.entries()].map(([h,f])=>({uint32_item_key:h,uint32_item_value:f}))})),str_user_sig:t,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),r}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){const i=+String(t).slice(-3);return i>=700&&i<799}isErrorCodeKey(t){const i=+String(t).slice(-3);return i>=600&&i<699}isCountKey(t){const i=+String(t).slice(-3);return i>=0&&i<599}isNumberKey(t){const i=+String(t).slice(-3);return i>=800&&i<899}addCount({key:t,useUV:i=!1}){this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug(`${t} is not count key, last 3 number should be 0~599`)}addEnum({key:t,value:i,useUV:r=!0}){var l;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(r&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);const I=((l=this.distributionMap)==null?void 0:l.get(t))||new Map;I.set(i,(I.get(i)||0)+1),this.distributionMap.set(t,I)}addNumber({key:t,value:i,split:r=100,useUV:l=!1,max:I=5e3}){var h;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(l&&this.countMap.has(t))return;i>I&&(i=I),this.countMap.set(t,(this.countMap.get(t)||0)+1);const f=((h=this.distributionMap)==null?void 0:h.get(t))||new Map;let w=0;if(Gv(r))w=Math.floor(i/r);else for(let _=r.length-1;_>0;_--)if(i>r[_]){w=_;break}f.set(w,(f.get(w)||0)+1),this.distributionMap.set(t,f)}addSuccessEvent({key:t,cost:i,timeKey:r,split:l}){if(t&&(this.addEnum({key:t,value:CIA,useUV:!1}),i)){const I=+String(t).slice(-3);I<800&&I>=700?this.addNumber({key:r||t+100,value:i,split:l}):r||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:i}){if(!t)return;let r=qg.UNKNOWN;i&&(Gv(i)?r=i:$n(i.extraCode)&&$n(i.code)||(r=i.extraCode||i.code)),this.addEnum({key:t,value:hIA,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},W7=(t=>(t[t.DECODER_TYPE=514700]="DECODER_TYPE",t[t.DECODER_HW_SW=514701]="DECODER_HW_SW",t[t.DECODE_RESULT=514702]="DECODE_RESULT",t[t.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",t[t.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",t[t.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",t[t.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",t[t.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",t[t.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",t[t.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",t[t.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",t[t.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",t[t.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",t[t.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",t[t.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",t[t.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",t[t.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",t[t.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",t[t.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",t))(W7||{}),BIA=new j7(!0);new j7(!1);var Ir=BIA,Xs={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},QIA=new Map([[sC,["Firefox",d7]],[CV,["Edg",B7]],[I4,["Chrome",U7]],[ld,["Safari",JU]],[Bm,["TBS",m7]],[CT,["XWEB",f7]],[VU&&dV,["WeChat",y7]],[o4,["QQ(Win)",D7]],[BV,["QQ(Mobile)",wY]],[hV,["QQ(Mobile X5)",wY]],[s4,["QQ(Mac)",S7]],[n4,["QQ(iPad)",M7]],[r4,["MI",_7]],[a4,["HW",N7]],[g4,["Samsung",G7]],[pV,["OPPO",b7]],[c4,["VIVO",k7]],[YU,["EDGE",h7]],[t4,["SogouMobile",Q7]],[i4,["Sogou",p7]]]);function pIA(){const t=QIA.get(!0);return{browserName:t?t[0]:"unknown",browserVersion:t?t[1]:"unknown"}}var E4=function(){return!KlA&&!YU&&!(CV&&HlA<80)&&!(sC&&C7<56)},d4=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},C4=function(){if(!navigator.mediaDevices)return mV()||Wo.error(x_.NOT_SUPPORTED_MEDIA),!1;const t=["getUserMedia","enumerateDevices"];return t.filter(i=>i in navigator.mediaDevices).length===t.length},yZ=!1;function mV(){return location.protocol==="http:"&&!TY&&(yZ||Wo.error(GY({key:NY.NOT_SUPPORTED_HTTP})),yZ=!0,!0)}var mIA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},fIA=function(){return!!window?.MediaStreamTrackGenerator},h4=async function(){var t,i,r;if(Xs.detail.isH264EncodeSupported&&Xs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Xs.detail.isH264EncodeSupported,isVp8EncodeSupported:Xs.detail.isVp8EncodeSupported,isH265EncodeSupported:Xs.detail.isH265EncodeSupported};let l,I=!1,h=!1,f=!1;try{const w=new RTCPeerConnection,_=document.createElement($t.CANVAS);_.getContext("2d");const G=_.captureStream(0);return w.addTrack(G.getVideoTracks()[0],G),l=await w.createOffer(),I=((t=l.sdp)==null?void 0:t.toLowerCase().indexOf("h264"))!==-1,h=((i=l.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,f=((r=l.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1,w.close(),{isH264EncodeSupported:I,isVp8EncodeSupported:h,isH265EncodeSupported:f}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},z7=async function(){var t;if(Xs.detail.isH264DecodeSupported&&Xs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Xs.detail.isH264DecodeSupported,isVp8DecodeSupported:Xs.detail.isVp8DecodeSupported,isH265DecodeSupported:Xs.detail.isH265DecodeSupported};let i,r=!1,l=!1;try{const I=new RTCPeerConnection;fV()?(I.addTransceiver($t.VIDEO,{direction:"recvonly"}),i=await I.createOffer()):i=await I.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(r=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(l=!0);const h=((t=i.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return I.close(),{isH264DecodeSupported:r,isVp8DecodeSupported:l,isH265DecodeSupported:h}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function yIA(){const[t,i]=await Promise.all([h4(),z7()]);return{encode:{h264:t.isH264EncodeSupported,vp8:t.isVp8EncodeSupported,h265:t.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var Z7=n7(async t=>{const i=Date.now(),r=Q4(),l=C4(),I=d4();if(Xs.detail.isWebRTCSupported=r,Xs.detail.isMediaDevicesSupported=l,Xs.detail.isWebCodecsSupported=I,Xs.detail.isScreenShareSupported=B4(),Xs.detail.isSmallStreamSupported=s$(),t===37)return Object.assign(Xs.detail,await MIA()),Xs.detail.isBrowserSupported=I,Xs.result=l&&I,Xs.result||Wo.error(`${navigator.userAgent} ${j3(Xs.detail,!1)}`),MZ(t),Ir.addNumber({key:523800,value:Date.now()-i}),Xs;if(Xs.result&&Xs.detail.isH264EncodeSupported&&Xs.detail.isVp8EncodeSupported&&Xs.detail.isH265EncodeSupported&&Xs.detail.isH264DecodeSupported&&Xs.detail.isVp8DecodeSupported&&Xs.detail.isH265DecodeSupported)return Xs;const h=E4(),{encode:f,decode:w}=await yIA();let{h264:_,vp8:G}=f,{h264:U}=w;const{h265:j}=f,{vp8:lA,h265:sA}=w;if(!_||!G){const mA=await h4();Wo.warn(`detect encode again h264:${_} vp8:${G} result: ${JSON.stringify(mA)}`),_=mA.isH264EncodeSupported,G=mA.isVp8EncodeSupported}if(_&&U&&aC&&tD&&!CT&&!Bm&&(!pV||iD!==115)){const{encode:mA,decode:IA}=await X7();_=mA,U=IA}return Xs.result=h&&r&&l&&(_||G)&&(U||lA),Xs.detail.isBrowserSupported=h,Xs.detail.isWebRTCSupported=r,Xs.detail.isH264EncodeSupported=_,Xs.detail.isVp8EncodeSupported=G,Xs.detail.isH265EncodeSupported=j,Xs.detail.isH264DecodeSupported=U,Xs.detail.isVp8DecodeSupported=lA,Xs.detail.isH265DecodeSupported=sA,Xs.result||Wo.error(`${navigator.userAgent} ${j3(Xs.detail,!1)}`),MZ(),Ir.addNumber({key:523800,value:Date.now()-i}),Xs}),DIA=function(){return Xs.result},B4=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},SIA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,DZ=null;async function X7(t=2e3){return DZ||(DZ=new Promise(async i=>{const r={encode:!1,decode:!1};let l=()=>{};try{const I=document.createElement("canvas"),h=I.getContext("2d");I.width=640,I.height=480;const f=setInterval(()=>{h.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let w=-1,_=-1;l=()=>{clearInterval(w),clearInterval(f),clearTimeout(_),U.close(),j.close(),G.getTracks().forEach(cA=>cA.stop())},_=setTimeout(()=>{l(),i(r)},t);const G=I.captureStream(),U=new RTCPeerConnection({}),j=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});U.addEventListener("icecandidate",cA=>j.addIceCandidate(cA.candidate)),j.addEventListener("icecandidate",cA=>U.addIceCandidate(cA.candidate)),U.addTrack(G.getVideoTracks()[0],G);const lA=await U.createOffer();await U.setLocalDescription(lA),await j.setRemoteDescription(lA);const sA=await j.createAnswer(),mA=fZ.default.parse(sA.sdp),IA=mA.media[0].rtp.findIndex(cA=>cA.codec==="H264");mA.media[0].rtp=[mA.media[0].rtp[IA]],mA.media[0].fmtp=mA.media[0].fmtp.filter(cA=>cA.payload===mA.media[0].rtp[0].payload),mA.media[0].rtcpFb&&(mA.media[0].rtcpFb=mA.media[0].rtcpFb.filter(cA=>cA.payload===mA.media[0].rtp[0].payload)),sA.sdp=fZ.default.write(mA),await j.setLocalDescription(sA),await U.setRemoteDescription(sA),w=setInterval(async()=>{r.encode&&r.decode&&(l(),i(r));const[cA,TA]=await Promise.all([U.getSenders()[0].getStats(),j.getReceivers()[0].getStats()]);r.encode||cA.forEach(WA=>{WA.type==="outbound-rtp"&&(WA.mediaType===$t.VIDEO||WA.kind===$t.VIDEO)&&WA.bytesSent>0&&(r.encode=!0)}),r.decode||TA.forEach(WA=>{WA.type==="inbound-rtp"&&(WA.mediaType===$t.VIDEO||WA.kind===$t.VIDEO)&&WA.bytesReceived>0&&(r.decode=!0)})},100)}catch(I){l(),Wo.warn("detectH264Supported failed",I),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||Wo.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${tIA}`),i)))}var SZ=null;async function MIA(){return SZ||(SZ=new Promise(async t=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!d4())return void t(i);let r=null,l=null,I=null;const h=()=>{I&&clearTimeout(I),r=null,l=null};try{r=document.createElement("canvas"),l=r.getContext("2d"),r.width=320,r.height=240;let f=0;const w=()=>{l&&r&&(l.fillStyle=`hsl(${f%360}, 50%, 50%)`,l.fillRect(0,0,r.width,r.height),l.fillStyle="white",l.font="20px Arial",l.fillText(`Frame ${f}`,10,30),f++)};I=setTimeout(()=>{h(),t(i)},5e3);const _=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(await Promise.all(_.map(async G=>{const U={type:G.type,encodeSupported:!1,decodeSupported:!1};let j;try{j=await new Promise(async(lA,sA)=>{try{const mA=new VideoEncoder({output:cA=>{lA(cA),U.encodeSupported=!0},error:sA});mA.configure(G.encodeConfig),w();const IA=new VideoFrame(r,{timestamp:0});mA.encode(IA,{keyFrame:!0}),IA.close(),await mA.flush(),mA.close()}catch(mA){sA(mA)}})}catch(lA){return Wo.warn(`${G.type} encoder error:`,lA),U}try{await new Promise(async(lA,sA)=>{try{const mA=new VideoDecoder({output:IA=>{U.decodeSupported=!0,lA(0),IA.close()},error:sA});mA.configure(G.decodeConfig),mA.decode(j),await mA.flush(),mA.close()}catch(mA){sA(mA)}})}catch(lA){Wo.warn(`${G.type} decoder error:`,lA)}return U}))).forEach(G=>{G.type==="h264"?(i.isH264EncodeSupported=G.encodeSupported,i.isH264DecodeSupported=G.decodeSupported):G.type==="vp8"&&(i.isVp8EncodeSupported=G.encodeSupported,i.isVp8DecodeSupported=G.decodeSupported)}),h(),t(i)}catch(f){h(),Wo.warn("detectWebCodecsSupported failed:",f),t(i)}}))}var vIA=(t,i,r)=>{location.protocol!=="http:"||TY||(t[i]=()=>{throw new ml({code:qg.INVALID_OPERATION,message:x_.NOT_SUPPORTED_HTTP})})},RIA=function(t){return!(t.type!=="candidate-pair"||!t.nominated||t.state!=="in-progress"&&t.state!=="succeeded")&&!(fv(t.selected)&&!t.selected)};function $7(){let t="";return screen.width&&(t+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),t}function A$(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function e$(){const t={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r=86,c$="RTCRtpScriptTransform"in window,UIA=HU&&(g$||c$),Q4=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function l$(){const t={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return $n(window.AudioDecoder)||(t.AudioDecoder=!0),$n(window.AudioEncoder)||(t.AudioEncoder=!0),$n(window.VideoDecoder)||(t.VideoDecoder=!0),$n(window.VideoEncoder)||(t.VideoEncoder=!0),$n(window.ImageDecoder)||(t.ImageDecoder=!0),t}function I$(){return"mediaSession"in navigator&&!$n(navigator.mediaSession.setActionHandler)}function u$(){return!$n(window.WebTransport)}function FIA(){return typeof WebAssembly<"u"&&WebAssembly.validate(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 OIA(){const t={browser:`${yv.name}/${yv.version}`,os:x7(),displayResolution:$7(),isScreenShareSupported:B4(),isWebRTCSupported:Q4(),isGetUserMediaSupported:A$(),isWebAudioSupported:e$(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:l$(),isMediaSessionSupported:I$(),isWebTransportSupported:u$()};return navigator.userAgent.includes("miniProgram")&&(t.browser=`mini/${t.browser}`),t}var E$="checkResult";function MZ(t=30){K7.setItem(E$+t,{ua:navigator.userAgent,checkResult:Xs})}function PIA(t){mV();const i=K7.getItem(E$+t);i&&i.ua===navigator.userAgent&&i.checkResult&&xIA(i.checkResult.detail,Xs.detail)&&(Xs=i.checkResult),Z7(t)}function xIA(t,i){return!!Cv(t)&&Object.keys(i).every(r=>r in t)}function p4(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var YIA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function vZ(t){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[t]}var RZ=!1;async function VIA(){var t;try{if(RZ||!((t=navigator?.mediaCapabilities)!=null&&t.encodingInfo))return;const i=u4(),r=oIA();if(i===0||r===0)return;RZ=!0;const l=["H264","VP8","VP9","AV1","H265"],[I,h]=await Promise.all([d$(l),C$(l)]);I&&Object.keys(I).forEach(_=>{const G=vZ(_.toLowerCase());Ir.addEnum({key:513707,value:+`${G}${+I[_].supported}${+I[_].powerEfficient}${i}${r}`,useUV:!1})}),h&&Object.keys(h).forEach(_=>{const G=vZ(_.toLowerCase());Ir.addEnum({key:514713,value:+`${G}${+h[_].supported}${+h[_].powerEfficient}${i}${r}`,useUV:!1})});const{sender:f,receiver:w}=h$();Ir.addEnum({key:513708,value:+`${i}${r}${+f.high}`,useUV:!1}),Ir.addEnum({key:513709,value:+`${i}${r}${+f.main}`,useUV:!1}),Ir.addEnum({key:514714,value:+`${i}${r}${+w.high}`,useUV:!1}),Ir.addEnum({key:514715,value:+`${i}${r}${+w.main}`,useUV:!1})}catch(i){Wo.info("detectVideoCodecCapabilities failed",i)}}async function d$(t,i=1920,r=1080,l=30,I=3e3){const h={};try{for(const f of t){const w=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${f}`,width:i,height:r,bitrate:I,framerate:l}});h[f]=w}}catch{}return h}async function C$(t,i=1920,r=1080,l=30,I=3e3){const h={};try{for(const f of t){const w=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${f}`,width:i,height:r,bitrate:I,framerate:l}});h[f]=w}}catch{}return h}function h$(){const t={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){const i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const l=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(l&&l[1])switch(l[1].slice(0,2)){case"42":t.sender.base=!0;break;case"4d":t.sender.main=!0;break;case"64":t.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(r=>r.mimeType.toLowerCase()==="video/h264").forEach(r=>{if(r.sdpFmtpLine){const l=r.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(l&&l[1])switch(l[1].slice(0,2)){case"42":t.receiver.base=!0;break;case"4d":t.receiver.main=!0;break;case"64":t.receiver.high=!0}}})}}catch(i){Wo.warn("get H264 profile levelId failed",i)}return t}var JIA=dT(PU()),wZ=Symbol("instance"),P1=Symbol("cacheResult"),Xj=class{constructor(t,i,r){this.oldState=t,this.newState=i,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,nU.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},$j=class extends Error{constructor(t,i,r){super(i),this.state=t,this.message=i,this.cause=r}};function HIA(t){return typeof t=="object"&&t&&"then"in t}var sU=new Map;function Du(t,i,r={}){return(l,I,h)=>{const f=r.action||I;if(!r.context){const _=sU.get(l)||[];sU.has(l)||sU.set(l,_),_.push({from:t,to:i,action:f})}const w=h.value;h.value=function(..._){let G=this;if(r.context&&(G=Xn.get(typeof r.context=="function"?r.context.call(this,..._):r.context)),G.state===i)return r.sync?G[P1]:Promise.resolve(G[P1]);G.state instanceof Xj&&G.state.action==r.abortAction&&G.state.abort(G);let U=null;Array.isArray(t)?t.length==0?G.state instanceof Xj&&G.state.abort(G):typeof G.state=="string"&&t.includes(G.state)||(U=new $j(G._state,`${G.name} ${f} to ${i} failed: current state ${G._state} not from ${t.join("|")}`)):t!==G.state&&(U=new $j(G._state,`${G.name} ${f} to ${i} failed: current state ${G._state} not from ${t}`));const j=cA=>{if(r.fail&&r.fail.call(this,cA),r.sync){if(r.ignoreError)return cA;throw cA}return r.ignoreError?Promise.resolve(cA):Promise.reject(cA)};if(U)return j(U);const lA=G.state,sA=new Xj(lA,i,f);nU.call(G,sA);const mA=cA=>{var TA;return G[P1]=cA,sA.aborted||(nU.call(G,i),(TA=r.success)===null||TA===void 0||TA.call(this,G[P1])),cA},IA=cA=>(nU.call(G,lA,cA),j(cA));try{const cA=w.apply(this,_);return HIA(cA)?cA.then(mA).catch(IA):r.sync?mA(cA):Promise.resolve(mA(cA))}catch(cA){return IA(new $j(G._state,`${G.name} ${f} from ${t} to ${i} failed: ${cA}`,cA instanceof Error?cA:new Error(String(cA))))}}}}var qIA=typeof window<"u"&&window.__AFSM__?(r,l)=>{window.dispatchEvent(new CustomEvent(r,{detail:l}))}:typeof importScripts<"u"?(r,l)=>{postMessage({type:r,payload:l})}:()=>{};function nU(t,i){const r=this._state;this._state=t;const l=t.toString();t&&this.emit(l,r),this.emit(Xn.STATECHANGED,t,r,i),this.updateDevTools({value:t,old:r,err:i instanceof Error?i.message:String(i)})}var Xn=class WC extends JIA.default{constructor(i,r,l){super(),this.name=i,this.groupName=r,this._state=WC.INIT,i||(i=Date.now().toString(36)),l?Object.setPrototypeOf(this,l):l=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const I=l[wZ];I?this.name=I.name+"-"+I.count++:l[wZ]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=sU.get(i)||[];let l=new Set,I=[],h=[];const f=new Set,w=Object.getPrototypeOf(i);sU.has(w)&&(w.stateDiagram.forEach(G=>l.add(G)),w.allStates.forEach(G=>f.add(G))),r.forEach(({from:G,to:U,action:j})=>{typeof G=="string"?I.push({from:G,to:U,action:j}):G.length?G.forEach(lA=>{I.push({from:lA,to:U,action:j})}):h.push({to:U,action:j})}),I.forEach(({from:G,to:U,action:j})=>{f.add(G),f.add(U),f.add(j+"ing"),l.add(`${G} --> ${j}ing : ${j}`),l.add(`${j}ing --> ${U} : ${j} 🟢`),l.add(`${j}ing --> ${G} : ${j} 🔴`)}),h.forEach(({to:G,action:U})=>{l.add(`${U}ing --> ${G} : ${U} 🟢`),f.forEach(j=>{j!==G&&l.add(`${j} --> ${U}ing : ${U}`)})});const _=[...l];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:f}}),_}static get(i){let r;return typeof i=="string"?(r=WC.instances.get(i),r||WC.instances.set(i,r=new WC(i,void 0,Object.create(WC.prototype)))):(r=WC.instances2.get(i),r||WC.instances2.set(i,r=new WC(i.constructor.name,void 0,Object.create(WC.prototype)))),r}static getState(i){var r;return(r=WC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){qIA(WC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){nU.call(this,i)}};Xn.STATECHANGED="stateChanged",Xn.UPDATEAFSM="updateAFSM",Xn.INIT="[*]",Xn.ON="on",Xn.OFF="off",Xn.instances=new Map,Xn.instances2=new WeakMap;var m4=typeof window<"u",_Z=m4&&window.requestIdleCallback||function(t){const i=Date.now();return setTimeout(()=>{t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},KIA=m4&&window.cancelIdleCallback||function(t){clearTimeout(t)},TZ=m4&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),FL=class hE{static generateTaskID(){return this.currentTaskID++}static run(i,r,l){l?.fps&&(l.delay=l.delay||Number((1e3/l.fps).toFixed(2))),l=Rn(Rn({},i==="interval"?{delay:2e3,count:0,backgroundTask:!0}:i==="ric"?{delay:1e4,count:0}:i==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),l);const I=nB(Rn({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:r},l),{delay:l.delay});return this.taskMap.set(I.taskID,I),this[i](I),I.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,hE.isBreakLoop(i)},i.delay)}static intervalInWorker(i){hE.sharedWorker||(hE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` +`,L+=C)),I&&(L+=` +Refer to: ${JZ("en",w)} +`),L}var HZ=mT($cA()),qIA=1,KIA=0,h$=class{constructor(t=!0){Be(this,"countMap",new Map),Be(this,"distributionMap",new Map),Be(this,"version"),Be(this,"log",Wo.createLogger({id:"kv"})),t&&(ms.on("102",({track:i,cost:n})=>{this.addSuccessEvent({key:i.kind===ei.AUDIO?501700:511700,cost:n})}),ms.on("103",({track:i,error:n})=>{this.addFailedEvent({key:i.kind===ei.AUDIO?501700:511700,error:n})}),ms.on("266",({enable:i})=>{this.log.info((i?"enable":"disable")+" sso"),i?this.addSuccessEvent({key:525701}):this.addFailedEvent({key:525701})}))}getReportData(t,i){const n={msg_sdk_basic_info:{uint32_sdk_version:v7(this.version||UY),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([c,I])=>({uint32_key:c,uint32_count:I})),stats_distribution:[...this.distributionMap.entries()].map(([c,I])=>({uint32_key:c,distribution_items:[...I.entries()].map(([C,f])=>({uint32_item_key:C,uint32_item_value:f}))})),str_user_sig:t,bytes_report_token:i};return this.countMap.clear(),this.distributionMap.clear(),n}clear(){this.countMap.clear(),this.distributionMap.clear()}isEnumKey(t){const i=+String(t).slice(-3);return i>=700&&i<799}isErrorCodeKey(t){const i=+String(t).slice(-3);return i>=600&&i<699}isCountKey(t){const i=+String(t).slice(-3);return i>=0&&i<599}isNumberKey(t){const i=+String(t).slice(-3);return i>=800&&i<899}addCount({key:t,useUV:i=!1}){this.isCountKey(t)?i&&this.countMap.has(t)||this.countMap.set(t,(this.countMap.get(t)||0)+1):this.log.debug(`${t} is not count key, last 3 number should be 0~599`)}addEnum({key:t,value:i,useUV:n=!0}){var c;if(!this.isEnumKey(t))return this.log.debug(`${t} is not enum key, last 3 number should be 700~799`);if(n&&this.countMap.has(t))return;this.countMap.set(t,(this.countMap.get(t)||0)+1);const I=((c=this.distributionMap)==null?void 0:c.get(t))||new Map;I.set(i,(I.get(i)||0)+1),this.distributionMap.set(t,I)}addNumber({key:t,value:i,split:n=100,useUV:c=!1,max:I=5e3}){var C;if(!this.isNumberKey(t))return this.log.debug(`${t} is not number key, last 3 number should be 800~899`);if(c&&this.countMap.has(t))return;i>I&&(i=I),this.countMap.set(t,(this.countMap.get(t)||0)+1);const f=((C=this.distributionMap)==null?void 0:C.get(t))||new Map;let w=0;if(Lv(n))w=Math.floor(i/n);else for(let _=n.length-1;_>0;_--)if(i>n[_]){w=_;break}f.set(w,(f.get(w)||0)+1),this.distributionMap.set(t,f)}addSuccessEvent({key:t,cost:i,timeKey:n,split:c}){if(t&&(this.addEnum({key:t,value:qIA,useUV:!1}),i)){const I=+String(t).slice(-3);I<800&&I>=700?this.addNumber({key:n||t+100,value:i,split:c}):n||this.log.debug(`time stat ignored, ${t}`)}}addFailedEvent({key:t,error:i}){if(!t)return;let n=qg.UNKNOWN;i&&(Lv(i)?n=i:er(i.extraCode)&&er(i.code)||(n=i.extraCode||i.code)),this.addEnum({key:t,value:KIA,useUV:!1}),this.addEnum({key:t,value:Math.abs(n),useUV:!1})}},B$=(t=>(t[t.DECODER_TYPE=514700]="DECODER_TYPE",t[t.DECODER_HW_SW=514701]="DECODER_HW_SW",t[t.DECODE_RESULT=514702]="DECODE_RESULT",t[t.DECODE_FAILED_OS=514703]="DECODE_FAILED_OS",t[t.DOWNGRADE_RESULT=514704]="DOWNGRADE_RESULT",t[t.DOWNGRADE_WEBCODECS_VIDEO=514705]="DOWNGRADE_WEBCODECS_VIDEO",t[t.DOWNGRADE_WEBCODECS_2D=514706]="DOWNGRADE_WEBCODECS_2D",t[t.DOWNGRADE_WASM_WEGBL=514707]="DOWNGRADE_WASM_WEGBL",t[t.DOWNGRADE_WASM_VIDEO=514708]="DOWNGRADE_WASM_VIDEO",t[t.DOWNGRADE_WASM_2D=514709]="DOWNGRADE_WASM_2D",t[t.DECODE_H264_RESULT=514710]="DECODE_H264_RESULT",t[t.DECODE_H265_RESULT=514711]="DECODE_H265_RESULT",t[t.DECODE_VP8_RESULT=514712]="DECODE_VP8_RESULT",t[t.DECODE_CAPABILITIES=514713]="DECODE_CAPABILITIES",t[t.H264_PROFILE_LEVEL_ID_HIGH=514714]="H264_PROFILE_LEVEL_ID_HIGH",t[t.H264_PROFILE_LEVEL_ID_MAIN=514715]="H264_PROFILE_LEVEL_ID_MAIN",t[t.RENDER_FREEZE_RATE=514850]="RENDER_FREEZE_RATE",t[t.DATA_FREEZE_RATE=514851]="DATA_FREEZE_RATE",t[t.VIDEO_CONSUME_RENDER_RATE=514852]="VIDEO_CONSUME_RENDER_RATE",t))(B$||{}),jIA=new h$(!0);new h$(!1);var dr=jIA,Xs={result:!1,detail:{isBrowserSupported:!1,isWebRTCSupported:!1,isWebCodecsSupported:!1,isMediaDevicesSupported:!1,isScreenShareSupported:!1,isSmallStreamSupported:!1,isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1,isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}},WIA=new Map([[rC,["Firefox",F7]],[_V,["Edg",x7]],[G4,["Chrome",n$]],[ld,["Safari",AF]],[mm,["TBS",J7]],[fT,["XWEB",H7]],[$U&&wV,["WeChat",q7]],[S4,["QQ(Win)",K7]],[NV,["QQ(Mobile)",xY]],[TV,["QQ(Mobile X5)",xY]],[M4,["QQ(Mac)",j7]],[v4,["QQ(iPad)",W7]],[R4,["MI",$7]],[w4,["HW",e$]],[_4,["Samsung",t$]],[bV,["OPPO",i$]],[T4,["VIVO",o$]],[XU,["EDGE",P7]],[y4,["SogouMobile",Y7]],[D4,["Sogou",V7]]]);function zIA(){const t=WIA.get(!0);return{browserName:t?t[0]:"unknown",browserVersion:t?t[1]:"unknown"}}var k4=function(){return!yIA&&!XU&&!(_V&&mIA<80)&&!(rC&&O7<56)},L4=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},U4=function(){if(!navigator.mediaDevices)return kV()||Wo.error(J_.NOT_SUPPORTED_MEDIA),!1;const t=["getUserMedia","enumerateDevices"];return t.filter(i=>i in navigator.mediaDevices).length===t.length},qZ=!1;function kV(){return location.protocol==="http:"&&!VY&&(qZ||Wo.error(HY({key:JY.NOT_SUPPORTED_HTTP})),qZ=!0,!0)}var ZIA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},XIA=function(){return!!window?.MediaStreamTrackGenerator},F4=async function(){var t,i,n;if(Xs.detail.isH264EncodeSupported&&Xs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Xs.detail.isH264EncodeSupported,isVp8EncodeSupported:Xs.detail.isVp8EncodeSupported,isH265EncodeSupported:Xs.detail.isH265EncodeSupported};let c,I=!1,C=!1,f=!1;try{const w=new RTCPeerConnection,_=document.createElement(ei.CANVAS);_.getContext("2d");const N=_.captureStream(0);return w.addTrack(N.getVideoTracks()[0],N),c=await w.createOffer(),I=((t=c.sdp)==null?void 0:t.toLowerCase().indexOf("h264"))!==-1,C=((i=c.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,f=((n=c.sdp)==null?void 0:n.toLowerCase().indexOf("h265"))!==-1,w.close(),{isH264EncodeSupported:I,isVp8EncodeSupported:C,isH265EncodeSupported:f}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},Q$=async function(){var t;if(Xs.detail.isH264DecodeSupported&&Xs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Xs.detail.isH264DecodeSupported,isVp8DecodeSupported:Xs.detail.isVp8DecodeSupported,isH265DecodeSupported:Xs.detail.isH265DecodeSupported};let i,n=!1,c=!1;try{const I=new RTCPeerConnection;LV()?(I.addTransceiver(ei.VIDEO,{direction:"recvonly"}),i=await I.createOffer()):i=await I.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(n=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(c=!0);const C=((t=i.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return I.close(),{isH264DecodeSupported:n,isVp8DecodeSupported:c,isH265DecodeSupported:C}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function $IA(){const[t,i]=await Promise.all([F4(),Q$()]);return{encode:{h264:t.isH264EncodeSupported,vp8:t.isVp8EncodeSupported,h265:t.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var p$=w7(async t=>{const i=Date.now(),n=P4(),c=U4(),I=L4();if(Xs.detail.isWebRTCSupported=n,Xs.detail.isMediaDevicesSupported=c,Xs.detail.isWebCodecsSupported=I,Xs.detail.isScreenShareSupported=O4(),Xs.detail.isSmallStreamSupported=R$(),t===37)return Object.assign(Xs.detail,await tuA()),Xs.detail.isBrowserSupported=I,Xs.result=c&&I,Xs.result||Wo.error(`${navigator.userAgent} ${cW(Xs.detail,!1)}`),WZ(t),dr.addNumber({key:523800,value:Date.now()-i}),Xs;if(Xs.result&&Xs.detail.isH264EncodeSupported&&Xs.detail.isVp8EncodeSupported&&Xs.detail.isH265EncodeSupported&&Xs.detail.isH264DecodeSupported&&Xs.detail.isVp8DecodeSupported&&Xs.detail.isH265DecodeSupported)return Xs;const C=k4(),{encode:f,decode:w}=await $IA();let{h264:_,vp8:N}=f,{h264:L}=w;const{h265:q}=f,{vp8:lA,h265:tA}=w;if(!_||!N){const BA=await F4();Wo.warn(`detect encode again h264:${_} vp8:${N} result: ${JSON.stringify(BA)}`),_=BA.isH264EncodeSupported,N=BA.isVp8EncodeSupported}if(_&&L&&cC&&sD&&!fT&&!mm&&(!bV||nD!==115)){const{encode:BA,decode:IA}=await m$();_=BA,L=IA}return Xs.result=C&&n&&c&&(_||N)&&(L||lA),Xs.detail.isBrowserSupported=C,Xs.detail.isWebRTCSupported=n,Xs.detail.isH264EncodeSupported=_,Xs.detail.isVp8EncodeSupported=N,Xs.detail.isH265EncodeSupported=q,Xs.detail.isH264DecodeSupported=L,Xs.detail.isVp8DecodeSupported=lA,Xs.detail.isH265DecodeSupported=tA,Xs.result||Wo.error(`${navigator.userAgent} ${cW(Xs.detail,!1)}`),WZ(),dr.addNumber({key:523800,value:Date.now()-i}),Xs}),AuA=function(){return Xs.result},O4=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},euA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,KZ=null;async function m$(t=2e3){return KZ||(KZ=new Promise(async i=>{const n={encode:!1,decode:!1};let c=()=>{};try{const I=document.createElement("canvas"),C=I.getContext("2d");I.width=640,I.height=480;const f=setInterval(()=>{C.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let w=-1,_=-1;c=()=>{clearInterval(w),clearInterval(f),clearTimeout(_),L.close(),q.close(),N.getTracks().forEach(gA=>gA.stop())},_=setTimeout(()=>{c(),i(n)},t);const N=I.captureStream(),L=new RTCPeerConnection({}),q=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});L.addEventListener("icecandidate",gA=>q.addIceCandidate(gA.candidate)),q.addEventListener("icecandidate",gA=>L.addIceCandidate(gA.candidate)),L.addTrack(N.getVideoTracks()[0],N);const lA=await L.createOffer();await L.setLocalDescription(lA),await q.setRemoteDescription(lA);const tA=await q.createAnswer(),BA=HZ.default.parse(tA.sdp),IA=BA.media[0].rtp.findIndex(gA=>gA.codec==="H264");BA.media[0].rtp=[BA.media[0].rtp[IA]],BA.media[0].fmtp=BA.media[0].fmtp.filter(gA=>gA.payload===BA.media[0].rtp[0].payload),BA.media[0].rtcpFb&&(BA.media[0].rtcpFb=BA.media[0].rtcpFb.filter(gA=>gA.payload===BA.media[0].rtp[0].payload)),tA.sdp=HZ.default.write(BA),await q.setLocalDescription(tA),await L.setRemoteDescription(tA),w=setInterval(async()=>{n.encode&&n.decode&&(c(),i(n));const[gA,RA]=await Promise.all([L.getSenders()[0].getStats(),q.getReceivers()[0].getStats()]);n.encode||gA.forEach(HA=>{HA.type==="outbound-rtp"&&(HA.mediaType===ei.VIDEO||HA.kind===ei.VIDEO)&&HA.bytesSent>0&&(n.encode=!0)}),n.decode||RA.forEach(HA=>{HA.type==="inbound-rtp"&&(HA.mediaType===ei.VIDEO||HA.kind===ei.VIDEO)&&HA.bytesReceived>0&&(n.decode=!0)})},100)}catch(I){c(),Wo.warn("detectH264Supported failed",I),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||Wo.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${NIA}`),i)))}var jZ=null;async function tuA(){return jZ||(jZ=new Promise(async t=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!L4())return void t(i);let n=null,c=null,I=null;const C=()=>{I&&clearTimeout(I),n=null,c=null};try{n=document.createElement("canvas"),c=n.getContext("2d"),n.width=320,n.height=240;let f=0;const w=()=>{c&&n&&(c.fillStyle=`hsl(${f%360}, 50%, 50%)`,c.fillRect(0,0,n.width,n.height),c.fillStyle="white",c.font="20px Arial",c.fillText(`Frame ${f}`,10,30),f++)};I=setTimeout(()=>{C(),t(i)},5e3);const _=[{type:"h264",encodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"},width:320,height:240,bitrate:1e6},decodeConfig:{codec:"avc1.42E01E",avc:{format:"annexb"}}},{type:"vp8",encodeConfig:{codec:"vp8",width:320,height:240,bitrate:1e6},decodeConfig:{codec:"vp8"}}];(await Promise.all(_.map(async N=>{const L={type:N.type,encodeSupported:!1,decodeSupported:!1};let q;try{q=await new Promise(async(lA,tA)=>{try{const BA=new VideoEncoder({output:gA=>{lA(gA),L.encodeSupported=!0},error:tA});BA.configure(N.encodeConfig),w();const IA=new VideoFrame(n,{timestamp:0});BA.encode(IA,{keyFrame:!0}),IA.close(),await BA.flush(),BA.close()}catch(BA){tA(BA)}})}catch(lA){return Wo.warn(`${N.type} encoder error:`,lA),L}try{await new Promise(async(lA,tA)=>{try{const BA=new VideoDecoder({output:IA=>{L.decodeSupported=!0,lA(0),IA.close()},error:tA});BA.configure(N.decodeConfig),BA.decode(q),await BA.flush(),BA.close()}catch(BA){tA(BA)}})}catch(lA){Wo.warn(`${N.type} decoder error:`,lA)}return L}))).forEach(N=>{N.type==="h264"?(i.isH264EncodeSupported=N.encodeSupported,i.isH264DecodeSupported=N.decodeSupported):N.type==="vp8"&&(i.isVp8EncodeSupported=N.encodeSupported,i.isVp8DecodeSupported=N.decodeSupported)}),C(),t(i)}catch(f){C(),Wo.warn("detectWebCodecsSupported failed:",f),t(i)}}))}var iuA=(t,i,n)=>{location.protocol!=="http:"||VY||(t[i]=()=>{throw new fl({code:qg.INVALID_OPERATION,message:J_.NOT_SUPPORTED_HTTP})})},ouA=function(t){return!(t.type!=="candidate-pair"||!t.nominated||t.state!=="in-progress"&&t.state!=="succeeded")&&!(Sv(t.selected)&&!t.selected)};function f$(){let t="";return screen.width&&(t+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),t}function y$(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function D$(){const t={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let n=0;n=86,G$="RTCRtpScriptTransform"in window,uuA=eF&&(N$||G$),P4=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function b$(){const t={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return er(window.AudioDecoder)||(t.AudioDecoder=!0),er(window.AudioEncoder)||(t.AudioEncoder=!0),er(window.VideoDecoder)||(t.VideoDecoder=!0),er(window.VideoEncoder)||(t.VideoEncoder=!0),er(window.ImageDecoder)||(t.ImageDecoder=!0),t}function k$(){return"mediaSession"in navigator&&!er(navigator.mediaSession.setActionHandler)}function L$(){return!er(window.WebTransport)}function EuA(){return typeof WebAssembly<"u"&&WebAssembly.validate(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 duA(){const t={browser:`${Mv.name}/${Mv.version}`,os:c$(),displayResolution:f$(),isScreenShareSupported:O4(),isWebRTCSupported:P4(),isGetUserMediaSupported:y$(),isWebAudioSupported:D$(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:b$(),isMediaSessionSupported:k$(),isWebTransportSupported:L$()};return navigator.userAgent.includes("miniProgram")&&(t.browser=`mini/${t.browser}`),t}var U$="checkResult";function WZ(t=30){C$.setItem(U$+t,{ua:navigator.userAgent,checkResult:Xs})}function CuA(t){kV();const i=C$.getItem(U$+t);i&&i.ua===navigator.userAgent&&i.checkResult&&huA(i.checkResult.detail,Xs.detail)&&(Xs=i.checkResult),p$(t)}function huA(t,i){return!!Qv(t)&&Object.keys(i).every(n=>n in t)}function x4(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var BuA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function zZ(t){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[t]}var ZZ=!1;async function QuA(){var t;try{if(ZZ||!((t=navigator?.mediaCapabilities)!=null&&t.encodingInfo))return;const i=b4(),n=bIA();if(i===0||n===0)return;ZZ=!0;const c=["H264","VP8","VP9","AV1","H265"],[I,C]=await Promise.all([F$(c),O$(c)]);I&&Object.keys(I).forEach(_=>{const N=zZ(_.toLowerCase());dr.addEnum({key:513707,value:+`${N}${+I[_].supported}${+I[_].powerEfficient}${i}${n}`,useUV:!1})}),C&&Object.keys(C).forEach(_=>{const N=zZ(_.toLowerCase());dr.addEnum({key:514713,value:+`${N}${+C[_].supported}${+C[_].powerEfficient}${i}${n}`,useUV:!1})});const{sender:f,receiver:w}=P$();dr.addEnum({key:513708,value:+`${i}${n}${+f.high}`,useUV:!1}),dr.addEnum({key:513709,value:+`${i}${n}${+f.main}`,useUV:!1}),dr.addEnum({key:514714,value:+`${i}${n}${+w.high}`,useUV:!1}),dr.addEnum({key:514715,value:+`${i}${n}${+w.main}`,useUV:!1})}catch(i){Wo.info("detectVideoCodecCapabilities failed",i)}}async function F$(t,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const f of t){const w=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${f}`,width:i,height:n,bitrate:I,framerate:c}});C[f]=w}}catch{}return C}async function O$(t,i=1920,n=1080,c=30,I=3e3){const C={};try{for(const f of t){const w=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${f}`,width:i,height:n,bitrate:I,framerate:c}});C[f]=w}}catch{}return C}function P$(){const t={sender:{base:!1,main:!1,high:!1},receiver:{base:!1,main:!1,high:!1}};try{if(RTCRtpSender&&typeof RTCRtpSender.getCapabilities=="function"){const i=RTCRtpSender.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":t.sender.base=!0;break;case"4d":t.sender.main=!0;break;case"64":t.sender.high=!0}}})}if(RTCRtpReceiver&&typeof RTCRtpReceiver.getCapabilities=="function"){const i=RTCRtpReceiver.getCapabilities("video");i&&i.codecs&&i.codecs.filter(n=>n.mimeType.toLowerCase()==="video/h264").forEach(n=>{if(n.sdpFmtpLine){const c=n.sdpFmtpLine.match(/profile-level-id=([0-9a-fA-F]+)/);if(c&&c[1])switch(c[1].slice(0,2)){case"42":t.receiver.base=!0;break;case"4d":t.receiver.main=!0;break;case"64":t.receiver.high=!0}}})}}catch(i){Wo.warn("get H264 profile levelId failed",i)}return t}var puA=mT(zU()),XZ=Symbol("instance"),z1=Symbol("cacheResult"),u3=class{constructor(t,i,n){this.oldState=t,this.newState=i,this.action=n,this.aborted=!1}abort(t){this.aborted=!0,dU.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},E3=class extends Error{constructor(t,i,n){super(i),this.state=t,this.message=i,this.cause=n}};function muA(t){return typeof t=="object"&&t&&"then"in t}var EU=new Map;function Su(t,i,n={}){return(c,I,C)=>{const f=n.action||I;if(!n.context){const _=EU.get(c)||[];EU.has(c)||EU.set(c,_),_.push({from:t,to:i,action:f})}const w=C.value;C.value=function(..._){let N=this;if(n.context&&(N=Ar.get(typeof n.context=="function"?n.context.call(this,..._):n.context)),N.state===i)return n.sync?N[z1]:Promise.resolve(N[z1]);N.state instanceof u3&&N.state.action==n.abortAction&&N.state.abort(N);let L=null;Array.isArray(t)?t.length==0?N.state instanceof u3&&N.state.abort(N):typeof N.state=="string"&&t.includes(N.state)||(L=new E3(N._state,`${N.name} ${f} to ${i} failed: current state ${N._state} not from ${t.join("|")}`)):t!==N.state&&(L=new E3(N._state,`${N.name} ${f} to ${i} failed: current state ${N._state} not from ${t}`));const q=gA=>{if(n.fail&&n.fail.call(this,gA),n.sync){if(n.ignoreError)return gA;throw gA}return n.ignoreError?Promise.resolve(gA):Promise.reject(gA)};if(L)return q(L);const lA=N.state,tA=new u3(lA,i,f);dU.call(N,tA);const BA=gA=>{var RA;return N[z1]=gA,tA.aborted||(dU.call(N,i),(RA=n.success)===null||RA===void 0||RA.call(this,N[z1])),gA},IA=gA=>(dU.call(N,lA,gA),q(gA));try{const gA=w.apply(this,_);return muA(gA)?gA.then(BA).catch(IA):n.sync?BA(gA):Promise.resolve(BA(gA))}catch(gA){return IA(new E3(N._state,`${N.name} ${f} from ${t} to ${i} failed: ${gA}`,gA instanceof Error?gA:new Error(String(gA))))}}}}var fuA=typeof window<"u"&&window.__AFSM__?(n,c)=>{window.dispatchEvent(new CustomEvent(n,{detail:c}))}:typeof importScripts<"u"?(n,c)=>{postMessage({type:n,payload:c})}:()=>{};function dU(t,i){const n=this._state;this._state=t;const c=t.toString();t&&this.emit(c,n),this.emit(Ar.STATECHANGED,t,n,i),this.updateDevTools({value:t,old:n,err:i instanceof Error?i.message:String(i)})}var Ar=class XC extends puA.default{constructor(i,n,c){super(),this.name=i,this.groupName=n,this._state=XC.INIT,i||(i=Date.now().toString(36)),c?Object.setPrototypeOf(this,c):c=Object.getPrototypeOf(this),n||(this.groupName=this.constructor.name);const I=c[XZ];I?this.name=I.name+"-"+I.count++:c[XZ]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),n=EU.get(i)||[];let c=new Set,I=[],C=[];const f=new Set,w=Object.getPrototypeOf(i);EU.has(w)&&(w.stateDiagram.forEach(N=>c.add(N)),w.allStates.forEach(N=>f.add(N))),n.forEach(({from:N,to:L,action:q})=>{typeof N=="string"?I.push({from:N,to:L,action:q}):N.length?N.forEach(lA=>{I.push({from:lA,to:L,action:q})}):C.push({to:L,action:q})}),I.forEach(({from:N,to:L,action:q})=>{f.add(N),f.add(L),f.add(q+"ing"),c.add(`${N} --> ${q}ing : ${q}`),c.add(`${q}ing --> ${L} : ${q} 🟢`),c.add(`${q}ing --> ${N} : ${q} 🔴`)}),C.forEach(({to:N,action:L})=>{c.add(`${L}ing --> ${N} : ${L} 🟢`),f.forEach(q=>{q!==N&&c.add(`${q} --> ${L}ing : ${L}`)})});const _=[...c];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:f}}),_}static get(i){let n;return typeof i=="string"?(n=XC.instances.get(i),n||XC.instances.set(i,n=new XC(i,void 0,Object.create(XC.prototype)))):(n=XC.instances2.get(i),n||XC.instances2.set(i,n=new XC(i.constructor.name,void 0,Object.create(XC.prototype)))),n}static getState(i){var n;return(n=XC.get(i))===null||n===void 0?void 0:n.state}updateDevTools(i={}){fuA(XC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){dU.call(this,i)}};Ar.STATECHANGED="stateChanged",Ar.UPDATEAFSM="updateAFSM",Ar.INIT="[*]",Ar.ON="on",Ar.OFF="off",Ar.instances=new Map,Ar.instances2=new WeakMap;var Y4=typeof window<"u",$Z=Y4&&window.requestIdleCallback||function(t){const i=Date.now();return setTimeout(()=>{t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},yuA=Y4&&window.cancelIdleCallback||function(t){clearTimeout(t)},A6=Y4&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),JL=class BE{static generateTaskID(){return this.currentTaskID++}static run(i,n,c){c?.fps&&(c.delay=c.delay||Number((1e3/c.fps).toFixed(2))),c=Rn(Rn({},i==="interval"?{delay:2e3,count:0,backgroundTask:!0}:i==="ric"?{delay:1e4,count:0}:i==="raf"?{fps:60,delay:16.6,count:0,backgroundTask:!0}:{delay:2e3,count:0,backgroundTask:!0}),c);const I=gB(Rn({taskID:this.generateTaskID(),loopCount:0,intervalID:null,timeoutID:null,rafID:null,ricID:null,taskName:i,callback:n},c),{delay:c.delay});return this.taskMap.set(I.taskID,I),this[i](I),I.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,BE.isBreakLoop(i)},i.delay)}static intervalInWorker(i){BE.sharedWorker||(BE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` const timers = new Map(); self.onmessage = function(e) { const { taskId, delay, type } = e.data; @@ -548,15 +548,15 @@ Refer to: ${mZ("en",w)} timers.delete(taskId); } }; - `],{type:"application/javascript"}))),hE.sharedWorker.onmessage=r=>{var l;if(r.data.type==="tick"){const I=hE.workerTasks.get(r.data.taskId);I&&(hE.isBreakLoop(I)?((l=hE.sharedWorker)==null||l.postMessage({type:"stop",taskId:I.taskID}),hE.workerTasks.delete(I.taskID)):(I.callback(),I.loopCount+=1))}}),hE.workerTasks.set(i.taskID,i),hE.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const r=()=>{if(i.callback(),i.loopCount+=1,!hE.isBreakLoop(i))return i.timeoutID=setTimeout(r,i.delay)};return i.timeoutID=setTimeout(r,i.delay)}static ric(i){let r,l=Yc();const I=()=>{if(r=Yc()-l,r>=i.delay&&(l=Yc()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!hE.isBreakLoop(i))return i.ricID=_Z(I,{timeout:i.delay})};return i.ricID=_Z(I,{timeout:i.delay})}static raf(i){let r,l=Yc();const I=()=>{if(document.hidden&&i.backgroundTask)return r=Yc()-l,l=Yc(),i.callback(),i.loopCount+=1,hE.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(I,i.delay-Math.floor(r%i.delay));if(r=Yc()-l,r>=i.delay&&(l=Yc()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!hE.isBreakLoop(i))return i.rafID=requestAnimationFrame(I)};if(i.rafID=requestAnimationFrame(I),i.backgroundTask){const h=()=>{if(document.hidden){const f=Yc()-l;f>=i.delay?I():i.timeoutID=setTimeout(I,i.delay-f)}};document.addEventListener("visibilitychange",h),i.onVisibilitychange=h,document.hidden&&h()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;const{intervalID:r,timeoutID:l,rafID:I,ricID:h,onVisibilitychange:f}=this.taskMap.get(i);return r&&clearInterval(r),l&&clearTimeout(l),I&&TZ&&TZ(I),h&&KIA(h),f&&document.removeEventListener("visibilitychange",f),this.taskMap.delete(i),!0}static isBreakLoop(i){return!this.hasTask(i.taskID)||i.count!==0&&i.loopCount>=i.count&&(this.clearTask(i.taskID),!0)}};de(FL,"taskMap",new Map),de(FL,"currentTaskID",1),de(FL,"sharedWorker",null),de(FL,"workerTasks",new Map);var jIA=FL,yQ=jIA,Vn={LOAD_START:$t.LOADSTART,LOADED_DATA:$t.LOADEDDATA,LOADED_META_DATA:$t.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:$t.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:$t.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:$t.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change",FIRST_FRAME_RENDER:"first-frame-render"},Z3={};qW(Z3,{create:()=>f4,remove:()=>yU});var rU=new WeakMap;function f4(t,i){rU.has(t)||rU.set(t,[]);const r=rU.get(t),l={add:(I,h)=>("addEventListener"in i?(r.push(i.removeEventListener.bind(i,I,h)),i.addEventListener(I,h)):(r.push(i.off.bind(i,I,h)),i.on(I,h)),l)};return l}function yU(t){const i=rU.get(t);i&&(i.forEach(r=>r()),rU.delete(t))}var WIA=class{constructor(){de(this,"_roomIdMap",new Map),de(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:SY,env:Jj.QCLOUD,browserVersion:yv.name+yv.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:i,userId:r,roomId:l}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=r,this._roomIdMap.set(r,String(l))}logSuccessEvent(t){!TY&&Wo.isAbleToUpload&&this._configs.env===Jj.QCLOUD&&this.uploadEventToKibana(nB(Rn({},t),{result:"success"}))}logFailedEvent(t){if(TY||!Wo.isAbleToUpload)return;const{eventType:i,code:r,error:l,userId:I}=t,h={roomId:this._roomIdMap.get(I||this._configs.userId),userId:I,eventType:i,result:"failed",code:r||l?.extraCode||l?.code||qg.UNKNOWN};this._configs.env===Jj.QCLOUD&&this.uploadEventToKibana(nB(Rn({},h),{error:l}))}uploadEventToKibana(t){let i=`stat-${t.eventType}-${t.result}`;t.eventType!=="delta-join"&&t.eventType!=="delta-leave"&&t.eventType!=="delta-publish"||(i=`${t.eventType}:${t.delta}`),this.uploadEvent({log:i,userId:t.userId}),t.result==="failed"&&(i=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:i,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:i,error:r}){const l={timestamp:YX(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:SY,log:t};r&&(l.errorInfo=r.message,r.stack&&(l.errorInfo+=` -${r.stack}`));const I=z3.enable?XW(l,2002,Number(this._configs.sdkAppId)):JSON.stringify(l);this.sendRequest(WW(this._configs.sdkAppId,HX.LOG),I)}sendRequest(t,i){setTimeout(()=>l7({url:t,body:i,priority:"low"}).catch(()=>{}),2e3)}},oh=new WIA,sv=new WeakMap;function zIA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:l}){return function(I,h,f){const w=A4({retryFunction:f.value,settings:t,onError({error:_,retry:G,reject:U,retryFuncArgs:j}){var lA;i?i.call(this,_,()=>{var sA;(sA=sv.get(I))!=null&&sA.has(h)?G():U(_)},U,j):(lA=sv.get(I))!=null&&lA.has(h)?G():U(_)},onRetrying(_,G){var U;k_(r)&&r.call(this,_,G),(U=sv.get(I))!=null&&U.has(h)&&(sv.get(I).get(h).stopRetry=G)},onRetryFailed:l});return f.value=function(..._){const G=sv.get(I);return G?G.set(h,{args:_}):sv.set(I,new Map([[h,{args:_}]])),w.apply(this,_).finally(()=>{var U;return(U=sv.get(I))==null?void 0:U.delete(h)})},f}}var lv=class extends Xn{constructor(t,i){super(t.id,`${i}-player`),this.options=t,this.kind=i,de(this,"id"),de(this,"element",null),de(this,"track"),de(this,"url"),de(this,"attr"),de(this,"mode"),de(this,"muted"),de(this,"_log"),de(this,"isPausedByUserCall",!1),de(this,"_pausedRetryCount"),de(this,"_isElementPlayingFired",!1),de(this,"_interval"),de(this,"_delayDestroyTimeoutId",0),de(this,"_playSuccessResolve"),de(this,"_isReplayByRecreateMediaStreamCalled",!1),de(this,"isPlayCalled",!1),de(this,"isInAutoPlayFailedState",!1),de(this,"isBindAutoPlayEvent",!1),this.id=t.id,this._log=t.log,this.track=t.track,this.muted=t.muted,this._pausedRetryCount=b_,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var t;return this._state==="PLAYING"&&((t=this.element)==null?void 0:t.paused)===!1}get isPaused(){var t;return this._state==="PAUSED"||((t=this.element)==null?void 0:t.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(t){this.attr=t}setUrl(t){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),t!==this.url&&(this.url=t,t!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=t))}async play(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),await new Promise((t,i)=>{this._playSuccessResolve=t,this.element.play().then(t,i)})}catch(t){const i=GY({key:NY.PLAY_FAILED,data:{media:this.kind,error:t}});if(this._log.warn(t),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new ml({code:qg.PLAY_NOT_ALLOWED,message:i})}}stop(t=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!F7?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${t}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*t)):this.destroyElement(),this.handleStopped($t.ENDED),this._interval>0&&yQ.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var t;(t=this.element)==null||t.pause()}resume(t=!1){return this.isPausedByUserCall=!1,this.doResume(t)}doResume(t=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():ZlA?this.replay():this.play().catch(()=>{})}setMuted(t){this.element&&(this.element.muted=t),this.muted=t}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const t=this.handleElementEvent.bind(this);return f4(this.element,this.element).add($t.PLAYING,t).add($t.ENDED,t).add($t.PAUSE,t).add($t.ERROR,t).add($t.LOADSTART,t).add($t.LOADEDDATA,t).add($t.LOADEDMETADATA,t)}}bindTrackEvents(t=this.track){if(t){const i=this.handleTrackEvent.bind(this);Z3?.create(t,t).add($t.ENDED,i).add($t.MUTE,i).add($t.UNMUTE,i),t.readyState===$t.ENDED&&this.handleTrackEvent({type:$t.ENDED}),t.muted&&this.handleTrackEvent({type:$t.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),ps.on(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(t=this.track){t&&yU(t)}unbindEvents(){this.element&&yU(this.element),this.unbindTrackEvents(),ps.off(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(t){switch(t.type){case $t.PLAYING:DU()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying($t.PLAYING),this._interval&&(yQ.clearTask(this._interval),this._interval=-1);break;case $t.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped($t.ENDED);break;case $t.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused($t.PAUSE);break;case $t.ERROR:if(this.element&&this.element.error){this.handlePaused($t.ERROR);const{code:i,message:r}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${r} userAgent: ${navigator.userAgent}`),oh.uploadEvent({log:`stat-${this.kind}-${tU.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),jlA||T7?this.emit(Vn.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case $t.LOADEDDATA:this.kind===$t.VIDEO&&this.emit(Vn.LOADED_DATA);break;case $t.LOADEDMETADATA:this.kind===$t.VIDEO&&this.emit(Vn.LOADED_META_DATA);break;case $t.LOADSTART:this.emit(Vn.LOAD_START)}}replayByRecreateMediaStream(t){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),oh.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Ir.addSuccessEvent({key:this.kind===$t.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),oh.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Ir.addFailedEvent({key:this.kind===$t.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(Vn.ERROR,t)})}doReplayByRecreateMediaStream(t){return this._log.warn(`delay ${t}ms to recreate mediaStream`),new Promise((i,r)=>{rT(t).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var l,I,h;this._log.warn(`element onerror ${(I=(l=this.element)==null?void 0:l.error)==null?void 0:I.code} fired after recreated mediaStream`),r((h=this.element)==null?void 0:h.error)}),rT(5e3).then(()=>{var l,I;this.isPlaying&&!((l=this.element)!=null&&l.error)||r((I=this.element)==null?void 0:I.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(t){const i=t.type;switch(this.options.enableLogTrackState&&this._log[i===$t.UNMUTE?"info":"warn"](`track ${i}`),i){case $t.ENDED:this.handleStopped($t.ENDED);break;case $t.MUTE:this.handlePaused($t.MUTE);break;case $t.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),await this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying($t.UNMUTE))}}handlePlaying(t){var i;return this._log.debug("handlePlaying",t),(i=this._playSuccessResolve)==null||i.call(this,t),t}handlePaused(t){return this._log.debug("handlePaused",t),t}handleStopped(t){return this._log.debug("handleStopped",t),t}getElement(){return this.element}};de(lv,"PlayerEvent",Vn),Cc([zIA({settings:{retries:2,timeout:0},onError(t,i,r,l){l[0]=(l[0]||1e3)+1e3,i()}})],lv.prototype,"doReplayByRecreateMediaStream"),Cc([Du([],"PLAYING",{sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:t})}})],lv.prototype,"handlePlaying"),Cc([Du("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:t})}})],lv.prototype,"handlePaused"),Cc([Du([],"STOPPED",{sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:t})}})],lv.prototype,"handleStopped");var Qm="trtc_autoplay",A3=`${Qm}_mask`,DL=`${Qm}_wrapper`,NZ=`${Qm}_header`,e3=`${Qm}_content`,x1=`${Qm}_action_wrapper`,t3=`${Qm}_question`,i3=`${Qm}_collapse`,Y1=`${Qm}_action_confirm`,GZ=`${Qm}_detail`,bZ="#2473E8",y4="dialog",ZIA=`${y4}-show`,XIA=`${y4}-1`,$IA=`${y4}-2`,kZ=!1,X3=!1,DU=()=>X3,B$=`${x3}/${zy()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,LZ=`
${zy()?"其他方案?":"Any other solution?"}`,AuA=zy()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${LZ}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${LZ}`,euA=class{constructor(){if(de(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),de(this,"_dialogNode",null),de(this,"_bodyPosition",""),de(this,"_showDetail",!1),de(this,"_isCollapseClicked",!1),de(this,"_isQuestionClicked",!1),zy()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!kZ){const t=document.createElement("style");t.innerHTML=`.${A3}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${A3} div:not(.${x1}){display:block !important;}.${DL}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${DL} a{color:${bZ};}.${NZ}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${e3}{margin:8px 0;}.${x1}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${i3}{margin-right:auto;cursor:pointer}.${t3}{height:100%;line-height:16px;cursor:pointer;}.${Y1}{margin-left:8px;color:#fff;background:${bZ};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${Y1}:hover{opacity:0.9;}.${i3},.${Y1},.${e3},.${t3}{font-size:14px;}@media screen and (max-width:750px){.${DL}{width:80vw;}}`,document.head.appendChild(t),kZ=!0}this.addDiaLog()}createDiaLog(){const t=document.createElement("template");t.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=Y1,i.innerText=zy()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const r=document.createElement("div");r.className=t3,r.innerHTML=` + `],{type:"application/javascript"}))),BE.sharedWorker.onmessage=n=>{var c;if(n.data.type==="tick"){const I=BE.workerTasks.get(n.data.taskId);I&&(BE.isBreakLoop(I)?((c=BE.sharedWorker)==null||c.postMessage({type:"stop",taskId:I.taskID}),BE.workerTasks.delete(I.taskID)):(I.callback(),I.loopCount+=1))}}),BE.workerTasks.set(i.taskID,i),BE.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const n=()=>{if(i.callback(),i.loopCount+=1,!BE.isBreakLoop(i))return i.timeoutID=setTimeout(n,i.delay)};return i.timeoutID=setTimeout(n,i.delay)}static ric(i){let n,c=Yc();const I=()=>{if(n=Yc()-c,n>=i.delay&&(c=Yc()-Math.floor(n%i.delay),i.callback(),i.loopCount+=1),!BE.isBreakLoop(i))return i.ricID=$Z(I,{timeout:i.delay})};return i.ricID=$Z(I,{timeout:i.delay})}static raf(i){let n,c=Yc();const I=()=>{if(document.hidden&&i.backgroundTask)return n=Yc()-c,c=Yc(),i.callback(),i.loopCount+=1,BE.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(I,i.delay-Math.floor(n%i.delay));if(n=Yc()-c,n>=i.delay&&(c=Yc()-Math.floor(n%i.delay),i.callback(),i.loopCount+=1),!BE.isBreakLoop(i))return i.rafID=requestAnimationFrame(I)};if(i.rafID=requestAnimationFrame(I),i.backgroundTask){const C=()=>{if(document.hidden){const f=Yc()-c;f>=i.delay?I():i.timeoutID=setTimeout(I,i.delay-f)}};document.addEventListener("visibilitychange",C),i.onVisibilitychange=C,document.hidden&&C()}return i.taskID}static hasTask(i){return this.taskMap.has(i)}static clearTask(i){if(!this.taskMap.has(i))return!0;const{intervalID:n,timeoutID:c,rafID:I,ricID:C,onVisibilitychange:f}=this.taskMap.get(i);return n&&clearInterval(n),c&&clearTimeout(c),I&&A6&&A6(I),C&&yuA(C),f&&document.removeEventListener("visibilitychange",f),this.taskMap.delete(i),!0}static isBreakLoop(i){return!this.hasTask(i.taskID)||i.count!==0&&i.loopCount>=i.count&&(this.clearTask(i.taskID),!0)}};Be(JL,"taskMap",new Map),Be(JL,"currentTaskID",1),Be(JL,"sharedWorker",null),Be(JL,"workerTasks",new Map);var DuA=JL,MQ=DuA,Jn={LOAD_START:ei.LOADSTART,LOADED_DATA:ei.LOADEDDATA,LOADED_META_DATA:ei.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:ei.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:ei.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:ei.ENTER_PICTURE_IN_PICTURE,USER_RESUME_IN_PIP_OR_FULL_SCREEN:"user-resume-in-pip-or-full-screen",USER_PAUSE_IN_PIP_OR_FULL_SCREEN:"user-pause-in-pip-or-full-screen",ENTER_FULL_SCREEN:"enter-full-screen",LEAVE_FULL_SCREEN:"leave-full-screen",VOLUME_CHANGE:"volume-change",FIRST_FRAME_RENDER:"first-frame-render"},uW={};u4(uW,{create:()=>V4,remove:()=>NU});var CU=new WeakMap;function V4(t,i){CU.has(t)||CU.set(t,[]);const n=CU.get(t),c={add:(I,C)=>("addEventListener"in i?(n.push(i.removeEventListener.bind(i,I,C)),i.addEventListener(I,C)):(n.push(i.off.bind(i,I,C)),i.on(I,C)),c)};return c}function NU(t){const i=CU.get(t);i&&(i.forEach(n=>n()),CU.delete(t))}var SuA=class{constructor(){Be(this,"_roomIdMap",new Map),Be(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:UY,env:s3.QCLOUD,browserVersion:Mv.name+Mv.version,ua:navigator.userAgent})}setConfig({sdkAppId:t,env:i,userId:n,roomId:c}){t!==this._configs.sdkAppId&&(this._configs.sdkAppId=String(t)),this._configs.env=i,this._configs.userId=n,this._roomIdMap.set(n,String(c))}logSuccessEvent(t){!VY&&Wo.isAbleToUpload&&this._configs.env===s3.QCLOUD&&this.uploadEventToKibana(gB(Rn({},t),{result:"success"}))}logFailedEvent(t){if(VY||!Wo.isAbleToUpload)return;const{eventType:i,code:n,error:c,userId:I}=t,C={roomId:this._roomIdMap.get(I||this._configs.userId),userId:I,eventType:i,result:"failed",code:n||c?.extraCode||c?.code||qg.UNKNOWN};this._configs.env===s3.QCLOUD&&this.uploadEventToKibana(gB(Rn({},C),{error:c}))}uploadEventToKibana(t){let i=`stat-${t.eventType}-${t.result}`;t.eventType!=="delta-join"&&t.eventType!=="delta-leave"&&t.eventType!=="delta-publish"||(i=`${t.eventType}:${t.delta}`),this.uploadEvent({log:i,userId:t.userId}),t.result==="failed"&&(i=`stat-${t.eventType}-${t.result}-${t.code}`,this.uploadEvent({log:i,userId:t.userId,error:t.error}))}uploadEvent({log:t,userId:i,error:n}){const c={timestamp:l7(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:UY,log:t};n&&(c.errorInfo=n.message,n.stack&&(c.errorInfo+=` +${n.stack}`));const I=IW.enable?Q4(c,2002,Number(this._configs.sdkAppId)):JSON.stringify(c);this.sendRequest(C4(this._configs.sdkAppId,E7.LOG),I)}sendRequest(t,i){setTimeout(()=>b7({url:t,body:i,priority:"low"}).catch(()=>{}),2e3)}},ah=new SuA,av=new WeakMap;function MuA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:n,onRetryFailed:c}){return function(I,C,f){const w=m4({retryFunction:f.value,settings:t,onError({error:_,retry:N,reject:L,retryFuncArgs:q}){var lA;i?i.call(this,_,()=>{var tA;(tA=av.get(I))!=null&&tA.has(C)?N():L(_)},L,q):(lA=av.get(I))!=null&&lA.has(C)?N():L(_)},onRetrying(_,N){var L;F_(n)&&n.call(this,_,N),(L=av.get(I))!=null&&L.has(C)&&(av.get(I).get(C).stopRetry=N)},onRetryFailed:c});return f.value=function(..._){const N=av.get(I);return N?N.set(C,{args:_}):av.set(I,new Map([[C,{args:_}]])),w.apply(this,_).finally(()=>{var L;return(L=av.get(I))==null?void 0:L.delete(C)})},f}}var Ev=class extends Ar{constructor(t,i){super(t.id,`${i}-player`),this.options=t,this.kind=i,Be(this,"id"),Be(this,"element",null),Be(this,"track"),Be(this,"url"),Be(this,"attr"),Be(this,"mode"),Be(this,"muted"),Be(this,"_log"),Be(this,"isPausedByUserCall",!1),Be(this,"_pausedRetryCount"),Be(this,"_isElementPlayingFired",!1),Be(this,"_interval"),Be(this,"_delayDestroyTimeoutId",0),Be(this,"_playSuccessResolve"),Be(this,"_isReplayByRecreateMediaStreamCalled",!1),Be(this,"isPlayCalled",!1),Be(this,"isInAutoPlayFailedState",!1),Be(this,"isBindAutoPlayEvent",!1),this.id=t.id,this._log=t.log,this.track=t.track,this.muted=t.muted,this._pausedRetryCount=U_,this._state="STOPPED",this.bindTrackEvents(),this._log.info(`create ${i}-player ${this.id}`)}get isPlaying(){var t;return this._state==="PLAYING"&&((t=this.element)==null?void 0:t.paused)===!1}get isPaused(){var t;return this._state==="PAUSED"||((t=this.element)==null?void 0:t.paused)===!0}get isStopped(){return this._state==="STOPPED"}setAttr(t){this.attr=t}setUrl(t){this.track&&(this.unbindTrackEvents(),this.element&&(this.element.srcObject=null),this.track=null),t!==this.url&&(this.url=t,t!==null&&this.element&&(this.element.crossOrigin="anonymous",this.element.src=t))}async play(){if(!this.isPlaying)try{this.isPlayCalled=!0,this._delayDestroyTimeoutId&&(clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0,this.bindTrackEvents(),this.bindElementEvents()),this.bindAutoPlayEvent(),await new Promise((t,i)=>{this._playSuccessResolve=t,this.element.play().then(t,i)})}catch(t){const i=HY({key:JY.PLAY_FAILED,data:{media:this.kind,error:t}});if(this._log.warn(t),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new fl({code:qg.PLAY_NOT_ALLOWED,message:i})}}stop(t=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!r$?this._delayDestroyTimeoutId||((i=this.element)==null||i.remove(),this._log.info(`destroy element after 3 * ${t}`),this._delayDestroyTimeoutId=setTimeout(()=>this.destroyElement(),3*t)):this.destroyElement(),this.handleStopped(ei.ENDED),this._interval>0&&MQ.clearTask(this._interval)}destroyElement(){this.element&&(this._log.debug("destroy element"),this.element.remove(),this.element.src="",this.element.srcObject=null,this.element=null),clearTimeout(this._delayDestroyTimeoutId),this._delayDestroyTimeoutId=0}pause(){this._log.info("pause"),this.isPausedByUserCall=!0,this.doPause()}doPause(){var t;(t=this.element)==null||t.pause()}resume(t=!1){return this.isPausedByUserCall=!1,this.doResume(t)}doResume(t=!1){return this._log.info("resume"),this.isPausedByUserCall||this.isPlaying?Promise.resolve():vIA?this.replay():this.play().catch(()=>{})}setMuted(t){this.element&&(this.element.muted=t),this.muted=t}replay(){return this.stop(),this.play().catch(()=>{})}bindElementEvents(){if(this.element){const t=this.handleElementEvent.bind(this);return V4(this.element,this.element).add(ei.PLAYING,t).add(ei.ENDED,t).add(ei.PAUSE,t).add(ei.ERROR,t).add(ei.LOADSTART,t).add(ei.LOADEDDATA,t).add(ei.LOADEDMETADATA,t)}}bindTrackEvents(t=this.track){if(t){const i=this.handleTrackEvent.bind(this);uW?.create(t,t).add(ei.ENDED,i).add(ei.MUTE,i).add(ei.UNMUTE,i),t.readyState===ei.ENDED&&this.handleTrackEvent({type:ei.ENDED}),t.muted&&this.handleTrackEvent({type:ei.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),ms.on(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(t=this.track){t&&NU(t)}unbindEvents(){this.element&&NU(this.element),this.unbindTrackEvents(),ms.off(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(t){switch(t.type){case ei.PLAYING:GU()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(ei.PLAYING),this._interval&&(MQ.clearTask(this._interval),this._interval=-1);break;case ei.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(ei.ENDED);break;case ei.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(ei.PAUSE);break;case ei.ERROR:if(this.element&&this.element.error){this.handlePaused(ei.ERROR);const{code:i,message:n}=this.element.error;this._log.error(`${this.kind} ${this._log.isLocal?"local":"remote"} MediaError code: ${i} message: ${n} userAgent: ${navigator.userAgent}`),ah.uploadEvent({log:`stat-${this.kind}-${lU.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),DIA||A$?this.emit(Jn.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case ei.LOADEDDATA:this.kind===ei.VIDEO&&this.emit(Jn.LOADED_DATA);break;case ei.LOADEDMETADATA:this.kind===ei.VIDEO&&this.emit(Jn.LOADED_META_DATA);break;case ei.LOADSTART:this.emit(Jn.LOAD_START)}}replayByRecreateMediaStream(t){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),dr.addSuccessEvent({key:this.kind===ei.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),ah.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),dr.addFailedEvent({key:this.kind===ei.AUDIO?506700:516700,error:(i=this.element)==null?void 0:i.error}),this.emit(Jn.ERROR,t)})}doReplayByRecreateMediaStream(t){return this._log.warn(`delay ${t}ms to recreate mediaStream`),new Promise((i,n)=>{IT(t).then(()=>{this.element&&(this.element.srcObject=null,this.element.srcObject=new MediaStream([this.track]),this._log.warn("recreated mediaStream"),this.element.onerror=()=>{var c,I,C;this._log.warn(`element onerror ${(I=(c=this.element)==null?void 0:c.error)==null?void 0:I.code} fired after recreated mediaStream`),n((C=this.element)==null?void 0:C.error)}),IT(5e3).then(()=>{var c,I;this.isPlaying&&!((c=this.element)!=null&&c.error)||n((I=this.element)==null?void 0:I.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(t){const i=t.type;switch(this.options.enableLogTrackState&&this._log[i===ei.UNMUTE?"info":"warn"](`track ${i}`),i){case ei.ENDED:this.handleStopped(ei.ENDED);break;case ei.MUTE:this.handlePaused(ei.MUTE);break;case ei.UNMUTE:this.mode>0?this.handlePlaying(this.mode.toString()):this.element&&(this.element.paused&&!this.isPausedByUserCall&&(this._log.warn("track unmuted and element is paused, resume"),await this.doResume()),this.element&&!this.element.paused&&this._isElementPlayingFired&&this.handlePlaying(ei.UNMUTE))}}handlePlaying(t){var i;return this._log.debug("handlePlaying",t),(i=this._playSuccessResolve)==null||i.call(this,t),t}handlePaused(t){return this._log.debug("handlePaused",t),t}handleStopped(t){return this._log.debug("handleStopped",t),t}getElement(){return this.element}};Be(Ev,"PlayerEvent",Jn),Cc([MuA({settings:{retries:2,timeout:0},onError(t,i,n,c){c[0]=(c[0]||1e3)+1e3,i()}})],Ev.prototype,"doReplayByRecreateMediaStream"),Cc([Su([],"PLAYING",{sync:!0,success(t){this.emit(Jn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:t})}})],Ev.prototype,"handlePlaying"),Cc([Su("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(t){this.emit(Jn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:t})}})],Ev.prototype,"handlePaused"),Cc([Su([],"STOPPED",{sync:!0,success(t){this.emit(Jn.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:t})}})],Ev.prototype,"handleStopped");var fm="trtc_autoplay",d3=`${fm}_mask`,_L=`${fm}_wrapper`,e6=`${fm}_header`,C3=`${fm}_content`,Z1=`${fm}_action_wrapper`,h3=`${fm}_question`,B3=`${fm}_collapse`,X1=`${fm}_action_confirm`,t6=`${fm}_detail`,i6="#2473E8",J4="dialog",vuA=`${J4}-show`,RuA=`${J4}-1`,wuA=`${J4}-2`,o6=!1,EW=!1,GU=()=>EW,x$=`${iW}/${Zy()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,s6=`
${Zy()?"其他方案?":"Any other solution?"}`,_uA=Zy()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${s6}`:`Autoplay Policy: Before user interacts with the web page (clicking, touching), page will not be allowed to play media with sound. This Dialog is used to help users resume playback. ${s6}`,TuA=class{constructor(){if(Be(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Be(this,"_dialogNode",null),Be(this,"_bodyPosition",""),Be(this,"_showDetail",!1),Be(this,"_isCollapseClicked",!1),Be(this,"_isQuestionClicked",!1),Zy()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!o6){const t=document.createElement("style");t.innerHTML=`.${d3}{position:fixed;top:0;left:0;right:0;bottom:0;width:100vw;height:100vh;display:flex;justify-content:center;align-items:center;background:rgba(0,0,0,0.5);z-index:1500;}.${d3} div:not(.${Z1}){display:block !important;}.${_L}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${_L} a{color:${i6};}.${e6}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${C3}{margin:8px 0;}.${Z1}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${B3}{margin-right:auto;cursor:pointer}.${h3}{height:100%;line-height:16px;cursor:pointer;}.${X1}{margin-left:8px;color:#fff;background:${i6};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${X1}:hover{opacity:0.9;}.${B3},.${X1},.${C3},.${h3}{font-size:14px;}@media screen and (max-width:750px){.${_L}{width:80vw;}}`,document.head.appendChild(t),o6=!0}this.addDiaLog()}createDiaLog(){const t=document.createElement("template");t.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=X1,i.innerText=Zy()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const n=document.createElement("div");n.className=h3,n.innerHTML=` - `,r.onclick=this.onQuestionClick.bind(this);const l=document.createElement("div");l.className=i3,l.innerText=zy()?"详情 >":"Detail >",l.onclick=this.onCollapseClick.bind(this);const I=t.content.firstChild,h=I.querySelector(`.${x1}`);return h.appendChild(l),h.appendChild(r),h.appendChild(i),I}addDiaLog(){DU()||(X3=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${DL}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",Wo.info("show autoplay dialog"),oh.uploadEvent({log:ZIA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,X3=!1),SU=null}onConfirm(){Wo.warn("confirm clicked, try resume stream"),ps.emit(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const t=this._dialogNode.querySelector(`.${GZ}`);t.style.visibility=this._showDetail?"hidden":"visible",t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||oh.uploadEvent({log:XIA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(B$,"_blank"),this._isQuestionClicked||oh.uploadEvent({log:$IA}),this._isQuestionClicked=!0}},SU=null;function tuA(){SU||(SU=new euA)}function iuA(){SU&&SU.deleteDialog()}var aU,Oy=class extends lv{constructor(t){super(t,$t.VIDEO),de(this,"stat",{}),de(this,"_calculateTimeout",-1),de(this,"viewMirror",!1),de(this,"objectFit","cover"),de(this,"container"),de(this,"canvas"),de(this,"shouldRenderAlpha",!1),de(this,"_preSize",{width:0,height:0}),de(this,"posterImg"),de(this,"pipWindow"),de(this,"enterPIPPromise"),de(this,"_originContainerPosition"),de(this,"_isResettingSrcObject",!1),de(this,"_wrapper",null),de(this,"_useWrapper",!1),de(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,$n(t.viewMirror)||(this.viewMirror=t.viewMirror),$n(t.objectFit)||(this.objectFit=t.objectFit),this.initializeElement()}get isPlaying(){var t;return this._state==="PLAYING"&&(!this.element||!this.element.paused)&&((t=this.track)==null?void 0:t.readyState)==="live"&&!this.track.muted}initializeElement(){const t=document.createElement($t.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id",`video_${this.id}`),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,aC&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const r=t.videoWidth||0,l=t.videoHeight||0;this._log.info(`first frame render: ${r}x${l}`),this.emit(Vn.FIRST_FRAME_RENDER,{width:r,height:l})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(i):t.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let t=this._useWrapper?`grid-area:1/1;width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`:`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setLiveMode(t){if(this._useWrapper!==t&&(this._useWrapper=t,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(t){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;const i=this._wrapper,r=this.container;this.container=t,this._pausedRetryCount=b_,this.track&&this.elementToRender&&this._appendToWrapper(),i&&r&&r!==this.container&&i.isConnected&&i.children.length===0&&i.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let t=this.container.querySelector("[data-trtc-video-wrapper]");return t||(t=document.createElement("div"),t.setAttribute("data-trtc-video-wrapper","true"),t.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(t)),this._wrapper=t,t}_appendToWrapper(t){const i=t??this.elementToRender;if(this.container&&i)if(this._useWrapper){const r=this._getOrCreateWrapper();r.insertBefore(i,r.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add($t.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add($t.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add($t.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener($t.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(t){var i;return t.type===$t.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(Vn.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(Vn.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(Vn.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,r,l,I,h,f;if(this.mode===2)return;super.handleElementEvent(t);const w=t.type,_=this.isPictureInPicture(),G=this.isFullscreen(),U=t.isTrusted&&(_&&ld||G);if(w===$t.PLAYING&&U&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(G?"fullscreen":"pip")),this.emit(Vn.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),w===$t.PAUSE&&(U&&(this._log.warn("user pause in "+(G?"fullscreen":"pip")),this.emit(Vn.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),rT(500).then(()=>{var j;(j=this.container)!=null&&j.isConnected&&(this._pausedRetryCount=b_,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!DU()&&!this.isPausedByUserCall&&!U&&(this._log.info(`[${b_-this._pausedRetryCount+1}/${b_}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),Mu&&!U&&(this._interval=yQ.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){const j=this.element.style.transform;w===$t.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=j.replace("scaleX(-1)",""):w!==$t.LEAVE_PICTURE_IN_PICTURE||j.includes("scaleX")||(this.element.style.transform=`${j} scaleX(-1)`)}w===$t.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((r=this.element)==null?void 0:r.videoWidth)||(this._log.info(`video size changed to ${(l=this.element)==null?void 0:l.videoWidth}x${(I=this.element)==null?void 0:I.videoHeight}`),this._preSize.height=((h=this.element)==null?void 0:h.videoHeight)||0,this._preSize.width=((f=this.element)==null?void 0:f.videoWidth)||0,this.emit(Vn.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),w===$t.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(Vn.LEAVE_PICTURE_IN_PICTURE)),w===$t.ENTER_PICTURE_IN_PICTURE&&this.emit(Vn.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){aC&&Zj&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(t=>{this._log.warn("play failed after reset srcObject",t)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(t,i=1){var r,l;this.canvas!==t&&((r=this.canvas)==null||r.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?i:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((l=this.element)==null||l.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(t,i){this.elementToRender&&(this.elementToRender.style.width=`${t}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit=`${t}`),this.objectFit=t}setPoster(t,i=!1){return new Promise(r=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!(i&&(ld||sC))))return r();if(t==="")return this.removePosterImg(),r();if(this.posterImg)return r();const l=document.createElement("img");l.src=t;const I=window.getComputedStyle(this.element),h=I.objectFit||this.objectFit;let f=1;if(this._useWrapper){const w=parseInt(I.zIndex,10);isNaN(w)||(f=w+1)}l.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${f};width:100%;height:100%;object-fit:${h};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${h};`,l.onload=async()=>{try{l.decode&&await l.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=l;const w=this._useWrapper?this._wrapper:this.container;w?.appendChild(l),RY()&&bv<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(w){this._log.warn("decode poster image error",w)}return r()},l.onerror=()=>(this._log.warn("load poster image error"),r())})}removePosterImg(){this.posterImg&&(RY()&&bv<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||$n(this._originContainerPosition)||this.container.style.position!=="relative"||(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var t;return!!this.posterImg||!!((t=this.element)!=null&&t.getAttribute("poster"))}async pause(t=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(Zj||t&&(sC||ld))||await this.setPoster(this.getVideoFrame(),!0)}resume(t=!1){return super.resume(t).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(t=!1){return this.isPaused&&t&&this.element&&this.track&&Zj&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(t=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(r=>{}),this.isFullscreen()&&this.exitFullscreen().catch(r=>{}),this.element&&(this.element.removeEventListener($t.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(t),(i=this.canvas)==null||i.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(t){if($n(t?.isLiveStream)||this.setLiveMode(t.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){const i=this._getOrCreateWrapper();this.elementToRender.parentElement!==i&&i.insertBefore(this.elementToRender,i.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(Vn.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";const t=document.createElement("canvas");return t.width=this.element.videoWidth,t.height=this.element.videoHeight,t.getContext("2d").drawImage(this.element,0,0),t.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(p4()&&this.element&&this._calculateTimeout<0){let t=0,i=null;const r=(l,I)=>{this.stat.width=I.width,this.stat.height=I.height,i&&(this.stat.fps=Math.round((I.presentedFrames-i.presentedFrames)/(l-t)*1e3)),t=l,i=I,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var h;return(h=this.element)==null?void 0:h.requestVideoFrameCallback(r)},2e3))};this.element.requestVideoFrameCallback(r)}}catch(t){this._log.warn("init stat failed",t)}}async enterFullscreen(){const t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(Mu&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{await this.exitPictureInPicture()}catch(i){this._log.warn("exit pip failed before fullscreen:",i)}}try{if(t.requestFullscreen)await t.requestFullscreen();else if(t.webkitRequestFullscreen)await t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)await t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)await t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");await t.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(i){throw this._log.error("failed to enter fullscreen:",i),i}}async exitFullscreen(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)await document.exitFullscreen();else if(document.webkitExitFullscreen)await document.webkitExitFullscreen();else if(document.mozCancelFullScreen)await document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");await document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(t){throw this._log.error("failed to exit fullscreen:",t),t}}isFullscreen(){const t=this.elementToRender;return t?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t:!1}async toggleFullscreen(){this.isFullscreen()?await this.exitFullscreen():await this.enterFullscreen()}async enterPictureInPicture(){this.enterPIPPromise=this._enterPictureInPicture();try{return await this.enterPIPPromise}finally{delete this.enterPIPPromise}}async _enterPictureInPicture(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");const{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(t){throw this._log.error("failed to enter pip:",t.name,t.message),t}}async exitPictureInPicture(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=b_,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");await this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(i){throw this._log.error("failed to exit pip:",i),i}}isPictureInPicture(){if(!this.element)return!1;const{element:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function ouA(t,i){if(!t.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await t.audioWorklet.addModule(i),Wo.info("worklet addModule success")}catch(r){throw Wo.info(`worklet addModule catch error. ${r.message}`),r}}typeof AudioContext<"u"?aU=AudioContext:typeof webkitAudioContext<"u"?aU=webkitAudioContext:typeof mozAudioContext<"u"&&(aU=mozAudioContext);var yu,suA=1500,UZ=-1,V1=0,gU=-1,$3=!1,FZ=0,OZ=-1,PZ=-1;function Q$(){try{if(yu)return;(yu=new aU({sampleRate:48e3})).onstatechange=()=>{Wo.info(`context state: ${yu.state}${yu.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),X_()},clearTimeout(UZ)}catch(t){Wo.error(`initAudioContext failed: ${t} typeof AudioContextClass: ${typeof aU}`),UZ=setTimeout(Q$,1e3)}}Q$();var X_=()=>{yu.state==="suspended"?(V1=Yc(),nuA(),kY(),document.addEventListener("click",X_)):yu.state==="interrupted"?kY():(V1&&(Ir.addNumber({key:507800,value:Yc()-V1,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),V1=0),ruA(),document.removeEventListener("visibilitychange",X_),document.removeEventListener("click",X_))},o3=0,s3=-1;function kY(){return new Promise((t,i)=>{if(yu.state==="running")return t();Date.now()-o3<1e3?(clearTimeout(s3),s3=setTimeout(()=>{o3=Date.now(),yu.resume().then(t,i)},1e3)):(clearTimeout(s3),o3=Date.now(),yu.resume().then(t,i))}).catch(t=>{Wo.warn(`context resume failed: ${t}`),document.addEventListener("visibilitychange",X_)})}function nuA(){gU===-1&&(gU=setTimeout(()=>{yu.state==="suspended"&&($3=!0,ps.emit("155",{isSuspended:!0}))},suA))}function ruA(){gU!==-1&&(clearTimeout(gU),gU=-1,$3&&($3=!1,ps.emit("155",{isSuspended:!1})))}function auA(){if(!Mu||PZ!==-1)return;const t=()=>{Yc()-FZ<500||(yu&&yu.state==="running"&&yu.currentTime===OZ&&(Wo.warn("context is fake running, auto resume"),yu.suspend().catch(i=>{Wo.warn(`context suspend failed: ${i}`)})),OZ=yu.currentTime,FZ=Yc())};PZ=setInterval(()=>{t()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}document.addEventListener("click",X_);var oD=t=>yu,Dv=class{constructor(t){this.name=t,de(this,"node"),de(this,"node2"),de(this,"pre",new Set),de(this,"next",new Set),de(this,"context"),de(this,"connectedNodes",new Set),de(this,"nextInputChannelMap",new Map),de(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(i=>i.channelCount=t)}setChannelCount(t,i){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=i||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var i;if(t!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(r){Wo.error(r)}}setNode(t,i){var r;if(!this.node)try{(r=this.context)==null||r.addMixWeight(),this.node=t,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),Ir.addSuccessEvent({key:502701})}catch(l){Wo.error(l),Ir.addFailedEvent({key:502701,error:l})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),Ir.addSuccessEvent({key:502702})}catch(i){Wo.error(i),Ir.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(i=>{const r=this.nextInputChannelMap.get(i);t._connect(i.node,r)||i.connectNext(t)})}_connect(t,i=0){return!(!this.node||!t)&&((this.node2||this.node).connect(t,0,i),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(t,i=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,i),t}},guA=class extends Dv{constructor(t=256){super(),this.fftSize=t,de(this,"dataArray",new Uint8Array(0))}setNode(t){t.fftSize=this.fftSize,this.dataArray=new Uint8Array(t.frequencyBinCount),super.setNode(t)}getByteTimeDomainData(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const t=this.getByteTimeDomainData();let i=0,r=0,l=`M${i},${r}`;for(let I=0;Ithis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(rm.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=r=>{rm.lastMessageTime=Date.now(),this._volume=r.data.volume||0,this._volumeDb=r.data.volumeDb||0,!i&&r.data.cacheLen&&r.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),oh.logFailedEvent({userId:this._log.userId,eventType:tU.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=oD("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{rm.lastMessageTime=Date.now();const r=i.inputBuffer.getChannelData(0);let l=0;for(let I=0;I>2);t.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),t.close()}}},uuA=dT(PU()),VZ=t=>i=>i.deviceId===t,n3=class{constructor(t,i){de(this,"kind"),de(this,"type"),de(this,"devices",[]),this.kind=t,this.type=i}update(t,i){const r=t.filter(l=>l.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&p$(this.devices[0])||i&&(r.forEach(l=>{if(l.deviceId&&!this.devices.find(VZ(l.deviceId))){const I=`${this.kind}${this.type}Added`;Wo.warn(`${I}: ${JSON.stringify(l)}`),i.emit(I,l)}}),this.devices.forEach(l=>{if(l.deviceId&&!r.find(VZ(l.deviceId))){const I=`${this.kind}${this.type}Removed`;Wo.warn(`${I}: ${JSON.stringify(l)}`),i.emit(I,l)}})),this.devices=r}hasDevice(t){return!!this.devices.find(i=>i.deviceId===t)}},EuA=class extends uuA.EventEmitter{constructor(){super(),de(this,"audioInputs",new n3($t.AUDIO,"Input")),de(this,"videoInputs",new n3($t.VIDEO,"Input")),de(this,"audioOutputs",new n3($t.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||yQ.run("interval",()=>{this.update()},{delay:1e4}))}init(){AW().then(t=>{this.audioInputs.update(t),this.videoInputs.update(t),this.audioOutputs.update(t)})}async update(t=0){const i=await AW(t);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var t;if(1e3*((t=oD())==null?void 0:t.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(r=>i.some(l=>r.label.toLowerCase().includes(l)))||this.audioInputs.devices.some(r=>i.some(l=>r.label.toLowerCase().includes(l)))}},mQ=JX||VX?null:new EuA;function p$(t){return t.deviceId===t.groupId&&t.groupId===""}async function AW(t=0){if(mV()||!C4())return[];let i=await navigator.mediaDevices.enumerateDevices();if(t!==0){const r={audio:!1,video:!1};if(i.forEach(l=>{p$(l)&&(l.kind===$t.AUDIO_INPUT?r.audio=!0:l.kind===$t.VIDEO_INPUT&&(r.video=!0))}),t===2&&(r.audio=!1),t===1&&(r.video=!1),r.audio||r.video){let l;try{l=await navigator.mediaDevices.getUserMedia(r),r.audio&&kY()}catch(I){Wo.debug("capture before getDevices failed: ",I)}i=await navigator.mediaDevices.enumerateDevices(),l?.getTracks().forEach(I=>I.stop())}}return i.map((r,l)=>{const I={kind:r.kind,deviceId:r.deviceId,groupId:r.groupId,label:r.label||`${r.kind}_${l}`};return r.deviceId.length>0&&D4.add(`${r.deviceId}_${r.kind}`),r.getCapabilities&&(I.getCapabilities=()=>r.getCapabilities()),I})}function MU(t=!1){return mQ.update(t?1:0).then(i=>i.audioInputs.devices)}function Sv(t=!1){return mQ.update(t?2:0).then(i=>i.videoInputs.devices)}var JZ=!1;async function duA(){try{JZ||(JZ=!0,Wo.info(`speakers:${(await CuA()).map(t=>` ${t.deviceId.slice(0,8)}: ${t.label}`)}`))}catch{}}async function CuA(t=!1){return(Mu||ld)&&(t=!1),mQ.update(t?1:0).then(i=>i.audioOutputs.devices)}var aY,D4=new Set;function huA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${$t.VIDEO_INPUT}`;return!!D4.has(r)}function BuA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const r=`${(t?.getSettings()||{}).deviceId}_${$t.AUDIO_INPUT}`;return!!D4.has(r)}async function QuA(t,i){const r=(await MU()).find(l=>l.deviceId===KX);return!i&&r?.groupId===t||r?.groupId===t&&r.label===i}async function puA({newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:l,kind:I}){return t===i&&(I!==$t.AUDIO||t!==KX||await QuA(r,l))}var muA=class extends cuA{constructor(t){super(),this.log=t,de(this,"volumeMeter"),de(this,"volumeMeterAfter3A"),de(this,"volumeDestination"),de(this,"analyser",new guA),this.volumeMeter=new YZ({log:this.log}),this.volumeMeterAfter3A=new YZ({log:this.log}),this.volumeDestination=new Dv,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},fuA=class extends lv{constructor(t){super(t,$t.AUDIO),de(this,"_outputDeviceId"),de(this,"_floatVolume",1),de(this,"_destination"),de(this,"pipeline"),de(this,"volumeMeterMode","worklet"),de(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new muA(this._log)}setTrack(t){}get duration(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.duration)||0))}get currentTime(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.currentTime)||0))}set currentTime(t){this.element&&(this.element.currentTime=t/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(t){if((MQ==="15.2"||MQ==="15.3"||MQ==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=aY||new Audio;i.setAttribute("autoplay","autoplay"),i.srcObject=this.getMediaStream(),i.muted=this.muted,this.url&&(i.crossOrigin="anonymous",i.src=this.url),this.element=i,this.setVolume(Gv(t)?t/100:this._floatVolume),i===aY&&(aY=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Vn.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(t){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(t?.volume),this._outputDeviceId&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(oD("player").createAnalyser()),duA()}catch(i){throw this._log.warn(`audio play error: ${i}`),O7(MQ,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(t=0){this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}async setSinkId(t){var i,r;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&await((r=(i=this.element).setSinkId)==null?void 0:r.call(i,t))}get useDestination(){return!!this.pipeline.stream}setLoop(t){this.element&&(this.element.loop=t)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},yuA=class extends fuA{constructor(t){super(t),de(this,"_sourceElement"),de(this,"_output",new Dv),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(oD().destination)}write(t){this.pipeline.volumeMeter.write(t)}setTrack(t){var i,r,l;((r=(i=this.element)==null?void 0:i.error)==null?void 0:r.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Vn.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([t]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t])),this.pipeline.source.channelCount=((l=t.getSettings())==null?void 0:l.channelCount)||1,this.pipeline.replaceSource(t)):this.pipeline.source.deleteNode())}setVolume(t){var i;const r=t<=1&&!RY();if(!(this._floatVolume===t&&(r&&((i=this.element)==null?void 0:i.volume)===t||!r&&this.pipeline.volume===t)))if(this._floatVolume=t,this.useDestination)this.pipeline.setVolume(t),this._log.info(`set pipeline volume: ${t}`);else if(r)this.element?(this._log.info(`set element volume: ${t}`),this.element.volume=t):this._log.info("set element volume: no element");else{if(RY()){if(!this.enableVolumeControlInIOS)return;auA()}if(sC&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${t}`),this.pipeline.setVolume(t),this.element&&!this._sourceElement&&(this._destination||(this._destination=oD().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),yU(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(l=>{this.emit(Vn.AUTOPLAY_FAILED,l)}))}}stop(t=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&F7&&(aY=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(t)}},S4=class extends Xn{constructor({userId:t,sdkAppId:i,mediaType:r,room:l,PlayerClass:I=r===1?yuA:Oy}){var h;super(),de(this,"id",q7()),de(this,"userId",""),de(this,"isRemote"),de(this,"mediaType"),de(this,"room"),de(this,"user"),de(this,"_log"),de(this,"_inputTrack"),de(this,"_outputTrack"),de(this,"isPlayCalled"),de(this,"container",null),de(this,"player"),de(this,"subVideoPlayerMap"),de(this,"muted",!1),de(this,"abortCtrl"),de(this,"objectFit","cover"),de(this,"mirror"),de(this,"rotation"),de(this,"isScreen",!1),de(this,"manager"),de(this,"trackSettings"),de(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=Wo.createLogger({parent:l?.getLogger(),id:`${this.kind[0]}t`,userId:(h=l||this.room)==null?void 0:h.userId,remoteUserId:this instanceof hv?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof hv}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:l?.enableVolumeControlInIOS}),this.player.on(Vn.PLAYER_STATE_CHANGED,f=>{if(ps.emit(mn.PLAYER_STATE_CHANGED,Rn({track:this},f)),this.emit("player-state-changed",f),f.state==="PLAYING"&&this.room){let w=!0;for(const{remoteAudioTrack:_,remoteVideoTrack:G,remoteAuxiliaryTrack:U}of[...this.room.remotePublishedUserMap.values()])if(_.isAvailable&&!_.player.isPlaying||G.isAvailable&&!G.player.isPlaying||U.isAvailable&&!U.player.isPlaying){w=!1;break}w&&DU()&&iuA()}}),this.kind===$t.VIDEO&&(this.player.on(Vn.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Vn.LOADED_DATA),ps.emit(mn.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Vn.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Vn.LOADED_META_DATA)}),this.player.on(Vn.MEDIA_TRACK_CHANGED,f=>{var w;(w=this.subVideoPlayerMap)==null||w.forEach(_=>_.setTrack(f))}),this.player.on(Vn.RESIZE,f=>{this.emitFirstVideoFrameEvent(Vn.RESIZE),this.emit("video-size-changed",Rn({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},f))}),this.player.on(Vn.FIRST_FRAME_RENDER,f=>{this.emit("first-frame-render",nB(Rn({},f),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Vn.ERROR,this.onPlayerError.bind(this)),this.player.on(Vn.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||Wo}get kind(){return this.mediaType===1?$t.AUDIO:$t.VIDEO}get isAudio(){return this.kind===$t.AUDIO}get strMediaType(){return this.mediaType===4?$t.VIDEO:this.mediaType===2?$t.SCREEN:$t.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}async play(t,i){const r=Ah(t)?t[0]:t;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!$n(i.muted)&&this.setPlayerMute(i.muted),i&&!$n(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof Oy&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(Ah(t)&&t.length>=1&&this.container&&t.includes(this.container)&&this.container.contains(this.player.elementToRender)?(t.splice(t.indexOf(this.container),1),t.unshift(this.container)):(this.container=r,this.player.setContainer(r))),Ah(t)&&t.length>=1&&await this.playSubContainer(t.slice(1),i)));if(i&&!$n(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==$t.VIDEO||this.setPlayerMute(!0),i&&!$n(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Oy&&($n(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!$n(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,r&&(this.container=r,this.player instanceof Oy&&this.player.setContainer(r)),ps.emit(mn.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(`play with options: ${JSON.stringify(i)}`);try{this.player.setTrack(this.playerMediaTrack),await this.player.play(i),Ah(t)&&t.length>1&&await this.playSubContainer(t.slice(1),i)}catch(l){throw this.handleAutoPlayFailed(l),l}}else this.log.info("play has not mediaTrack, abort")}setMirror(t,i){if(this.isScreen||this.kind!==$t.VIDEO||$n(t)||t===this.mirror)return;this.mirror=t;let r=this.player;i&&(r=i);const l=this.manager;if(fv(this.mirror))return r.setViewMirror(this.mirror),void(!this.isRemote&&l&&(l.mirror=!1));switch(this.mirror){case"view":l&&(l.mirror=!1),r.setViewMirror(!0);break;case"publish":l&&(l.mirror=!0),r.setViewMirror(!0);break;case"both":l&&(l.mirror=!0),r.setViewMirror(!1)}}async playSubContainer(t,i){if(!this._outputTrack||this.kind===$t.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((l,I)=>{var h;t.find(f=>I===f)||(l.stop(),(h=this.subVideoPlayerMap)==null||h.delete(I))});for(const[l,I]of t.entries()){const h=this.subVideoPlayerMap.get(I);h?i&&($n(i.objectFit)||h.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(I,new Oy({id:this.userId||this.id,track:this.playerMediaTrack,container:I,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${l+1}`})}))}const r=[...this.subVideoPlayerMap.values()];for(const l of r)l.setViewMirror(this.player.mirror),await l.play()}setAudioOutput(t){return this.player.setSinkId(t)}setAudioVolume(t){this.player.setVolume(t)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var t;return((t=this.player)==null?void 0:t.getInternalAudioLevel())||0}stop(t=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(Wj(this)&&!t?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var t;this.isPlayCalled&&await((t=this.player)==null?void 0:t.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(t){this.muted=t,this._inputTrack&&(this._inputTrack.enabled=!t),this._outputTrack&&(this._outputTrack.enabled=!t),this.emit(t?"mute":"unmute",this),ps.emit(t?mn.TRACK_MUTED:mn.TRACK_UNMUTED,{track:this})}setPlayerMute(t){this.player.setMuted(t)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(t){f4(t,t).add($t.MUTE,this.onTrackMuted).add($t.UNMUTE,this.onTrackUnmuted).add($t.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===$t.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){yU(t)}setInputMediaStreamTrack(t){var i;const r=this._inputTrack;if(t!==r)return this._inputTrack=t,this.trackSettings=(i=t.getSettings)==null?void 0:i.call(t),t.enabled=!this.muted,r&&this.uninstallTrackEvent(r),this.installTrackEvent(t),this.emit("input-media-track-changed",t||null,r||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(t)}setOutputMediaStreamTrack(t){var i;const r=this._outputTrack;this instanceof DV&&$W(r)||t!==r&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",t.label):this.log.info("setOutputMediaStreamTrack",(i=t.getSettings)==null?void 0:i.call(t).deviceId,t.label),this._outputTrack=t,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!t),this.emit("output-media-track-changed",t))}setMediaType(t){this.mediaType=t}updatePlayingState(t){var i,r;if(this.isPlayCalled){if(t){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(l=>this.handleAutoPlayFailed(l)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return Wj(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted)?void 0:(this.player.stop(Wj(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${t} ${this.player.isStopped}`)}async handleAutoPlayFailed(t){var i;this.log.warn("handleAutoPlayFailed",t);const r=()=>{this.resume().then(()=>{document.removeEventListener("click",r,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((CT||VU)&&(await rT(100),(i=this.player)==null?void 0:i.isPlaying))return;tuA()}else document.addEventListener("click",r,!0);ps.once(mn.LOCAL_TRACK_CAPTURE_SUCCESS,({track:l})=>{l.kind==="audio"&&DU()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&r()}),this.emit("error",t)}getVideoFrame(){return this.player instanceof Oy?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(t){var i,r,l;if(this.isFirstVideoFrameEmitted)return;const I=(i=this.mediaTrack)==null?void 0:i.getSettings();let h=I?.width||((r=this.player.element)==null?void 0:r.videoWidth)||0,f=I?.height||((l=this.player.element)==null?void 0:l.videoHeight)||0;(t!==Vn.RESIZE||h||f)&&(t!==Vn.LOADED_META_DATA||h||f)&&(t!==Vn.LOADED_DATA||h||f||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,a7(this.rotation)&&([h,f]=[f,h]),this.emit("first-video-frame",{width:h,height:f,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};Cc([Du([],Xn.INIT,{sync:!0})],S4.prototype,"_toInitState");var DuA=Object.prototype.hasOwnProperty;function SuA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(nT(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(DuA.call(t,i))return!1;return!0}return!1}var LY=SuA,MuA=async function(t){const i=RuA(t);Wo.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let r=[],l=[];const I=["label","deviceId","groupId"];if(i.audio&&(r=await MU(),Wo.info(`microphones: ${Zy(r.map(h=>nB(Rn({},h),{groupId:h.groupId.substring(0,8)})),{keysToInclude:I})}`)),i.video&&(l=await Sv(),Wo.info(`cameras: ${Zy(l,{keysToInclude:I})}`),!fv(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const h=l.filter(f=>!f.label.includes("infrared")).find(f=>f.label.includes("facing front"));h&&(i.video.deviceId=h.deviceId,Wo.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const h=await navigator.mediaDevices.getUserMedia(i);return r$&&h.getTracks().forEach(f=>{var w;const _=f.getCapabilities();Wo.info(`${f.kind} capabilities: ${Zy(_,{keysToInclude:jX})}`),$n(t.echoCancellation)||((w=_.echoCancellation)==null?void 0:w.indexOf(t.echoCancellation))!==-1||Wo.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(_.echoCancellation)}], but received '${t.echoCancellation}'`)}),i.audio&&kY(),h}catch(h){let{message:f}=h;throw h.name==="NotFoundError"&&(t.video&&l&&l.length===0&&(f=GY({key:NY.CAMERA_NOT_FOUND})),t.audio&&r&&r.length===0&&(f=GY({key:NY.MICROPHONE_NOT_FOUND}))),new ml({code:qg.INITIALIZE_FAILED,name:h.name,message:f,constraint:h.constraint})}},vuA=A4({retryFunction:MuA,settings:{retries:3,timeout:500},onError:({error:t,retry:i,reject:r,retryFuncArgs:l,retriedCount:I})=>{const h=I+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(h===1?(l[0].video&&(l[0].maxResolution=!1,(!ld||l[0].width*l[0].height<=2073600)&&l[0].frameRate&&(l[0].frameRate=l[0].frameRate>10?10:5)),l[0].retryWhenExactFailed&&l[0].useExactDeviceId&&(l[0].useExactDeviceId=!1)):h===2?l[0].useDeviceIdOnly=!0:h!==3||l[0].useExactDeviceId||(l[0].useTrueAsConstraint=!0),i()):r(t),l[0].microphoneId&&HZ(l[0].microphoneId,!1),l[0].cameraId&&HZ(l[0].cameraId,!0)},onRetrying:t=>{Wo.warn(`getUserMedia NotReadableError observed, retrying [${t}/3]`)},onRetryFailed:t=>{oh.logFailedEvent({eventType:tU.GET_USER_MEDIA_RETRY,error:t})},onRetrySuccess:t=>{oh.logSuccessEvent({eventType:tU.GET_USER_MEDIA_RETRY}),oh.uploadEvent({log:`stat-${tU.GET_USER_MEDIA_RETRY}-success-${t}`})}});async function HZ(t,i){const r=(i?await Sv():await MU()).find(l=>l.deviceId===t);r&&mv(r.getCapabilities)&&Wo.warn(Zy(r.getCapabilities(),{keysToInclude:jX}))}function RuA(t){return{audio:wuA(t),video:_uA(t)}}function wuA(t){if(!t.audio)return!1;if(t.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:t.sampleRate};return!LY(t.microphoneId)&&(i.deviceId=t.useExactDeviceId?{exact:t.microphoneId}:t.microphoneId,t.useDeviceIdOnly)?i:(Gv(t.channelCount)&&(i.channelCount=t.channelCount),(fv(t.echoCancellation)||t.echoCancellation==="remote-only"||t.echoCancellation==="all")&&(i.echoCancellation=t.echoCancellation),fv(t.noiseSuppression)&&!t.noiseSuppression&&(i.noiseSuppression=!1),fv(t.autoGainControl)&&!t.autoGainControl&&(i.autoGainControl=!1),!!LY(i)||i)}function _uA(t){if(!t.video)return!1;if(t.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=t,r={};return t.cameraId?r.deviceId=t.useExactDeviceId?{exact:t.cameraId}:t.cameraId:t.facingMode&&(r.facingMode=t.facingMode),t.useDeviceIdOnly&&!LY(r)?r:(t.width&&(r.width={ideal:t.width},i&&!sC&&(r.width.max=t.width)),t.height&&(r.height={ideal:t.height},i&&!sC&&(r.height.max=t.height)),sC&&QV&&t.width&&t.height&&t.width*t.height<101376&&(r.width=t.width,r.height=t.height),t.frameRate&&(r.frameRate=t.frameRate),!!LY(r)||r)}var TuA=vuA;function m$(t){return yV((i,r)=>async function(...l){const I=await i.apply(this,l);return await t.call(this,...l),I})}function yV(t){return function(i,r,l){return l.value=t(l.value,r),l}}var NuA=(()=>{let t=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&Wo.info(`visibility change: ${document.visibilityState}`),t||(document.addEventListener("visibilitychange",()=>{Wo.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),t=!0)}})(),GuA=0,buA=class{constructor(t){de(this,"log"),de(this,"isRunning",!1),de(this,"queue",[]);let i="fq"+ ++GuA;t&&(i+=`|${t}`),this.log=Wo.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,i=!1){var r,l;const I=Rn({},t),h=new Promise((f,w)=>{I.resolve=f,I.reject=w});return I.promise=h,i?this.length<=1?this.queue.push(I):(l=(r=this.lastQueueItem)==null?void 0:r.promise)==null||l.then(I.resolve,I.reject):this.queue.push(I),this.log.debug(`push ${this.length}`,t.funcName,t.args),this.isRunning||this.callNext(),h}shift(){const t=this.queue.shift();return this.log.debug(`shift ${this.length}`,t?.funcName,t?.args),t}callNext(){if(this.isRunning||this.length===0)return;const{fn:t,args:i,context:r,resolve:l,reject:I,funcName:h}=this.queue[0];this.log.debug("callNext",this.length,h,i),this.isRunning=!0,t.apply(r,i).then(l,I).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},qZ=new WeakMap;function kuA(t=!1){return function(i,r,l){const I=l.value;return l.value=function(...h){const f=qZ.get(this)||new buA;return qZ.set(this,f),f.push({fn:I,args:h,context:this,funcName:r},t)},l}}function f$(t,i){return yV((r,l)=>function(...I){const h=t;try{const f=r.apply(this,I),w=Yc();return $X(f)?f.then(_=>(i?Ir.addSuccessEvent({key:h,cost:Yc()-w}):Ir.addSuccessEvent({key:h}),_)).catch(_=>{throw Ir.addFailedEvent({key:h,error:_}),_}):(Ir.addSuccessEvent({key:h}),f)}catch(f){throw Ir.addFailedEvent({key:h,error:f}),f}})}function $l(...t){}var LuA=t=>t();function UuA(){this.dispose()}var FuA=()=>typeof __FASTRX_DEVTOOLS__<"u",OuA=1,aT=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const i=new xuA(t,this,this.streamId++);return Ql.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},M4=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=$l,this.error=$l,this.next=$l,this.dispose=$l,this.subscribe=$l,this.doDefer()}subscribe(t){return t instanceof aT?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(LuA),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},aB=class extends M4{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},PuA=class extends M4{constructor(t,i=$l,r=$l,l=$l){if(super(),this._next=i,this._error=r,this._complete=l,this.then=$l,t instanceof aT){const I={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{Ql.defer(I,0)}),Ql.create(I),Ql.pipe(I),this.sourceId=I.id,this.subscribe(t),Ql.subscribe({id:I.id,end:!0}),i==$l?this._next=h=>Ql.next(I,0,h):this.next=h=>{Ql.next(I,0,h),i(h)},l==$l?this._complete=()=>Ql.complete(I,0):this.complete=()=>{this.dispose(),Ql.complete(I,0),l()},r==$l?this._error=h=>Ql.complete(I,0,h):this.error=h=>{this.dispose(),Ql.complete(I,0,h),r(h)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function $C(t,...i){return i.reduce((r,l)=>l(r),t)}function nC(t,i,r){if(FuA()){const l=Object.defineProperties(Object.setPrototypeOf(t,aT.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:r,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});Ql.create(l);for(let I=0;I{if(l instanceof aT){const I=nC(h=>{const f=new t(h,...r);f.sourceId=I.id,f.subscribe(l)},i,arguments);return I.source=l,Ql.pipe(I),I}return I=>l(new t(I,...r))}}}function Ty(t,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:t,payload:i}})}var xuA=class extends aB{constructor(t,i,r){super(t),this.source=i,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{Ql.defer(this.source,this.id)})}next(t){Ql.next(this.source,this.id,t),this.sink.next(t)}complete(){Ql.complete(this.source,this.id),this.sink.complete()}error(t){Ql.complete(this.source,this.id,t),this.sink.error(t)}},Ql={addSource(t,i){Ty("addSource",{id:t.id,name:t.toString(),source:{id:i.id,name:i.toString()}})},next(t,i,r){Ty("next",{id:t.id,streamId:i,data:r&&r.toString()})},subscribe({id:t,end:i},r){Ty("subscribe",{id:t,end:i,sink:{nodeId:r&&r.nodeId,streamId:r&&r.streamId}})},complete(t,i,r){Ty("complete",{id:t.id,streamId:i,err:r?r.toString():null})},defer(t,i){Ty("defer",{id:t.id,streamId:i})},pipe(t){Ty("pipe",{name:t.toString(),id:t.id,source:{id:t.source.id,name:t.source.toString()}})},update(t){Ty("update",{id:t.id,name:t.toString()})},create(t){t.id||(t.id=OuA++),Ty("create",{name:t.toString(),id:t.id})}},YuA=class extends M4{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(i=>i.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(i=>i.error(t)),this.sinks.clear()}};function y$(){return t=>{const i=new YuA(t);if(t instanceof aT){const r=nC(l=>{i.add(l)},"share",arguments);return i.sourceId=r.id,r.source=t,Ql.pipe(r),r}return nC(i.add.bind(i),"share",arguments)}}function D$(...t){return nC(i=>{const r=new aB(i);let l=t.length;r.complete=()=>{--l===0&&i.complete()},t.forEach(r.bindSubscribe)},"merge",arguments)}function VuA(...t){return nC(i=>{const r=new Map;t.forEach(l=>{const I=new aB(i);r.set(l,I),I.complete=()=>{r.delete(l),r.size===0?i.complete():I.dispose()},I.next=h=>{r.delete(l),r.forEach(f=>f.dispose()),I.resetNext(),I.resetComplete(),I.next(h)}}),t.forEach(l=>r.get(l).subscribe(l))},"race",arguments)}function JuA(...t){return i=>nC((r,l=0,I=t.length)=>{for(;l{r.next=I=>l.next(I),r.complete=()=>l.complete(),r.error=I=>l.error(I),t&&l.subscribe(t)},"subject",i));return r.next=$l,r.complete=$l,r.error=$l,r}function HuA(t){return nC(i=>{let r=0;const l=setInterval(()=>i.next(r++),t);return i.defer(()=>{clearInterval(l)}),"interval"},"interval",arguments)}function quA(t,i){return nC(r=>{let l=0;const I=setTimeout(()=>{r.removeDefer(h),r.next(l++),i||r.complete()},t),h=()=>clearTimeout(I);r.defer(h)},"timer",arguments)}function r3(t,i){return r=>{const l=I=>r.next(I);r.defer(()=>i(l)),t(l)}}function fE(t,i){if("on"in t&&"off"in t)return nC(r3(r=>t.on(i,r),r=>t.off(i,r)),"fromEvent",arguments);if("addListener"in t&&"removeListener"in t)return nC(r3(r=>t.addListener(i,r),r=>t.removeListener(i,r)),"fromEvent",arguments);if("addEventListener"in t)return nC(r3(r=>t.addEventListener(i,r),r=>t.removeEventListener(i,r)),"fromEvent",arguments);throw"target is not a EventDispachter"}function KuA(){return nC(t=>t.complete(),"empty",arguments)}var juA=class extends aB{constructor(t,i,r){super(t),this.filter=i,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},$_=Uv(juA,"filter"),WuA=class extends aB{constructor(t,i){super(t),this.count=i}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},zuA=Uv(WuA,"take"),ZuA=class extends aB{constructor(t,i){super(t);const r=new aB(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=UuA,r.subscribe(i)}},gT=Uv(ZuA,"takeUntil"),XuA=class extends aB{constructor(t,i){super(t),this.f=i}next(t){this.f(t)||(this.next=super.next,this.next(t))}},$uA=Uv(XuA,"skipWhile"),AEA=class extends aB{constructor(t,i,r){super(t),this.mapper=i,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},M$=Uv(AEA,"map"),eEA=class extends aB{constructor(t,i,r){super(t),this.data=i,this.context=r}next(t){const i=this.context.combineResults;i?this.sink.next(i(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},tEA=class v$ extends aB{constructor(i,r,l){super(i),this.makeSource=r,this.combineResults=l,this.index=0}subInner(i,r){const l=this.currentSink=new r(this.sink,i,this);this.complete===v$.prototype.complete&&(this.complete=this.tryComplete),l.complete=l.tryComplete,l.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},KZ=class extends eEA{},R$=class extends tEA{next(t){this.subInner(t,KZ),this.next=i=>{this.currentSink.dispose(),this.subInner(i,KZ)}}},iEA=Uv(R$,"switchMap");function oEA(t){return(i,r)=>t(()=>i,r)}var w$=oEA(Uv(R$,"switchMapTo")),kv=(t=$l,i=$l,r=$l)=>l=>new PuA(l,t,i,r),_$=(t=>(t[t.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",t[t.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",t))(_$||{}),hv=class extends S4{constructor(t,i){super({mediaType:t,PlayerClass:i}),de(this,"isRemote",!1),de(this,"deviceId"),de(this,"groupId",""),de(this,"label",""),de(this,"sourceTrack"),de(this,"enableAutoSwitchWhenRecapturing",!0),de(this,"_isRecapturing",!1),de(this,"_lastRecaptureTime",0),de(this,"_onMuteTimeoutId",-1),de(this,"_encodeCheckTimeoutId",-1),de(this,"recaptureMode",0),de(this,"profile"),de(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(t,i){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener($t.MUTE,this.onTrackMuted),t.addEventListener($t.UNMUTE,this.onTrackUnmuted),t.addEventListener($t.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===$t.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener($t.MUTE,this.onTrackMuted),t.removeEventListener($t.UNMUTE,this.onTrackUnmuted),t.removeEventListener($t.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(t,i=!1){var r,l;const I=this.sourceTrack;try{const h=Yc();let f;ps.emit(mn.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(f=new MediaStream,f.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),f=await TuA(t));const w=f.getTracks()[0];return await this.setInputMediaStreamTrack(w),t.customSource||(this.sourceTrack=w,this.updateDeviceIdInUse(),this.listenDeviceChange()),ps.emit(mn.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Yc()-h,profile:this.profile,room:(l=this.manager)==null?void 0:l.room}),f}catch(h){throw ps.emit(mn.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:h}),this.log.error(`getUserMedia error observed ${h}`),h}finally{i&&I?.stop()}}setOutputMediaStreamTrack(t){var i;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var t,i;const r=e7(((t=this.room)==null?void 0:t.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&r.hasVideo||this.mediaType===1&&r.hasAudio||this.mediaType===2&&r.hasAuxiliary}async publish(t,i){return this.room=t,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=t.userId,this._log.bindParent(t.getLogger()),await i,this._checkPublishFlag(t)}_checkPublishFlag(t){return new Promise(async(i,r)=>{var l,I,h,f,w;const _=()=>r(new ml({code:qg.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==Xn.INIT&&this.state!=="ready"||_(),$C(fE(t,"local-publish-flag-changed"),$_(()=>this.hasFlag),gT(D$(fE(this,Xn.INIT),fE(this,"ready"))),kv(i,r,_))),(h=(I=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:I.hadRecentBadUplink)==null?void 0:h.call(I,2))return i();const G=t.heartbeatCount,U=((w=(f=this.mediaTrack)==null?void 0:f.stats)==null?void 0:w.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var j,lA,sA,mA,IA,cA,TA,WA;if((sA=(lA=(j=this.room)==null?void 0:j.networkQuality)==null?void 0:lA.hadRecentBadUplink)!=null&&sA.call(lA,2)||t.heartbeatCount-G<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((mA=this.mediaTrack)!=null&&mA.stats){const xe=this.mediaTrack.stats.totalFrames||0;xe-U===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",xe)}const ue=this.kind===$t.AUDIO,Ce=this.stat.bytesSent>0;if(Ir[Ce?"addSuccessEvent":"addFailedEvent"]({key:ue?503700:513702}),!ue){const xe={H264:513704,H265:513705,VP8:513706}[((cA=(IA=this.room)==null?void 0:IA.videoCodec)==null?void 0:cA.toUpperCase())||"H264"];xe&&Ir[Ce?"addSuccessEvent":"addFailedEvent"]({key:xe})}if(!Ce){if(Ir.addEnum({key:ue?503701:513703,value:u4()}),oh.uploadEvent({log:`stat-encode-failed-${this.kind}-${P7()||Y7()}`,userId:this.userId}),this.log.warn(ue?"encode failed":`${(WA=(TA=this.room)==null?void 0:TA.videoCodec)==null?void 0:WA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await rT(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new ml({message:`${this.strMediaType} encode failed`,code:ue?qg.AUDIO_ENCODE_FAILED:qg.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),ps.emit(mn.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&bY){const{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;await puA({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=t,this.label=r,i&&(this.groupId=i),AW().then(l=>{const I=l.find(h=>{let f=h.deviceId===t;return i&&(f=f&&h.groupId===i),f});I&&this.emit("2",I)}))}}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(t=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===$t.AUDIO&&!BuA(this.sourceTrack)||this.kind===$t.VIDEO&&!huA(this.sourceTrack)||this._isRecapturing||t&&QV&&ld)}onTrackMuted(){super.onTrackMuted(),NuA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),O1):this._onMuteTimeoutId=setTimeout(async()=>{var t;if((t=this.sourceTrack)!=null&&t.muted){if((Mu||aC)&&document.visibilityState!=="visible")return;this.recapture(await this.getRecoverCaptureDeviceId())}},5e3))}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}async onTrackEnded(){if(super.onTrackEnded(),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),O1);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(t,i=!1){var r;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const l=this.sourceTrack;i||(r=this.sourceTrack)==null||r.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const I={useExactDeviceId:!0};if(t==="user"||t==="environment")I.facingMode=t;else{let h;(this.kind==="audio"?await MU():await Sv()).find(f=>f.deviceId===t)&&(h=t),I.deviceId=h}return this.capture(I,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),ps.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(h=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${h.message}`),this.emit("5",h),ps.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this,error:h})}).finally(()=>{i&&l?.stop()})}async getRecoverCaptureDeviceId(){const t=this instanceof DV;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const r=(OL.get(i)||0)+1;if(OL.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){const l=t?(await Sv()).find(I=>!OL.has(I.deviceId)):(await MU()).find(I=>!OL.has(I.deviceId));l&&(this.log.warn(`${i} capture fail ${r} times, change new ${l.deviceId}`),i=l.deviceId)}}return i}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),ps.emit(mn.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};Cc([Du(Xn.INIT,"ready",{ignoreError:!0,sync:!0})],hv.prototype,"setStateToReady"),Cc([kuA()],hv.prototype,"capture"),Cc([Du("ready","publish",{ignoreError:!0,success(){ps.emit(mn.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(t){var i;(i=this.room)==null||i.localTracks.delete(this);let r="error";const l=t instanceof ml?t:t.cause instanceof ml?t.cause:t;let I=!1;l instanceof ml&&(l.message.includes("timeout")?r="timeout":l.code===qg.API_CALL_ABORTED&&(I=!0,r="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:l}),this.log[I?"info":"error"]("publish failed",l)}}),f$(521714,!1)],hv.prototype,"publish"),Cc([yV(t=>async function(){const i=this.state==="publish"?"started":"starting";t.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),Du([],"ready",{sync:!0})],hv.prototype,"unpublish");var OL=new Map;ps.on(mn.SWITCH_DEVICE_SUCCESS,t=>{t.track.deviceId&&OL.delete(t.track.deviceId)});var sEA=class{constructor(t,i=!1){this.dataView=t,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-2,r=[];let l=0;for(let h=t;h<=i;h++){const f=this.dataView.getInt8(h);switch(f){case 0:case 1:case 2:case 3:l===2&&(r.push(3),l=0),f===0?l+=1:l=0,r.push(f);break;default:l=0,r.push(f)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=I}removePreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-1,r=[];let l=0;for(let h=t;h<=i;h++)switch(this.dataView.getInt8(h)){case 0:l++,r.push(this.dataView.getInt8(h));break;case 3:l!==2&&r.push(this.dataView.getInt8(h)),l=0;break;default:r.push(this.dataView.getInt8(h)),l=0}const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=I}get seiPayloadStartIndex(){let t=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(t)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},nEA=class{constructor(){de(this,"_seiMessageList",[]),de(this,"_smallSeiMessageList",[]),de(this,"_seiPayloadType",243)}encodeSEINalu(t){const i=t.byteLength,r=parseInt(String(i/255),10),l=i%255,I=[];I.push(0,0,0,1,6,this._seiPayloadType);for(let f=0;f0&&t.data.byteLength>0){const l=9-this.getNaluCount(t.data);if(l<=0)return 0;const I=r.splice(0,l).reverse().map(this.encodeSEINalu.bind(this)),h=I.reduce((U,j)=>U+j.dataView.byteLength,0),f=new ArrayBuffer(h+t.data.byteLength),w=new DataView(f),_=new DataView(t.data);let G=0;for(let U=0;U{var l;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const I=MY(((l=this.room)==null?void 0:l.sdkAppId)||0)?nZ:sZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${I}`),this.setProfile(nB(Rn({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",r),this.on("publish",r),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(bY&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)||""}get isQosClearFirst(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)==="detail"}get hasSmall(){var t;return!!((t=this.manager)!=null&&t.hasSmall)}async setMute(t){var i,r,l;if(ih(t)){if(this.muteImage===t)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((r=this.manager)==null?void 0:r.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0})),this.muteImage=t,super.setMute(!1)}else this.muteImage&&(await((l=this.manager)==null?void 0:l.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(t)}async capture({deviceId:t,facingMode:i,useExactDeviceId:r=!0,customSource:l,retryWhenExactFailed:I=!0}){const h={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:r,retryWhenExactFailed:I,customSource:l};if(h.facingMode==="environment"){const f=await this.getDeviceIdWhenUsingBackCamera();f&&(h.cameraId=f)}return super.capture(h)}setProfile(t){var i;const r=this.fallbackProfile(t);if(r.bitrate&&(this.isNeedToSetBandwidth=r.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(r);else{const l=MY(((i=this.room)==null?void 0:i.sdkAppId)||0)?nZ:sZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${l}`),super.setProfile(nB(Rn({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var t,i;if(!this.mediaTrack)return;const{width:r=0,height:l=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=r*l,h=this.settings,f=h.height!==this.profile.height||h.width!==this.profile.width||h.frameRate!==this.profile.frameRate;if(f&&(bv===16&&this.deviceId?await this.recapture(this.deviceId):($W(this.outMediaTrack)?await((t=this.outMediaTrack)==null?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})):await((i=this.sourceTrack||this.mediaTrack)==null?void 0:i.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;const{width:w=0,height:_=0}=(this.sourceTrack||this.mediaTrack).getSettings(),G=w*_;return f&&G&&I&&G===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:$t.VIDEO,videoType:$t.BIG})}}get settings(){const t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return bY&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:r7(this.settings,this.profile)}isAllowed2k4k(t){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||t.height*t.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}async switchDevice(t){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?i.facingMode=t:i.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),ps.emit(mn.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(i){throw this.log.error(`switch camera failed ${i}`),this.deviceId&&this.recapture(this.deviceId),i}}async getDeviceIdWhenUsingBackCamera(){let t;try{if(T7&&!l4&&a$){const i=(await Sv(!0)).map(l=>{var I;return nB(Rn({},l),{capabilities:(I=l.getCapabilities)==null?void 0:I.call(l)})}).filter(l=>{var I,h;return(h=(I=l.capabilities)==null?void 0:I.facingMode)==null?void 0:h.includes("environment")});let r=i[0];i.forEach(l=>{var I,h,f,w;const{capabilities:_}=l;((I=_.width)!=null&&I.max&&((h=_.height)!=null&&h.max)?_.width.max*_.height.max:0)>((f=r.capabilities.width)!=null&&f.max&&((w=r.capabilities.height)!=null&&w.max)?r.capabilities.width.max*r.capabilities.height.max:0)&&(r=l)}),r?.capabilities&&(this._log.info("use max resolution back camera",r),t=r.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return t}async updateSmallConfig(t){var i,r;this._log.info(`update small stream config: ${JSON.stringify(t)}`);const l=!this.small;this.small=this.fallbackProfile(t,!0),await((i=this.manager)==null?void 0:i.update()),l&&await((r=this.room)==null?void 0:r.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(t,i=!1){const r=t.width>t.height,l=Rn({},t);return t.width*t.height<=19200&&aC&&tD&&(this.log.warn(`${i?"small ":""}resolution is ${t.width}*${t.height}, fallback to 240*180 for android chrome`),l.width=r?240:180,l.height=r?180:240,l.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&XlA&&(l.width=r?1280:720,l.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),zlA(MQ,"14.3")&&O7(MQ,"14.0",!0)&&this.on("7",()=>{const I=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=I?640:480,this.profile.height=I?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=I?640:360,this.profile.height=I?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(tD||sC)&&!eIA()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,l.width=1280,l.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),l}stopSmall(){var t,i;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){mQ&&!mQ.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&mQ.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(t){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${_$[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(t)}`),this.recaptureMode===0){Ec(this.userId,{eventId:2003,param1:7,streamType:2});const r=await Sv();r[0]?this.recapture(r[0].deviceId):i=!0}i&&mQ.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(mQ.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(t)}`),this.recapture(t.deviceId))}encodeFrame(t,i){if(!this.manager)return t;const r=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((l,I)=>I?I({frame:l,mediaType:r}):l,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,i){return $n(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){mQ.off("videoInputAdded",this.handleCameraAdded,this),mQ.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(t){try{await super.recapture(t)}catch(i){const r=(await Sv()).find(l=>l.deviceId!==t);if(!r)throw i;await super.recapture(r.deviceId)}}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info(`setContentHint ${t}`),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||$n(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};Cc([m$(function(t){this.setContentHint(t.contentHint||"motion")})],DV.prototype,"capture");var rEA=[-1,-1,1,-1,-1,1,1,1],aEA=[0,0,1,0,0,1,1,1],PL=class eW extends Xn{constructor(i,r){if(super(),this.context=i,de(this,"name"),de(this,"input"),de(this,"output"),de(this,"texture"),de(this,"ctx2d",null),de(this,"fbo"),de(this,"width",0),de(this,"height",0),de(this,"x",0),de(this,"y",0),de(this,"program"),de(this,"vertexShader"),de(this,"fragmentShader"),de(this,"totalFrames",0),de(this,"dropFrames",0),de(this,"matchInputSize",!0),de(this,"texCoordBuffer"),de(this,"positionBuffer"),de(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),de(this,"cost",0),de(this,"_canvas",null),de(this,"_image"),de(this,"log"),this.context.on("disconnect",this.close,this),this.name=r.name,this.log=r.logger,this.matchInputSize=r.matchInputSize!==!1,this.width=r.width||i.width,this.height=r.height||i.height,this._image=r.image,i instanceof RU)i.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&bv!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{const l=i.ctx;this.texCoordBuffer=this.createBuffer(aEA),this.positionBuffer=this.createBuffer(rEA),r.createTexture!==!1&&(this.texture=l.createTexture(),this.useTexture(),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_MIN_FILTER,l.LINEAR),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_MAG_FILTER,l.LINEAR),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_S,l.CLAMP_TO_EDGE),l.texParameteri(l.TEXTURE_2D,l.TEXTURE_WRAP_T,l.CLAMP_TO_EDGE),l.pixelStorei(l.UNPACK_ALIGNMENT,1)),r.useFbo&&(this.fbo=l.createFramebuffer(),this.useBufferFrame(),this.useTexture(),l.texImage2D(l.TEXTURE_2D,0,l.RGBA,this.width,this.height,0,l.RGBA,l.UNSIGNED_BYTE,null),l.framebufferTexture2D(l.FRAMEBUFFER,l.COLOR_ATTACHMENT0,l.TEXTURE_2D,this.texture,0)),r.useDefaultProgram?this.program=i.defaultProgam:(r.vertexShaderSource||r.fragmentShaderSource)&&(this.vertexShader=r.vertexShaderSource?i.createShader(l.VERTEX_SHADER,r.vertexShaderSource):i.defaultVShader,this.fragmentShader=r.fragmentShaderSource?i.createShader(l.FRAGMENT_SHADER,r.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(l){this.context.destroy(new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${l.message||l}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const r=this.context.ctx,l=r.createFramebuffer();return r.bindFramebuffer(r.FRAMEBUFFER,l),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,i,0),l}connect(i,...r){return i.addInput(this,...r),this.output=i,i}addInput(i,...r){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const r=Date.now();return!!(this.context instanceof tW&&this.render(i)||this.context instanceof RU&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-r,!0)}render2d(i){var r;return!!((r=this.input)!=null&&r.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var r;(r=this.output)==null||r.update(i)}disconnect(...i){var r;(r=this.output)==null||r.removeInput(this,...i),delete this.output}removeInput(i,...r){delete this.input}close(){var i,r;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(r=this.input)==null||r.disconnect(),this.context instanceof tW){const l=this.context.ctx;l.deleteBuffer(this.texCoordBuffer),l.deleteBuffer(this.positionBuffer),this.fbo&&l.deleteFramebuffer(this.fbo),this.texture&&l.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&l.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&l.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&l.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var i;this.useTextures((i=this.input)==null?void 0:i.texture)}useTextures(...i){const r=this.context.ctx;i.forEach((l,I)=>{l&&(r.activeTexture(r.TEXTURE0+I),r.bindTexture(r.TEXTURE_2D,l))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const r=this.context.ctx,l=r.createBuffer();return r.bindBuffer(r.ARRAY_BUFFER,l),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW),l}setTexBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.texCoordBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}setPosBuffer(i){const r=this.context.ctx;r.bindBuffer(r.ARRAY_BUFFER,this.positionBuffer),r.bufferData(r.ARRAY_BUFFER,new Float32Array(i),r.STATIC_DRAW)}changeBufferData(i,r){const l=this.context.ctx;l.bindBuffer(l.ARRAY_BUFFER,i),l.bufferData(l.ARRAY_BUFFER,new Float32Array(r),l.STATIC_DRAW)}setAttributes(...i){const r=this.context.ctx;i.forEach((l,I)=>{r.enableVertexAttribArray(I),r.bindBuffer(r.ARRAY_BUFFER,l),r.vertexAttribPointer(I,2,r.FLOAT,!1,0,0)})}getVertexPoint(i,r){return[i/this.width*2-1,r/this.height*2-1]}layout2texCoords(i){return[...this.getVertexPoint(i.x,i.y),...this.getVertexPoint(i.x+i.width,i.y),...this.getVertexPoint(i.x,i.y+i.height),...this.getVertexPoint(i.x+i.width,i.y+i.height)]}resize(i,r){if(this.width!==i||this.height!==r){if(this.width=i,this.height=r,this._canvas&&(this._canvas.width=i,this._canvas.height=r),this.texture&&this.fbo){this.useTexture();const l=this.context.ctx;l.texImage2D(l.TEXTURE_2D,0,l.RGBA,i,r,0,l.RGBA,l.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,r)}}draw(i,r){this.setAttributes(i||this.positionBuffer,r||this.texCoordBuffer);const l=this.context.ctx;l.drawArrays(l.TRIANGLE_STRIP,0,4)}draw2d(i,r,l,I,h,f,w,_,G){const U=!($n(f)||$n(w)||$n(_)||$n(G));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(U?this.ctx2d.putImageData(i,r,l,f,w,_,G):this.ctx2d.putImageData(i,r,l),this.emit(eW.RENDER,this.ctx2d.canvas)):(U?this.ctx2d.drawImage(i,f,w,_,G,r,l,I,h):this.ctx2d.drawImage(i,r,l,I,h),this.emit(eW.RENDER,i)),typeof VideoFrame<"u"&&i instanceof VideoFrame&&i.close(),!0)}drawBackGround2d(i){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=i,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var i;const{totalFrames:r,x:l,y:I,width:h,height:f,name:w,cost:_}=this,G=Date.now(),U=(r-this.lastInfo.totalFrames)/((G-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:r,x:l,y:I,width:h,height:f,timestamp:G,fps:U,name:w,cost:_},Rn({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const r=this.context.ctx,l=r.createTexture();return this.useTextures(l),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.LINEAR),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.pixelStorei(r.UNPACK_ALIGNMENT,1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,i),l}};de(PL,"RENDER","render"),Cc([Du(Xn.INIT,"connected",{sync:!0})],PL.prototype,"connect"),Cc([Du("connected",Xn.INIT,{ignoreError:!0,sync:!0})],PL.prototype,"disconnect"),Cc([Du([],"closed",{sync:!0})],PL.prototype,"close");var UY=PL,gEA=$C(HuA(250),M$(()=>performance.now()),y$()),cEA=t=>i=>{const r=performance.now();$C(gEA,$uA(l=>l-r{if(t!==this.context.frameRate&&(yQ.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof tW){const i=this.context.ctx.getError();i&&this.context.destroy(new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(t){var i;return!!((i=this.input)!=null&&i.requestFrame(t))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(UY.RENDER,this.context._canvas),!0)}addInput(t,...i){super.addInput(t,...i),this.start(this.context.frameRate)}update(t=0){this.state!=="closed"&&(this._intervalId&&(yQ.clearTask(this._intervalId),this._intervalId=0,t===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(t){super.removeInput(t),yQ.clearTask(this._intervalId)}resize(t,i){super.resize(t,i),this.context.setSize(t,i)}close(){super.close(),yQ.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},uEA=class extends IEA{constructor(t,i){super(t,i),de(this,"_videoTrack"),de(this,"_muteOb"),de(this,"_closedOb",fE(this,"closed")),de(this,"_subscription"),de(this,"_canvasContainer"),Number(JU)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=t.canvas.captureStream().getVideoTracks(),this._muteOb=fE(this._videoTrack,"mute"),$C(fE(this._videoTrack,"ended"),gT(this._closedOb),kv(()=>{this.context.destroy(new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=$C(this._muteOb,gT(this._closedOb),w$(cEA(5e3)),$_(()=>{var t;return!!((t=this._videoTrack)!=null&&t.muted)&&!document.hidden}),kv(()=>{this.context.destroy(new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var t;(t=this._subscription)==null||t.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){this.context._canvas&&this._canvasContainer&&(document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas)))}render(t){return this.putCanvasIntoDom(),super.render(t)}render2d(t){return this.putCanvasIntoDom(),super.render2d(t)}close(){var t,i;super.close(),(t=this._videoTrack)==null||t.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},T$=class extends UY{constructor(t,i){super(t,Rn({name:"imageSource"},i)),de(this,"_lastImage"),de(this,"_totalFrames",0),de(this,"_autoResize",!1),de(this,"_canvasRendered"),de(this,"videoCallbackId",0),de(this,"waitingFirstFrame",!0),de(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,bv===16&&(this._canvasRendered=S$(),$C(this._canvasRendered,JuA(this._image),iEA(r=>r instanceof HTMLCanvasElement?fE(r,"rendered"):KuA()),gT(fE(this,"closed")),kv(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const t=this.image;this.videoCallbackId&&t.cancelVideoFrameCallback(this.videoCallbackId),p4()&&!document.hidden&&(this.videoCallbackId=t.requestVideoFrameCallback((i,r)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=r.presentedFrames,this.update(1))}))}_render(t,i){var r;let{width:l,height:I}=this;const{image:h}=this;if(h instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:l,videoHeight:I}=h,!l||!I)return!1;h.width=l,h.height=I}else if(h instanceof HTMLImageElement||h instanceof ImageData||h instanceof ImageBitmap){if({width:l,height:I}=h,h!==this._lastImage)this._lastImage=h;else if(l===this.width&&I===this.height)return!0}else h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas?({width:l,height:I}=h,this._lastImage=h):typeof VideoFrame<"u"&&h instanceof VideoFrame&&({displayWidth:l,displayHeight:I}=h,(r=this._lastImage)==null||r.close(),this._lastImage=h);if(!this._autoResize)return!0;if(this.width===l&&this.height===I&&this.totalFrames){if(i){this.useTexture();const f=this.context.ctx;f.texSubImage2D(f.TEXTURE_2D,0,0,0,f.RGBA,f.UNSIGNED_BYTE,h)}}else{if(i){this.useTexture();const f=this.context.ctx;f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,h)}this.resize(l,I)}return!0}get image(){return this._image}set image(t){var i;(i=this._canvasRendered)==null||i.next(t),this._image=t}render(t){return this._render(t,!0)}render2d(t){return this._render(t,!1)}},N$=class extends T${constructor(t,i,r){super(t,r),this._player=i,this.name="videoPlayerSource",$C(fE(this._player,Vn.PLAYER_STATE_CHANGED),gT(fE(this,"closed")),$_(({state:l})=>l==="PLAYING"),kv(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},EEA=class extends N${get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,i,r){super(t,new Oy({id:r.name,track:i,muted:!0,container:null,objectFit:"contain",log:r.logger}),r),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}},dEA=class extends UY{constructor(t,i,r){super(t,nB(Rn({name:"textSource"},r),{create2d:!0})),de(this,"hasChange",!0),de(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(t){this.ctx2d&&(this.ctx2d.font=t,this.hasChange=!0)}get font(){var t;return((t=this.ctx2d)==null?void 0:t.font)||""}set color(t){this.ctx2d&&(this.ctx2d.fillStyle=t,this.hasChange=!0)}get color(){var t;return((t=this.ctx2d)==null?void 0:t.fillStyle)||""}render2d(t){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(t){return!1}resize(t,i){if(!this.ctx2d)return;const{color:r,font:l}=this;super.resize(t,i),this.color=r,this.font=l}drawMultilineText(t=0,i=0,r=1.2){if(!this.ctx2d)return;const l=this.ctx2d.measureText(this.content);i+=l.fontBoundingBoxAscent||l.actualBoundingBoxAscent||0;const I=this.font.match(/(\d+)px/),h=(I?parseInt(I[1],10):16)*r,f=this.content.split(` -`);for(let w=0;w":"Detail >",c.onclick=this.onCollapseClick.bind(this);const I=t.content.firstChild,C=I.querySelector(`.${Z1}`);return C.appendChild(c),C.appendChild(n),C.appendChild(i),I}addDiaLog(){GU()||(EW=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${_L}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",Wo.info("show autoplay dialog"),ah.uploadEvent({log:vuA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,EW=!1),bU=null}onConfirm(){Wo.warn("confirm clicked, try resume stream"),ms.emit(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const t=this._dialogNode.querySelector(`.${t6}`);t.style.visibility=this._showDetail?"hidden":"visible",t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||ah.uploadEvent({log:RuA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(x$,"_blank"),this._isQuestionClicked||ah.uploadEvent({log:wuA}),this._isQuestionClicked=!0}},bU=null;function NuA(){bU||(bU=new TuA)}function GuA(){bU&&bU.deleteDialog()}var hU,Yy=class extends Ev{constructor(t){super(t,ei.VIDEO),Be(this,"stat",{}),Be(this,"_calculateTimeout",-1),Be(this,"viewMirror",!1),Be(this,"objectFit","cover"),Be(this,"container"),Be(this,"canvas"),Be(this,"shouldRenderAlpha",!1),Be(this,"_preSize",{width:0,height:0}),Be(this,"posterImg"),Be(this,"pipWindow"),Be(this,"enterPIPPromise"),Be(this,"_originContainerPosition"),Be(this,"_isResettingSrcObject",!1),Be(this,"_wrapper",null),Be(this,"_useWrapper",!1),Be(this,"_isFirstFrameRenderEmitted",!1),this.mode=t.canvas?1:0,this.container=t.container,this.canvas=t.canvas,er(t.viewMirror)||(this.viewMirror=t.viewMirror),er(t.objectFit)||(this.objectFit=t.objectFit),this.initializeElement()}get isPlaying(){var t;return this._state==="PLAYING"&&(!this.element||!this.element.paused)&&((t=this.track)==null?void 0:t.readyState)==="live"&&!this.track.muted}initializeElement(){const t=document.createElement(ei.VIDEO);this.track&&this.mode!==2&&(t.srcObject=new MediaStream([this.track])),t.muted=!0,t.setAttribute("id",`video_${this.id}`),t.setAttribute("style",this.styleAttribute),this.canvas&&this.canvas.setAttribute("style",this.styleAttribute),t.setAttribute("autoplay","autoplay"),t.setAttribute("playsinline","playsinline"),this.element=t,cC&&(t.poster="data:,"),this._appendToWrapper(),this.bindElementEvents(),this.calculateStat(),this._bindFirstFrameRenderEvent(t)}_bindFirstFrameRenderEvent(t){const i=()=>{if(this._isFirstFrameRenderEmitted)return;this._isFirstFrameRenderEmitted=!0;const n=t.videoWidth||0,c=t.videoHeight||0;this._log.info(`first frame render: ${n}x${c}`),this.emit(Jn.FIRST_FRAME_RENDER,{width:n,height:c})};typeof t.requestVideoFrameCallback=="function"?t.requestVideoFrameCallback(i):t.addEventListener("loadeddata",i,{once:!0})}get styleAttribute(){let t=this._useWrapper?`grid-area:1/1;width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`:`width:100%;height:100%;object-fit:${this.objectFit};${this.shouldRenderAlpha?"":"background-color:black"};`;return this.viewMirror&&(t+="transform:scaleX(-1);"),t}setLiveMode(t){if(this._useWrapper!==t&&(this._useWrapper=t,this.elementToRender&&this.elementToRender.setAttribute("style",this.styleAttribute),this.container&&this.elementToRender))if(t){const i=this._getOrCreateWrapper();i.insertBefore(this.elementToRender,i.firstChild)}else this.container.appendChild(this.elementToRender),this._cleanupWrapper()}setContainer(t){if(this.container===t)return;const i=this._wrapper,n=this.container;this.container=t,this._pausedRetryCount=U_,this.track&&this.elementToRender&&this._appendToWrapper(),i&&n&&n!==this.container&&i.isConnected&&i.children.length===0&&i.remove()}_getOrCreateWrapper(){if(!this.container)throw new Error("[VideoPlayer] container is required");let t=this.container.querySelector("[data-trtc-video-wrapper]");return t||(t=document.createElement("div"),t.setAttribute("data-trtc-video-wrapper","true"),t.style.cssText="display:grid;width:100%;height:100%;",this.container.appendChild(t)),this._wrapper=t,t}_appendToWrapper(t){const i=t??this.elementToRender;if(this.container&&i)if(this._useWrapper){const n=this._getOrCreateWrapper();n.insertBefore(i,n.firstChild)}else this.container.appendChild(i)}bindElementEvents(){const t=super.bindElementEvents();this.handleElementEvent=this.handleElementEvent.bind(this),this.handleFullscreenChange=this.handleFullscreenChange.bind(this),this.handleVolumeChange=this.handleVolumeChange.bind(this),t&&t.add(ei.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(ei.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(ei.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(ei.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.addEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.addEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.addEventListener("volumechange",this.handleVolumeChange))}handleTrackEvent(t){var i;return t.type===ei.MUTE&&((i=this.stat)!=null&&i.fps&&(this.stat.fps=0),this.isFullscreen()&&this.resetSrcObjectToReplay()),super.handleTrackEvent(t)}handleFullscreenChange(){this.isFullscreen()?(this._log.info("enter fullscreen"),this.emit(Jn.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(Jn.LEAVE_FULL_SCREEN))}handleVolumeChange(){var t;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(Jn.VOLUME_CHANGE,{muted:(t=this.element)==null?void 0:t.muted})}handleElementEvent(t){var i,n,c,I,C,f;if(this.mode===2)return;super.handleElementEvent(t);const w=t.type,_=this.isPictureInPicture(),N=this.isFullscreen(),L=t.isTrusted&&(_&&ld||N);if(w===ei.PLAYING&&L&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(N?"fullscreen":"pip")),this.emit(Jn.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),w===ei.PAUSE&&(L&&(this._log.warn("user pause in "+(N?"fullscreen":"pip")),this.emit(Jn.USER_PAUSE_IN_PIP_OR_FULL_SCREEN)),this.container&&!this.container.isConnected&&(this._log.warn(`${this.kind} player has been remove, element ID: ${this.container.id}`),IT(500).then(()=>{var q;(q=this.container)!=null&&q.isConnected&&(this._pausedRetryCount=U_,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!GU()&&!this.isPausedByUserCall&&!L&&(this._log.info(`[${U_-this._pausedRetryCount+1}/${U_}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),vu&&!L&&(this._interval=MQ.run("timeout",()=>{this.element&&this._state==="PAUSED"&&!this.isPausedByUserCall&&this.doResume()},{delay:3e3})),this.stat.fps&&(this.stat.fps=0)),this.viewMirror&&this.element){const q=this.element.style.transform;w===ei.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=q.replace("scaleX(-1)",""):w!==ei.LEAVE_PICTURE_IN_PICTURE||q.includes("scaleX")||(this.element.style.transform=`${q} scaleX(-1)`)}w===ei.RESIZE&&(this._preSize.height===((i=this.element)==null?void 0:i.videoHeight)&&this._preSize.width===((n=this.element)==null?void 0:n.videoWidth)||(this._log.info(`video size changed to ${(c=this.element)==null?void 0:c.videoWidth}x${(I=this.element)==null?void 0:I.videoHeight}`),this._preSize.height=((C=this.element)==null?void 0:C.videoHeight)||0,this._preSize.width=((f=this.element)==null?void 0:f.videoWidth)||0,this.emit(Jn.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),w===ei.LEAVE_PICTURE_IN_PICTURE&&(this._log.warn("exit pip"),this.isPaused&&!this.isPausedByUserCall&&(this._log.warn("resume after exit pip"),this.doResume()),this.resetSrcObjectToReplay(),this.emit(Jn.LEAVE_PICTURE_IN_PICTURE)),w===ei.ENTER_PICTURE_IN_PICTURE&&this.emit(Jn.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){cC&&I3&&this.isPlayCalled&&this.element&&this.track&&!this.isPausedByUserCall&&(this._log.warn("reset srcObject to replay for android chromium"),this._isResettingSrcObject=!0,this.element.srcObject=new MediaStream([this.track]),this.element.play().catch(t=>{this._log.warn("play failed after reset srcObject",t)}).finally(()=>{this._isResettingSrcObject=!1}))}setCanvas(t,i=1){var n,c;this.canvas!==t&&((n=this.canvas)==null||n.remove(),t?.setAttribute("style",this.styleAttribute),this.canvas=t,this.mode=t?i:0,this.mode===2&&this.setTrack(t.captureStream().getVideoTracks()[0]),t?((c=this.element)==null||c.remove(),this._appendToWrapper(t)):this.element&&this._appendToWrapper(this.element))}setAttr(t){const i=Object.assign({autoplay:"autoplay",playsinline:"playsinline",muted:!0},t);i.style=Object.assign({width:"100%",height:"100%"},i.style),super.setAttr(i)}get mirror(){return this.viewMirror}setRect(t,i){this.elementToRender&&(this.elementToRender.style.width=`${t}px`,this.elementToRender.style.height=`${i}px`)}setViewMirror(t){this.elementToRender&&(this.elementToRender.style.transform=t?"scaleX(-1)":""),this.viewMirror=t}setObjectFit(t){this.elementToRender&&(this.elementToRender.style.objectFit=`${t}`),this.objectFit=t}setPoster(t,i=!1){return new Promise(n=>{if(!this.element||(this._log.info("setPoster",t.slice(0,10)),t===""?this.element.removeAttribute("poster"):this.element.poster=t,!(i&&(ld||rC))))return n();if(t==="")return this.removePosterImg(),n();if(this.posterImg)return n();const c=document.createElement("img");c.src=t;const I=window.getComputedStyle(this.element),C=I.objectFit||this.objectFit;let f=1;if(this._useWrapper){const w=parseInt(I.zIndex,10);isNaN(w)||(f=w+1)}c.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${f};width:100%;height:100%;object-fit:${C};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${C};`,c.onload=async()=>{try{c.decode&&await c.decode(),this.container&&!this._useWrapper&&window.getComputedStyle(this.container).position==="static"&&(this._originContainerPosition=this.container.style.position,this.container.style.position="relative"),this.posterImg=c;const w=this._useWrapper?this._wrapper:this.container;w?.appendChild(c),PY()&&Uv<=17&&this.elementToRender&&(this.elementToRender.style.visibility="hidden")}catch(w){this._log.warn("decode poster image error",w)}return n()},c.onerror=()=>(this._log.warn("load poster image error"),n())})}removePosterImg(){this.posterImg&&(PY()&&Uv<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),this._useWrapper||!this.container||er(this._originContainerPosition)||this.container.style.position!=="relative"||(this.container.style.position=this._originContainerPosition),delete this.posterImg)}get hasPoster(){var t;return!!this.posterImg||!!((t=this.element)!=null&&t.getAttribute("poster"))}async pause(t=!0){super.pause(),this.isPictureInPicture()||this.hasPoster||!(I3||t&&(rC||ld))||await this.setPoster(this.getVideoFrame(),!0)}resume(t=!1){return super.resume(t).then(()=>{var i;(this.posterImg||(i=this.element)!=null&&i.poster)&&this.setPoster("",!0)})}doResume(t=!1){return this.isPaused&&t&&this.element&&this.track&&I3&&this.track.kind==="video"&&(this.element.srcObject=new MediaStream([this.track])),super.doResume()}stop(t=0){var i;this.isPictureInPicture()&&this.exitPictureInPicture().catch(n=>{}),this.isFullscreen()&&this.exitFullscreen().catch(n=>{}),this.element&&(this.element.removeEventListener(ei.FULLSCREEN_CHANGE,this.handleFullscreenChange),this.element.removeEventListener("webkitbeginfullscreen",this.handleFullscreenChange),this.element.removeEventListener("webkitendfullscreen",this.handleFullscreenChange),this.element.removeEventListener("volumechange",this.handleVolumeChange)),this._isFirstFrameRenderEmitted=!1,super.stop(t),(i=this.canvas)==null||i.remove(),this.removePosterImg(),this._useWrapper&&this._cleanupWrapper()}_cleanupWrapper(){this._wrapper&&this._wrapper.children.length===0&&this._wrapper.remove(),this._wrapper=null}play(t){if(er(t?.isLiveStream)||this.setLiveMode(t.isLiveStream),this.element){if(this.elementToRender&&this.container)if(this._useWrapper){const i=this._getOrCreateWrapper();this.elementToRender.parentElement!==i&&i.insertBefore(this.elementToRender,i.firstChild)}else this.elementToRender.parentElement!==this.container&&this.container.append(this.elementToRender)}else this.initializeElement();return this.mode===2?Promise.resolve():super.play()}get elementToRender(){return this.canvas||this.element}setTrack(t){t!==this.track&&(this.unbindTrackEvents(),this.track=t,this.emit(Jn.MEDIA_TRACK_CHANGED,t),t!==null&&(this.bindTrackEvents(),this.element&&this.mode!==2&&(this.element.srcObject=new MediaStream([t]),this.element.remove()),this._appendToWrapper()))}getVideoFrame(){if(this.canvas)return this.canvas.toDataURL("image/png");if(!this.element)return"";const t=document.createElement("canvas");return t.width=this.element.videoWidth,t.height=this.element.videoHeight,t.getContext("2d").drawImage(this.element,0,0),t.toDataURL("image/png")}getElement(){return this.element}calculateStat(){try{if(x4()&&this.element&&this._calculateTimeout<0){let t=0,i=null;const n=(c,I)=>{this.stat.width=I.width,this.stat.height=I.height,i&&(this.stat.fps=Math.round((I.presentedFrames-i.presentedFrames)/(c-t)*1e3)),t=c,i=I,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var C;return(C=this.element)==null?void 0:C.requestVideoFrameCallback(n)},2e3))};this.element.requestVideoFrameCallback(n)}}catch(t){this._log.warn("init stat failed",t)}}async enterFullscreen(){const t=this.elementToRender;if(!t)throw this._log.warn("no element to render, cannot enter fullscreen"),new Error("No element available for fullscreen");if(vu&&this.isPictureInPicture()){this._log.info("exit pip before entering fullscreen");try{await this.exitPictureInPicture()}catch(i){this._log.warn("exit pip failed before fullscreen:",i)}}try{if(t.requestFullscreen)await t.requestFullscreen();else if(t.webkitRequestFullscreen)await t.webkitRequestFullscreen();else if(t.webkitEnterFullscreen)await t.webkitEnterFullscreen();else if(t.mozRequestFullScreen)await t.mozRequestFullScreen();else{if(!t.msRequestFullscreen)throw new Error("Fullscreen API not supported");await t.msRequestFullscreen()}this._log.info("entered fullscreen mode")}catch(i){throw this._log.error("failed to enter fullscreen:",i),i}}async exitFullscreen(){try{if(!this.isFullscreen())return;if(document.exitFullscreen)await document.exitFullscreen();else if(document.webkitExitFullscreen)await document.webkitExitFullscreen();else if(document.mozCancelFullScreen)await document.mozCancelFullScreen();else{if(!document.msExitFullscreen)throw new Error("Exit fullscreen API not supported");await document.msExitFullscreen()}this._log.info("exited fullscreen mode")}catch(t){throw this._log.error("failed to exit fullscreen:",t),t}}isFullscreen(){const t=this.elementToRender;return t?this.element&&this.element.webkitDisplayingFullscreen?!this.isPictureInPicture():(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)===t:!1}async toggleFullscreen(){this.isFullscreen()?await this.exitFullscreen():await this.enterFullscreen()}async enterPictureInPicture(){this.enterPIPPromise=this._enterPictureInPicture();try{return await this.enterPIPPromise}finally{delete this.enterPIPPromise}}async _enterPictureInPicture(){try{if(!this.element)throw new Error("No video element available for pip");if(this.canvas&&this.mode!==1)throw new Error("pip is not supported for canvas-only mode");const{element:t}=this;if(t.requestPictureInPicture){this._log.info("requestPictureInPicture");const i=await t.requestPictureInPicture();return this.pipWindow=i,this._log.info("entered pip mode"),this.elementToRender===this.canvas&&(this.canvas.remove(),this._appendToWrapper(this.element)),i}if(t.webkitSetPresentationMode)return this._log.info("webkitSetPresentationMode"),await t.webkitSetPresentationMode("picture-in-picture"),this._log.info("entered pip mode (webkit)"),{};throw new Error("pip API not supported")}catch(t){throw this._log.error("failed to enter pip:",t.name,t.message),t}}async exitPictureInPicture(){var t;try{if(!this.isPictureInPicture())return;if(delete this.pipWindow,document.pictureInPictureElement&&document.exitPictureInPicture)await document.exitPictureInPicture(),this.elementToRender===this.canvas&&((t=this.element)==null||t.remove(),this._pausedRetryCount=U_,this._appendToWrapper(this.canvas)),this._log.info("exited pip mode");else{if(!this.element||!this.element.webkitSetPresentationMode)throw new Error("Exit pip API not supported or not in PiP mode");await this.element.webkitSetPresentationMode("inline"),this._log.info("exited pip mode (webkit)")}}catch(i){throw this._log.error("failed to exit pip:",i),i}}isPictureInPicture(){if(!this.element)return!1;const{element:t}=this;return document.pictureInPictureElement?document.pictureInPictureElement===t:!!t.webkitPresentationMode&&t.webkitPresentationMode==="picture-in-picture"}async togglePictureInPicture(){this.isPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}};async function buA(t,i){if(!t.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await t.audioWorklet.addModule(i),Wo.info("worklet addModule success")}catch(n){throw Wo.info(`worklet addModule catch error. ${n.message}`),n}}typeof AudioContext<"u"?hU=AudioContext:typeof webkitAudioContext<"u"?hU=webkitAudioContext:typeof mozAudioContext<"u"&&(hU=mozAudioContext);var Du,kuA=1500,n6=-1,$1=0,BU=-1,dW=!1,r6=0,a6=-1,g6=-1;function Y$(){try{if(Du)return;(Du=new hU({sampleRate:48e3})).onstatechange=()=>{Wo.info(`context state: ${Du.state}${Du.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),eT()},clearTimeout(n6)}catch(t){Wo.error(`initAudioContext failed: ${t} typeof AudioContextClass: ${typeof hU}`),n6=setTimeout(Y$,1e3)}}Y$();var eT=()=>{Du.state==="suspended"?($1=Yc(),LuA(),KY(),document.addEventListener("click",eT)):Du.state==="interrupted"?KY():($1&&(dr.addNumber({key:507800,value:Yc()-$1,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),$1=0),UuA(),document.removeEventListener("visibilitychange",eT),document.removeEventListener("click",eT))},Q3=0,p3=-1;function KY(){return new Promise((t,i)=>{if(Du.state==="running")return t();Date.now()-Q3<1e3?(clearTimeout(p3),p3=setTimeout(()=>{Q3=Date.now(),Du.resume().then(t,i)},1e3)):(clearTimeout(p3),Q3=Date.now(),Du.resume().then(t,i))}).catch(t=>{Wo.warn(`context resume failed: ${t}`),document.addEventListener("visibilitychange",eT)})}function LuA(){BU===-1&&(BU=setTimeout(()=>{Du.state==="suspended"&&(dW=!0,ms.emit("155",{isSuspended:!0}))},kuA))}function UuA(){BU!==-1&&(clearTimeout(BU),BU=-1,dW&&(dW=!1,ms.emit("155",{isSuspended:!1})))}function FuA(){if(!vu||g6!==-1)return;const t=()=>{Yc()-r6<500||(Du&&Du.state==="running"&&Du.currentTime===a6&&(Wo.warn("context is fake running, auto resume"),Du.suspend().catch(i=>{Wo.warn(`context suspend failed: ${i}`)})),a6=Du.currentTime,r6=Yc())};g6=setInterval(()=>{t()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}document.addEventListener("click",eT);var rD=t=>Du,vv=class{constructor(t){this.name=t,Be(this,"node"),Be(this,"node2"),Be(this,"pre",new Set),Be(this,"next",new Set),Be(this,"context"),Be(this,"connectedNodes",new Set),Be(this,"nextInputChannelMap",new Map),Be(this,"_channelCount",1)}get channelCount(){return this._channelCount}set channelCount(t){this._channelCount=t,this.setChannelCount(this.node,t),this.setChannelCount(this.node2,t),this.next.forEach(i=>i.channelCount=t)}setChannelCount(t,i){!t||t instanceof ScriptProcessorNode||(t.channelCountMode="explicit",t.channelCount=i||this.channelCount||1)}setContext(t){this.context=t,this.node&&t.addMixWeight()}removeContext(){var t;this.node&&((t=this.context)==null||t.reduceMixWeight()),delete this.context}replaceNode(t){var i;if(t!==this.node)try{this.node?this._disconnect():(i=this.context)==null||i.addMixWeight(),this.node=t,this.setChannelCount(this.node),this.preNodeReconnect(),this.reconnect()}catch(n){Wo.error(n)}}setNode(t,i){var n;if(!this.node)try{(n=this.context)==null||n.addMixWeight(),this.node=t,this.setChannelCount(this.node),i&&(this.node2=i,this.setChannelCount(this.node2)),this.preNodeReconnect(),this.reconnect(),dr.addSuccessEvent({key:502701})}catch(c){Wo.error(c),dr.addFailedEvent({key:502701,error:c})}}deleteNode(){var t;if(this.node)try{this._disconnect(),delete this.node,delete this.node2,(t=this.context)==null||t.reduceMixWeight(),this.preNodeReconnect(),dr.addSuccessEvent({key:502702})}catch(i){Wo.error(i),dr.addFailedEvent({key:502702,error:i})}}preNodeReconnect(){this.pre.forEach(t=>{t.node?t.reconnect():t.preNodeReconnect()})}connectNext(t){this.next.forEach(i=>{const n=this.nextInputChannelMap.get(i);t._connect(i.node,n)||i.connectNext(t)})}_connect(t,i=0){return!(!this.node||!t)&&((this.node2||this.node).connect(t,0,i),this.connectedNodes.add(t),!0)}_disconnect(){this.connectedNodes.forEach(t=>{var i;return(i=this.node2||this.node)==null?void 0:i.disconnect(t)}),this.connectedNodes.clear()}reconnect(){this._disconnect(),this.connectNext(this)}pipeTo(t,i=0){return this.next.add(t),t.pre.add(this),this.nextInputChannelMap.set(t,i),t}},OuA=class extends vv{constructor(t=256){super(),this.fftSize=t,Be(this,"dataArray",new Uint8Array(0))}setNode(t){t.fftSize=this.fftSize,this.dataArray=new Uint8Array(t.frequencyBinCount),super.setNode(t)}getByteTimeDomainData(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),this.dataArray}get level(){var t;return(t=this.node)==null||t.getByteTimeDomainData(this.dataArray),Math.max(...this.dataArray)/128-1}get timeDomainPathData(){const t=this.getByteTimeDomainData();let i=0,n=0,c=`M${i},${n}`;for(let I=0;Ithis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(cm.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=n=>{cm.lastMessageTime=Date.now(),this._volume=n.data.volume||0,this._volumeDb=n.data.volumeDb||0,!i&&n.data.cacheLen&&n.data.outputLen&&(this._log.warn("worklet play success"),i=!0)},this.handleAudioLevelInterval({interval:this._interval})}catch(i){this._log.error(`volumeMeter init audio worklet error: ${i}`),ah.logFailedEvent({userId:this._log.userId,eventType:lU.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=rD("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{cm.lastMessageTime=Date.now();const n=i.inputBuffer.getChannelData(0);let c=0;for(let I=0;I>2);t.copyTo(n,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:n},[n.buffer]),t.close()}}},VuA=mT(zU()),I6=t=>i=>i.deviceId===t,m3=class{constructor(t,i){Be(this,"kind"),Be(this,"type"),Be(this,"devices",[]),this.kind=t,this.type=i}update(t,i){const n=t.filter(c=>c.kind===`${this.kind}${this.type.toLocaleLowerCase()}`);this.devices.length===1&&V$(this.devices[0])||i&&(n.forEach(c=>{if(c.deviceId&&!this.devices.find(I6(c.deviceId))){const I=`${this.kind}${this.type}Added`;Wo.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}}),this.devices.forEach(c=>{if(c.deviceId&&!n.find(I6(c.deviceId))){const I=`${this.kind}${this.type}Removed`;Wo.warn(`${I}: ${JSON.stringify(c)}`),i.emit(I,c)}})),this.devices=n}hasDevice(t){return!!this.devices.find(i=>i.deviceId===t)}},JuA=class extends VuA.EventEmitter{constructor(){super(),Be(this,"audioInputs",new m3(ei.AUDIO,"Input")),Be(this,"videoInputs",new m3(ei.VIDEO,"Input")),Be(this,"audioOutputs",new m3(ei.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||MQ.run("interval",()=>{this.update()},{delay:1e4}))}init(){CW().then(t=>{this.audioInputs.update(t),this.videoInputs.update(t),this.audioOutputs.update(t)})}async update(t=0){const i=await CW(t);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var t;if(1e3*((t=rD())==null?void 0:t.outputLatency)>150)return!0;const i=["bluetooth","air","wireless","bt","tws","buds","headset","headphone"];return this.audioOutputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))||this.audioInputs.devices.some(n=>i.some(c=>n.label.toLowerCase().includes(c)))}},DQ=u7||I7?null:new JuA;function V$(t){return t.deviceId===t.groupId&&t.groupId===""}async function CW(t=0){if(kV()||!U4())return[];let i=await navigator.mediaDevices.enumerateDevices();if(t!==0){const n={audio:!1,video:!1};if(i.forEach(c=>{V$(c)&&(c.kind===ei.AUDIO_INPUT?n.audio=!0:c.kind===ei.VIDEO_INPUT&&(n.video=!0))}),t===2&&(n.audio=!1),t===1&&(n.video=!1),n.audio||n.video){let c;try{c=await navigator.mediaDevices.getUserMedia(n),n.audio&&KY()}catch(I){Wo.debug("capture before getDevices failed: ",I)}i=await navigator.mediaDevices.enumerateDevices(),c?.getTracks().forEach(I=>I.stop())}}return i.map((n,c)=>{const I={kind:n.kind,deviceId:n.deviceId,groupId:n.groupId,label:n.label||`${n.kind}_${c}`};return n.deviceId.length>0&&H4.add(`${n.deviceId}_${n.kind}`),n.getCapabilities&&(I.getCapabilities=()=>n.getCapabilities()),I})}function kU(t=!1){return DQ.update(t?1:0).then(i=>i.audioInputs.devices)}function Rv(t=!1){return DQ.update(t?2:0).then(i=>i.videoInputs.devices)}var u6=!1;async function HuA(){try{u6||(u6=!0,Wo.info(`speakers:${(await quA()).map(t=>` ${t.deviceId.slice(0,8)}: ${t.label}`)}`))}catch{}}async function quA(t=!1){return(vu||ld)&&(t=!1),DQ.update(t?1:0).then(i=>i.audioOutputs.devices)}var pY,H4=new Set;function KuA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("camera")||i.includes("webcam"))return!0;const n=`${(t?.getSettings()||{}).deviceId}_${ei.VIDEO_INPUT}`;return!!H4.has(n)}function juA(t){if(t instanceof CanvasCaptureMediaStreamTrack||!(t instanceof MediaStreamTrack))return!1;const i=t.label.toLocaleLowerCase();if(i.includes("mic")||i.includes("麦克风"))return!0;const n=`${(t?.getSettings()||{}).deviceId}_${ei.AUDIO_INPUT}`;return!!H4.has(n)}async function WuA(t,i){const n=(await kU()).find(c=>c.deviceId===C7);return!i&&n?.groupId===t||n?.groupId===t&&n.label===i}async function zuA({newDeviceId:t,oldDeviceId:i,oldGroupId:n,oldLabel:c,kind:I}){return t===i&&(I!==ei.AUDIO||t!==C7||await WuA(n,c))}var ZuA=class extends PuA{constructor(t){super(),this.log=t,Be(this,"volumeMeter"),Be(this,"volumeMeterAfter3A"),Be(this,"volumeDestination"),Be(this,"analyser",new OuA),this.volumeMeter=new l6({log:this.log}),this.volumeMeterAfter3A=new l6({log:this.log}),this.volumeDestination=new vv,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},XuA=class extends Ev{constructor(t){super(t,ei.AUDIO),Be(this,"_outputDeviceId"),Be(this,"_floatVolume",1),Be(this,"_destination"),Be(this,"pipeline"),Be(this,"volumeMeterMode","worklet"),Be(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new ZuA(this._log)}setTrack(t){}get duration(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.duration)||0))}get currentTime(){var t;return Math.floor(1e3*(((t=this.element)==null?void 0:t.currentTime)||0))}set currentTime(t){this.element&&(this.element.currentTime=t/1e3)}getMediaStream(){return this.pipeline.stream||(this.track?new MediaStream([this.track]):null)}initializeElement(t){if((wQ==="15.2"||wQ==="15.3"||wQ==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=pY||new Audio;i.setAttribute("autoplay","autoplay"),i.srcObject=this.getMediaStream(),i.muted=this.muted,this.url&&(i.crossOrigin="anonymous",i.src=this.url),this.element=i,this.setVolume(Lv(t)?t/100:this._floatVolume),i===pY&&(pY=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(Jn.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}async play(t){if(this.track||this.url){try{!this.pipeline.source.node&&this.track&&this.pipeline.replaceSource(this.track),this.element||this.initializeElement(t?.volume),this._outputDeviceId&&await this.setSinkId(this._outputDeviceId),this.volumeMeterMode==="worklet"?(this.pipeline.volumeMeter.init(),this.pipeline.volumeMeterAfter3A.init()):this.volumeMeterMode==="analyser"&&this.pipeline.analyser.setNode(rD("player").createAnalyser()),HuA()}catch(i){throw this._log.warn(`audio play error: ${i}`),a$(wQ,"18.7",!0)&&this.bindAutoPlayEvent(),i}return super.play()}}stop(t=0){this.pipeline.destroy(),super.stop(t)}setVolume(t){this._floatVolume=t,this.element&&(this.element.volume=t)}async setSinkId(t){var i,n;this._outputDeviceId!==t&&(this._outputDeviceId=t),this.element&&this.element.sinkId!==t&&await((n=(i=this.element).setSinkId)==null?void 0:n.call(i,t))}get useDestination(){return!!this.pipeline.stream}setLoop(t){this.element&&(this.element.loop=t)}getAudioLevel(){return this.pipeline.volumeMeter.getCalculatedVolume()}getInternalAudioLevel(){return this.pipeline.volumeMeter.getInternalAudioLevel()}getInternalAudioLevelAfter3A(){return this.pipeline.volumeMeterAfter3A.getInternalAudioLevel()}},$uA=class extends XuA{constructor(t){super(t),Be(this,"_sourceElement"),Be(this,"_output",new vv),this.pipeline.source.pipeTo(this.pipeline.gain),this.pipeline.gain.pipeTo(this.pipeline.volumeMeter).pipeTo(this._output),this.pipeline.gain.pipeTo(this.pipeline.destination)}setOutput(){this.mode=1,this._output.setNode(rD().destination)}write(t){this.pipeline.volumeMeter.write(t)}setTrack(t){var i,n,c;((n=(i=this.element)==null?void 0:i.error)==null?void 0:n.code)!==MediaError.MEDIA_ERR_DECODE&&this.track!==t&&(this.unbindTrackEvents(),this.track=t,this.emit(Jn.MEDIA_TRACK_CHANGED,t),t?(this.bindTrackEvents(),this._sourceElement?this._sourceElement.srcObject=new MediaStream([t]):!this.useDestination&&this.element&&(this.element.srcObject=new MediaStream([t])),this.pipeline.source.channelCount=((c=t.getSettings())==null?void 0:c.channelCount)||1,this.pipeline.replaceSource(t)):this.pipeline.source.deleteNode())}setVolume(t){var i;const n=t<=1&&!PY();if(!(this._floatVolume===t&&(n&&((i=this.element)==null?void 0:i.volume)===t||!n&&this.pipeline.volume===t)))if(this._floatVolume=t,this.useDestination)this.pipeline.setVolume(t),this._log.info(`set pipeline volume: ${t}`);else if(n)this.element?(this._log.info(`set element volume: ${t}`),this.element.volume=t):this._log.info("set element volume: no element");else{if(PY()){if(!this.enableVolumeControlInIOS)return;FuA()}if(rC&&!this.pipeline.source.node)return void this._log.warn("set pipeline volume failed: no source node");this._log.info(`start set pipeline volume: ${t}`),this.pipeline.setVolume(t),this.element&&!this._sourceElement&&(this._destination||(this._destination=rD().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),NU(this.element),this._sourceElement=this.element,this._sourceElement.muted=!0,this.element=null,this.play().catch(c=>{this.emit(Jn.AUTOPLAY_FAILED,c)}))}}stop(t=0){this.pipeline.destroy();const i=this._sourceElement||this.element;i&&r$&&(pY=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(t)}},q4=class extends Ar{constructor({userId:t,sdkAppId:i,mediaType:n,room:c,PlayerClass:I=n===1?$uA:Yy}){var C;super(),Be(this,"id",d$()),Be(this,"userId",""),Be(this,"isRemote"),Be(this,"mediaType"),Be(this,"room"),Be(this,"user"),Be(this,"_log"),Be(this,"_inputTrack"),Be(this,"_outputTrack"),Be(this,"isPlayCalled"),Be(this,"container",null),Be(this,"player"),Be(this,"subVideoPlayerMap"),Be(this,"muted",!1),Be(this,"abortCtrl"),Be(this,"objectFit","cover"),Be(this,"mirror"),Be(this,"rotation"),Be(this,"isScreen",!1),Be(this,"manager"),Be(this,"trackSettings"),Be(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=n,this._log=Wo.createLogger({parent:c?.getLogger(),id:`${this.kind[0]}t`,userId:(C=c||this.room)==null?void 0:C.userId,remoteUserId:this instanceof pv?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof pv}),this.player=new I({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:c?.enableVolumeControlInIOS}),this.player.on(Jn.PLAYER_STATE_CHANGED,f=>{if(ms.emit(mn.PLAYER_STATE_CHANGED,Rn({track:this},f)),this.emit("player-state-changed",f),f.state==="PLAYING"&&this.room){let w=!0;for(const{remoteAudioTrack:_,remoteVideoTrack:N,remoteAuxiliaryTrack:L}of[...this.room.remotePublishedUserMap.values()])if(_.isAvailable&&!_.player.isPlaying||N.isAvailable&&!N.player.isPlaying||L.isAvailable&&!L.player.isPlaying){w=!1;break}w&&GU()&&GuA()}}),this.kind===ei.VIDEO&&(this.player.on(Jn.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Jn.LOADED_DATA),ms.emit(mn.VIDEO_LOADED_DATA,{track:this})}),this.player.on(Jn.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(Jn.LOADED_META_DATA)}),this.player.on(Jn.MEDIA_TRACK_CHANGED,f=>{var w;(w=this.subVideoPlayerMap)==null||w.forEach(_=>_.setTrack(f))}),this.player.on(Jn.RESIZE,f=>{this.emitFirstVideoFrameEvent(Jn.RESIZE),this.emit("video-size-changed",Rn({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},f))}),this.player.on(Jn.FIRST_FRAME_RENDER,f=>{this.emit("first-frame-render",gB(Rn({},f),{streamType:this.streamType,userId:this.isRemote?this.userId:""}))})),this.onTrackMuted=this.onTrackMuted.bind(this),this.onTrackUnmuted=this.onTrackUnmuted.bind(this),this.onTrackEnded=this.onTrackEnded.bind(this),this.onPlayerError&&this.player.on(Jn.ERROR,this.onPlayerError.bind(this)),this.player.on(Jn.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||Wo}get kind(){return this.mediaType===1?ei.AUDIO:ei.VIDEO}get isAudio(){return this.kind===ei.AUDIO}get strMediaType(){return this.mediaType===4?ei.VIDEO:this.mediaType===2?ei.SCREEN:ei.AUDIO}get streamType(){return 2&this.mediaType?"auxiliary":"main"}get isMediaTrackActive(){return!!this.mediaTrack&&!this.mediaTrack.muted&&this.mediaTrack.readyState==="live"&&this.mediaTrack.enabled}async play(t,i){const n=oh(t)?t[0]:t;if(this.isPlayCalled)return this.log.info(`play update options: ${JSON.stringify(i)}`),i&&!er(i.muted)&&this.setPlayerMute(i.muted),i&&!er(i.objectFit)&&(this.objectFit=i.objectFit),void(this.player instanceof Yy&&(this.player.setObjectFit(this.objectFit),this.container!==n&&n&&(oh(t)&&t.length>=1&&this.container&&t.includes(this.container)&&this.container.contains(this.player.elementToRender)?(t.splice(t.indexOf(this.container),1),t.unshift(this.container)):(this.container=n,this.player.setContainer(n))),oh(t)&&t.length>=1&&await this.playSubContainer(t.slice(1),i)));if(i&&!er(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==ei.VIDEO||this.setPlayerMute(!0),i&&!er(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Yy&&(er(i?.isLiveStream)||this.player.setLiveMode(i.isLiveStream),this.player.setObjectFit(this.objectFit),i&&!er(i.poster)&&this.player.setPoster(i.poster)),this.isPlayCalled=!0,n&&(this.container=n,this.player instanceof Yy&&this.player.setContainer(n)),ms.emit(mn.PLAY_TRACK_START,{track:this}),this._outputTrack){this._log.info(`play with options: ${JSON.stringify(i)}`);try{this.player.setTrack(this.playerMediaTrack),await this.player.play(i),oh(t)&&t.length>1&&await this.playSubContainer(t.slice(1),i)}catch(c){throw this.handleAutoPlayFailed(c),c}}else this.log.info("play has not mediaTrack, abort")}setMirror(t,i){if(this.isScreen||this.kind!==ei.VIDEO||er(t)||t===this.mirror)return;this.mirror=t;let n=this.player;i&&(n=i);const c=this.manager;if(Sv(this.mirror))return n.setViewMirror(this.mirror),void(!this.isRemote&&c&&(c.mirror=!1));switch(this.mirror){case"view":c&&(c.mirror=!1),n.setViewMirror(!0);break;case"publish":c&&(c.mirror=!0),n.setViewMirror(!0);break;case"both":c&&(c.mirror=!0),n.setViewMirror(!1)}}async playSubContainer(t,i){if(!this._outputTrack||this.kind===ei.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((c,I)=>{var C;t.find(f=>I===f)||(c.stop(),(C=this.subVideoPlayerMap)==null||C.delete(I))});for(const[c,I]of t.entries()){const C=this.subVideoPlayerMap.get(I);C?i&&(er(i.objectFit)||C.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(I,new Yy({id:this.userId||this.id,track:this.playerMediaTrack,container:I,muted:this.player.muted,objectFit:this.objectFit,log:this.log.createChild({id:`vp-sub${c+1}`})}))}const n=[...this.subVideoPlayerMap.values()];for(const c of n)c.setViewMirror(this.player.mirror),await c.play()}setAudioOutput(t){return this.player.setSinkId(t)}setAudioVolume(t){this.player.setVolume(t)}getAudioLevel(){return this.player.getAudioLevel()||0}getInternalAudioLevel(){var t;return((t=this.player)==null?void 0:t.getInternalAudioLevel())||0}stop(t=!1){this.isPlayCalled&&(this.isPlayCalled=!1,this.isFirstVideoFrameEmitted=!1,this.player&&(this.log.info(`stop ${this.kind} player`),this.player.stop(c3(this)&&!t?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(i=>{i.stop()}),this.container=null)}async resume(){var t;this.isPlayCalled&&await((t=this.player)==null?void 0:t.resume())}close(){this._toInitState(),this.log.info("close"),this.isPlayCalled&&this.stop(!0)}_toInitState(){}setMute(t){this.muted=t,this._inputTrack&&(this._inputTrack.enabled=!t),this._outputTrack&&(this._outputTrack.enabled=!t),this.emit(t?"mute":"unmute",this),ms.emit(t?mn.TRACK_MUTED:mn.TRACK_UNMUTED,{track:this})}setPlayerMute(t){this.player.setMuted(t)}get mediaTrack(){return this._inputTrack||null}get outMediaTrack(){return this._outputTrack||null}get playerMediaTrack(){return this.outMediaTrack}installTrackEvent(t){V4(t,t).add(ei.MUTE,this.onTrackMuted).add(ei.UNMUTE,this.onTrackUnmuted).add(ei.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===ei.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){NU(t)}setInputMediaStreamTrack(t){var i;const n=this._inputTrack;if(t!==n)return this._inputTrack=t,this.trackSettings=(i=t.getSettings)==null?void 0:i.call(t),t.enabled=!this.muted,n&&this.uninstallTrackEvent(n),this.installTrackEvent(t),this.emit("input-media-track-changed",t||null,n||null),this.manager?this.manager.changeInput(this):this.setOutputMediaStreamTrack(t)}setOutputMediaStreamTrack(t){var i;const n=this._outputTrack;this instanceof FV&&p4(n)||t!==n&&(this.isRemote?this.log.debug("setOutputMediaStreamTrack",t.label):this.log.info("setOutputMediaStreamTrack",(i=t.getSettings)==null?void 0:i.call(t).deviceId,t.label),this._outputTrack=t,this._inputTrack&&(this._outputTrack.contentHint=this._inputTrack.contentHint,this._outputTrack.enabled=this._inputTrack.enabled),this.updatePlayingState(!!t),this.emit("output-media-track-changed",t))}setMediaType(t){this.mediaType=t}updatePlayingState(t){var i,n;if(this.isPlayCalled){if(t){if(this.player.setTrack(this.playerMediaTrack),this.player.isStopped)return this.player.play().catch(c=>this.handleAutoPlayFailed(c)),void this.log.info(`playing state updated, play ${this.kind}`)}else if(!this.player.isStopped)return c3(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((n=this.user)!=null&&n.muteState.audioMuted)?void 0:(this.player.stop(c3(this)?this.jitterBufferDelay:0),void this.log.info(`playing state updated, stop ${this.kind}`))}this.log.debug(`updatePlayingState abort ${this.isPlayCalled} ${t} ${this.player.isStopped}`)}async handleAutoPlayFailed(t){var i;this.log.warn("handleAutoPlayFailed",t);const n=()=>{this.resume().then(()=>{document.removeEventListener("click",n,!0)})};if(this.room&&this.room.enableAutoPlayDialog){if((fT||$U)&&(await IT(100),(i=this.player)==null?void 0:i.isPlaying))return;NuA()}else document.addEventListener("click",n,!0);ms.once(mn.LOCAL_TRACK_CAPTURE_SUCCESS,({track:c})=>{c.kind==="audio"&&GU()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&n()}),this.emit("error",t)}getVideoFrame(){return this.player instanceof Yy?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(t){var i,n,c;if(this.isFirstVideoFrameEmitted)return;const I=(i=this.mediaTrack)==null?void 0:i.getSettings();let C=I?.width||((n=this.player.element)==null?void 0:n.videoWidth)||0,f=I?.height||((c=this.player.element)==null?void 0:c.videoHeight)||0;(t!==Jn.RESIZE||C||f)&&(t!==Jn.LOADED_META_DATA||C||f)&&(t!==Jn.LOADED_DATA||C||f||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,T7(this.rotation)&&([C,f]=[f,C]),this.emit("first-video-frame",{width:C,height:f,streamType:this.streamType,userId:this.isRemote?this.userId:""}))}onTrackMuted(){this._log.warn(`${this.kind} track is unable to provide media output`)}onTrackUnmuted(){this._log.info(`${this.kind} track is able to provide media output`)}onTrackEnded(){this._log.warn(`${this.kind} track ended`)}};Cc([Su([],Ar.INIT,{sync:!0})],q4.prototype,"_toInitState");var AEA=Object.prototype.hasOwnProperty;function eEA(t){if(t==null)return!0;if(typeof t=="boolean")return!1;if(typeof t=="number")return t===0;if(typeof t=="string"||typeof t=="function"||Array.isArray(t))return t.length===0;if(t instanceof Error)return t.message==="";if(lT(t))switch(Object.prototype.toString.call(t)){case"[object File]":case"[object Map]":case"[object Set]":return t.size===0;case"[object Object]":for(const i in t)if(AEA.call(t,i))return!1;return!0}return!1}var jY=eEA,tEA=async function(t){const i=oEA(t);Wo.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let n=[],c=[];const I=["label","deviceId","groupId"];if(i.audio&&(n=await kU(),Wo.info(`microphones: ${Xy(n.map(C=>gB(Rn({},C),{groupId:C.groupId.substring(0,8)})),{keysToInclude:I})}`)),i.video&&(c=await Rv(),Wo.info(`cameras: ${Xy(c,{keysToInclude:I})}`),!Sv(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const C=c.filter(f=>!f.label.includes("infrared")).find(f=>f.label.includes("facing front"));C&&(i.video.deviceId=C.deviceId,Wo.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const C=await navigator.mediaDevices.getUserMedia(i);return _$&&C.getTracks().forEach(f=>{var w;const _=f.getCapabilities();Wo.info(`${f.kind} capabilities: ${Xy(_,{keysToInclude:h7})}`),er(t.echoCancellation)||((w=_.echoCancellation)==null?void 0:w.indexOf(t.echoCancellation))!==-1||Wo.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(_.echoCancellation)}], but received '${t.echoCancellation}'`)}),i.audio&&KY(),C}catch(C){let{message:f}=C;throw C.name==="NotFoundError"&&(t.video&&c&&c.length===0&&(f=HY({key:JY.CAMERA_NOT_FOUND})),t.audio&&n&&n.length===0&&(f=HY({key:JY.MICROPHONE_NOT_FOUND}))),new fl({code:qg.INITIALIZE_FAILED,name:C.name,message:f,constraint:C.constraint})}},iEA=m4({retryFunction:tEA,settings:{retries:3,timeout:500},onError:({error:t,retry:i,reject:n,retryFuncArgs:c,retriedCount:I})=>{const C=I+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(C===1?(c[0].video&&(c[0].maxResolution=!1,(!ld||c[0].width*c[0].height<=2073600)&&c[0].frameRate&&(c[0].frameRate=c[0].frameRate>10?10:5)),c[0].retryWhenExactFailed&&c[0].useExactDeviceId&&(c[0].useExactDeviceId=!1)):C===2?c[0].useDeviceIdOnly=!0:C!==3||c[0].useExactDeviceId||(c[0].useTrueAsConstraint=!0),i()):n(t),c[0].microphoneId&&E6(c[0].microphoneId,!1),c[0].cameraId&&E6(c[0].cameraId,!0)},onRetrying:t=>{Wo.warn(`getUserMedia NotReadableError observed, retrying [${t}/3]`)},onRetryFailed:t=>{ah.logFailedEvent({eventType:lU.GET_USER_MEDIA_RETRY,error:t})},onRetrySuccess:t=>{ah.logSuccessEvent({eventType:lU.GET_USER_MEDIA_RETRY}),ah.uploadEvent({log:`stat-${lU.GET_USER_MEDIA_RETRY}-success-${t}`})}});async function E6(t,i){const n=(i?await Rv():await kU()).find(c=>c.deviceId===t);n&&Dv(n.getCapabilities)&&Wo.warn(Xy(n.getCapabilities(),{keysToInclude:h7}))}function oEA(t){return{audio:sEA(t),video:nEA(t)}}function sEA(t){if(!t.audio)return!1;if(t.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:t.sampleRate};return!jY(t.microphoneId)&&(i.deviceId=t.useExactDeviceId?{exact:t.microphoneId}:t.microphoneId,t.useDeviceIdOnly)?i:(Lv(t.channelCount)&&(i.channelCount=t.channelCount),(Sv(t.echoCancellation)||t.echoCancellation==="remote-only"||t.echoCancellation==="all")&&(i.echoCancellation=t.echoCancellation),Sv(t.noiseSuppression)&&!t.noiseSuppression&&(i.noiseSuppression=!1),Sv(t.autoGainControl)&&!t.autoGainControl&&(i.autoGainControl=!1),!!jY(i)||i)}function nEA(t){if(!t.video)return!1;if(t.useTrueAsConstraint)return!0;const{maxResolution:i=!0}=t,n={};return t.cameraId?n.deviceId=t.useExactDeviceId?{exact:t.cameraId}:t.cameraId:t.facingMode&&(n.facingMode=t.facingMode),t.useDeviceIdOnly&&!jY(n)?n:(t.width&&(n.width={ideal:t.width},i&&!rC&&(n.width.max=t.width)),t.height&&(n.height={ideal:t.height},i&&!rC&&(n.height.max=t.height)),rC&&GV&&t.width&&t.height&&t.width*t.height<101376&&(n.width=t.width,n.height=t.height),t.frameRate&&(n.frameRate=t.frameRate),!!jY(n)||n)}var rEA=iEA;function J$(t){return UV((i,n)=>async function(...c){const I=await i.apply(this,c);return await t.call(this,...c),I})}function UV(t){return function(i,n,c){return c.value=t(c.value,n),c}}var aEA=(()=>{let t=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&Wo.info(`visibility change: ${document.visibilityState}`),t||(document.addEventListener("visibilitychange",()=>{Wo.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),t=!0)}})(),gEA=0,cEA=class{constructor(t){Be(this,"log"),Be(this,"isRunning",!1),Be(this,"queue",[]);let i="fq"+ ++gEA;t&&(i+=`|${t}`),this.log=Wo.createLogger({id:i})}get length(){return this.queue.length}get lastQueueItem(){return this.length===0?null:this.queue[this.length-1]}push(t,i=!1){var n,c;const I=Rn({},t),C=new Promise((f,w)=>{I.resolve=f,I.reject=w});return I.promise=C,i?this.length<=1?this.queue.push(I):(c=(n=this.lastQueueItem)==null?void 0:n.promise)==null||c.then(I.resolve,I.reject):this.queue.push(I),this.log.debug(`push ${this.length}`,t.funcName,t.args),this.isRunning||this.callNext(),C}shift(){const t=this.queue.shift();return this.log.debug(`shift ${this.length}`,t?.funcName,t?.args),t}callNext(){if(this.isRunning||this.length===0)return;const{fn:t,args:i,context:n,resolve:c,reject:I,funcName:C}=this.queue[0];this.log.debug("callNext",this.length,C,i),this.isRunning=!0,t.apply(n,i).then(c,I).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},d6=new WeakMap;function lEA(t=!1){return function(i,n,c){const I=c.value;return c.value=function(...C){const f=d6.get(this)||new cEA;return d6.set(this,f),f.push({fn:I,args:C,context:this,funcName:n},t)},c}}function H$(t,i){return UV((n,c)=>function(...I){const C=t;try{const f=n.apply(this,I),w=Yc();return f7(f)?f.then(_=>(i?dr.addSuccessEvent({key:C,cost:Yc()-w}):dr.addSuccessEvent({key:C}),_)).catch(_=>{throw dr.addFailedEvent({key:C,error:_}),_}):(dr.addSuccessEvent({key:C}),f)}catch(f){throw dr.addFailedEvent({key:C,error:f}),f}})}function AI(...t){}var IEA=t=>t();function uEA(){this.dispose()}var EEA=()=>typeof __FASTRX_DEVTOOLS__<"u",dEA=1,uT=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const i=new hEA(t,this,this.streamId++);return pl.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},K4=class{constructor(){this.defers=new Set,this.disposed=!1}next(t){}complete(){this.dispose()}error(t){this.dispose()}get bindDispose(){return()=>this.dispose()}dispose(){this.disposed=!0,this.complete=AI,this.error=AI,this.next=AI,this.dispose=AI,this.subscribe=AI,this.doDefer()}subscribe(t){return t instanceof uT?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(IEA),this.defers.clear()}defer(t){this.defers.add(t)}removeDefer(t){this.defers.delete(t)}reset(){this.disposed=!1,delete this.complete,delete this.next,delete this.dispose,delete this.next,delete this.subscribe}resetNext(){delete this.next}resetComplete(){delete this.complete}resetError(){delete this.error}},lB=class extends K4{constructor(t){super(),this.sink=t,t.defer(this.bindDispose)}next(t){this.sink.next(t)}complete(){this.sink.complete()}error(t){this.sink.error(t)}},CEA=class extends K4{constructor(t,i=AI,n=AI,c=AI){if(super(),this._next=i,this._error=n,this._complete=c,this.then=AI,t instanceof uT){const I={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{pl.defer(I,0)}),pl.create(I),pl.pipe(I),this.sourceId=I.id,this.subscribe(t),pl.subscribe({id:I.id,end:!0}),i==AI?this._next=C=>pl.next(I,0,C):this.next=C=>{pl.next(I,0,C),i(C)},c==AI?this._complete=()=>pl.complete(I,0):this.complete=()=>{this.dispose(),pl.complete(I,0),c()},n==AI?this._error=C=>pl.complete(I,0,C):this.error=C=>{this.dispose(),pl.complete(I,0,C),n(C)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function ih(t,...i){return i.reduce((n,c)=>c(n),t)}function aC(t,i,n){if(EEA()){const c=Object.defineProperties(Object.setPrototypeOf(t,uT.prototype),{streamId:{value:0,writable:!0,configurable:!0},name:{value:i,writable:!0,configurable:!0},args:{value:n,writable:!0,configurable:!0},id:{value:0,writable:!0,configurable:!0}});pl.create(c);for(let I=0;I{if(c instanceof uT){const I=aC(C=>{const f=new t(C,...n);f.sourceId=I.id,f.subscribe(c)},i,arguments);return I.source=c,pl.pipe(I),I}return I=>c(new t(I,...n))}}}function by(t,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:t,payload:i}})}var hEA=class extends lB{constructor(t,i,n){super(t),this.source=i,this.id=n,this.sourceId=t.sourceId,this.defer(()=>{pl.defer(this.source,this.id)})}next(t){pl.next(this.source,this.id,t),this.sink.next(t)}complete(){pl.complete(this.source,this.id),this.sink.complete()}error(t){pl.complete(this.source,this.id,t),this.sink.error(t)}},pl={addSource(t,i){by("addSource",{id:t.id,name:t.toString(),source:{id:i.id,name:i.toString()}})},next(t,i,n){by("next",{id:t.id,streamId:i,data:n&&n.toString()})},subscribe({id:t,end:i},n){by("subscribe",{id:t,end:i,sink:{nodeId:n&&n.nodeId,streamId:n&&n.streamId}})},complete(t,i,n){by("complete",{id:t.id,streamId:i,err:n?n.toString():null})},defer(t,i){by("defer",{id:t.id,streamId:i})},pipe(t){by("pipe",{name:t.toString(),id:t.id,source:{id:t.source.id,name:t.source.toString()}})},update(t){by("update",{id:t.id,name:t.toString()})},create(t){t.id||(t.id=dEA++),by("create",{name:t.toString(),id:t.id})}},BEA=class extends K4{constructor(t){super(),this.source=t,this.sinks=new Set}add(t){t.defer(()=>this.remove(t)),this.sinks.add(t).size===1&&(this.reset(),this.subscribe(this.source))}remove(t){this.sinks.delete(t),this.sinks.size===0&&this.dispose()}next(t){this.sinks.forEach(i=>i.next(t))}complete(){this.sinks.forEach(t=>t.complete()),this.sinks.clear()}error(t){this.sinks.forEach(i=>i.error(t)),this.sinks.clear()}};function q$(){return t=>{const i=new BEA(t);if(t instanceof uT){const n=aC(c=>{i.add(c)},"share",arguments);return i.sourceId=n.id,n.source=t,pl.pipe(n),n}return aC(i.add.bind(i),"share",arguments)}}function K$(...t){return aC(i=>{const n=new lB(i);let c=t.length;n.complete=()=>{--c===0&&i.complete()},t.forEach(n.bindSubscribe)},"merge",arguments)}function QEA(...t){return aC(i=>{const n=new Map;t.forEach(c=>{const I=new lB(i);n.set(c,I),I.complete=()=>{n.delete(c),n.size===0?i.complete():I.dispose()},I.next=C=>{n.delete(c),n.forEach(f=>f.dispose()),I.resetNext(),I.resetComplete(),I.next(C)}}),t.forEach(c=>n.get(c).subscribe(c))},"race",arguments)}function pEA(...t){return i=>aC((n,c=0,I=t.length)=>{for(;c{n.next=I=>c.next(I),n.complete=()=>c.complete(),n.error=I=>c.error(I),t&&c.subscribe(t)},"subject",i));return n.next=AI,n.complete=AI,n.error=AI,n}function mEA(t){return aC(i=>{let n=0;const c=setInterval(()=>i.next(n++),t);return i.defer(()=>{clearInterval(c)}),"interval"},"interval",arguments)}function fEA(t,i){return aC(n=>{let c=0;const I=setTimeout(()=>{n.removeDefer(C),n.next(c++),i||n.complete()},t),C=()=>clearTimeout(I);n.defer(C)},"timer",arguments)}function f3(t,i){return n=>{const c=I=>n.next(I);n.defer(()=>i(c)),t(c)}}function yE(t,i){if("on"in t&&"off"in t)return aC(f3(n=>t.on(i,n),n=>t.off(i,n)),"fromEvent",arguments);if("addListener"in t&&"removeListener"in t)return aC(f3(n=>t.addListener(i,n),n=>t.removeListener(i,n)),"fromEvent",arguments);if("addEventListener"in t)return aC(f3(n=>t.addEventListener(i,n),n=>t.removeEventListener(i,n)),"fromEvent",arguments);throw"target is not a EventDispachter"}function yEA(){return aC(t=>t.complete(),"empty",arguments)}var DEA=class extends lB{constructor(t,i,n){super(t),this.filter=i,this.thisArg=n}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},tT=Pv(DEA,"filter"),SEA=class extends lB{constructor(t,i){super(t),this.count=i}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},MEA=Pv(SEA,"take"),vEA=class extends lB{constructor(t,i){super(t);const n=new lB(t);n.next=()=>{n.doDefer(),t.complete()},n.complete=uEA,n.subscribe(i)}},ET=Pv(vEA,"takeUntil"),REA=class extends lB{constructor(t,i){super(t),this.f=i}next(t){this.f(t)||(this.next=super.next,this.next(t))}},wEA=Pv(REA,"skipWhile"),_EA=class extends lB{constructor(t,i,n){super(t),this.mapper=i,this.thisArg=n}next(t){super.next(this.mapper.call(this.thisArg,t))}},W$=Pv(_EA,"map"),TEA=class extends lB{constructor(t,i,n){super(t),this.data=i,this.context=n}next(t){const i=this.context.combineResults;i?this.sink.next(i(this.data,t)):this.sink.next(t)}tryComplete(){this.context.resetComplete(),this.dispose()}},NEA=class z$ extends lB{constructor(i,n,c){super(i),this.makeSource=n,this.combineResults=c,this.index=0}subInner(i,n){const c=this.currentSink=new n(this.sink,i,this);this.complete===z$.prototype.complete&&(this.complete=this.tryComplete),c.complete=c.tryComplete,c.subscribe(this.makeSource(i,this.index++))}complete(){this.sink.complete()}tryComplete(){this.currentSink.resetComplete(),this.dispose()}},C6=class extends TEA{},Z$=class extends NEA{next(t){this.subInner(t,C6),this.next=i=>{this.currentSink.dispose(),this.subInner(i,C6)}}},GEA=Pv(Z$,"switchMap");function bEA(t){return(i,n)=>t(()=>i,n)}var X$=bEA(Pv(Z$,"switchMapTo")),Fv=(t=AI,i=AI,n=AI)=>c=>new CEA(c,t,i,n),$$=(t=>(t[t.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",t[t.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",t))($$||{}),pv=class extends q4{constructor(t,i){super({mediaType:t,PlayerClass:i}),Be(this,"isRemote",!1),Be(this,"deviceId"),Be(this,"groupId",""),Be(this,"label",""),Be(this,"sourceTrack"),Be(this,"enableAutoSwitchWhenRecapturing",!0),Be(this,"_isRecapturing",!1),Be(this,"_lastRecaptureTime",0),Be(this,"_onMuteTimeoutId",-1),Be(this,"_encodeCheckTimeoutId",-1),Be(this,"recaptureMode",0),Be(this,"profile"),Be(this,"retryEncodeFailed")}get enableEncodeFrame(){return!1}get isPublishing(){return this.state.toString()==="publishing"}get isPublished(){return this.state==="publish"}get isUseCustomSource(){return!(!this.mediaTrack||this.sourceTrack===this.mediaTrack)}encodeFrame(t,i){throw new Error("Method not implemented.")}installTrackEvent(t){t.addEventListener(ei.MUTE,this.onTrackMuted),t.addEventListener(ei.UNMUTE,this.onTrackUnmuted),t.addEventListener(ei.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===ei.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(ei.MUTE,this.onTrackMuted),t.removeEventListener(ei.UNMUTE,this.onTrackUnmuted),t.removeEventListener(ei.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(t,i=!1){var n,c;const I=this.sourceTrack;try{const C=Yc();let f;ms.emit(mn.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(f=new MediaStream,f.addTrack(t.customSource)):(i||(n=this.sourceTrack)==null||n.stop(),f=await rEA(t));const w=f.getTracks()[0];return await this.setInputMediaStreamTrack(w),t.customSource||(this.sourceTrack=w,this.updateDeviceIdInUse(),this.listenDeviceChange()),ms.emit(mn.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Yc()-C,profile:this.profile,room:(c=this.manager)==null?void 0:c.room}),f}catch(C){throw ms.emit(mn.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:C}),this.log.error(`getUserMedia error observed ${C}`),C}finally{i&&I?.stop()}}setOutputMediaStreamTrack(t){var i;if(super.setOutputMediaStreamTrack(t),this.setStateToReady(),this.isPublishing||this.isPublished)return(i=this.room)==null?void 0:i.replaceTrack(this)}get hasFlag(){var t,i;const n=D7(((t=this.room)==null?void 0:t.localPublishFlag)||0,((i=this.room)==null?void 0:i.userId)||"");return this.mediaType===4&&n.hasVideo||this.mediaType===1&&n.hasAudio||this.mediaType===2&&n.hasAuxiliary}async publish(t,i){return this.room=t,this.room.localTracks.add(this),this.emit("4",{mediaType:this.strMediaType,state:"starting",prevState:"stopped"}),this.userId=t.userId,this._log.bindParent(t.getLogger()),await i,this._checkPublishFlag(t)}_checkPublishFlag(t){return new Promise(async(i,n)=>{var c,I,C,f,w;const _=()=>n(new fl({code:qg.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==Ar.INIT&&this.state!=="ready"||_(),ih(yE(t,"local-publish-flag-changed"),tT(()=>this.hasFlag),ET(K$(yE(this,Ar.INIT),yE(this,"ready"))),Fv(i,n,_))),(C=(I=(c=this.room)==null?void 0:c.networkQuality)==null?void 0:I.hadRecentBadUplink)==null?void 0:C.call(I,2))return i();const N=t.heartbeatCount,L=((w=(f=this.mediaTrack)==null?void 0:f.stats)==null?void 0:w.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var q,lA,tA,BA,IA,gA,RA,HA;if((tA=(lA=(q=this.room)==null?void 0:q.networkQuality)==null?void 0:lA.hadRecentBadUplink)!=null&&tA.call(lA,2)||t.heartbeatCount-N<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((BA=this.mediaTrack)!=null&&BA.stats){const me=this.mediaTrack.stats.totalFrames||0;me-L===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",me)}const ZA=this.kind===ei.AUDIO,KA=this.stat.bytesSent>0;if(dr[KA?"addSuccessEvent":"addFailedEvent"]({key:ZA?503700:513702}),!ZA){const me={H264:513704,H265:513705,VP8:513706}[((gA=(IA=this.room)==null?void 0:IA.videoCodec)==null?void 0:gA.toUpperCase())||"H264"];me&&dr[KA?"addSuccessEvent":"addFailedEvent"]({key:me})}if(!KA){if(dr.addEnum({key:ZA?503701:513703,value:b4()}),ah.uploadEvent({log:`stat-encode-failed-${this.kind}-${g$()||l$()}`,userId:this.userId}),this.log.warn(ZA?"encode failed":`${(HA=(RA=this.room)==null?void 0:RA.videoCodec)==null?void 0:HA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await IT(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),n(new fl({message:`${this.strMediaType} encode failed`,code:ZA?qg.AUDIO_ENCODE_FAILED:qg.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),ms.emit(mn.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&qY){const{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:n}=this.sourceTrack;await zuA({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=t,this.label=n,i&&(this.groupId=i),CW().then(c=>{const I=c.find(C=>{let f=C.deviceId===t;return i&&(f=f&&C.groupId===i),f});I&&this.emit("2",I)}))}}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(t=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===ei.AUDIO&&!juA(this.sourceTrack)||this.kind===ei.VIDEO&&!KuA(this.sourceTrack)||this._isRecapturing||t&&GV&&ld)}onTrackMuted(){super.onTrackMuted(),aEA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),W1):this._onMuteTimeoutId=setTimeout(async()=>{var t;if((t=this.sourceTrack)!=null&&t.muted){if((vu||cC)&&document.visibilityState!=="visible")return;this.recapture(await this.getRecoverCaptureDeviceId())}},5e3))}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}async onTrackEnded(){if(super.onTrackEnded(),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),W1);this.emit("7"),this.recapture(await this.getRecoverCaptureDeviceId())}}async recapture(t,i=!1){var n;if(this._isRecapturing||!this.sourceTrack)return;this.log.warn("recapture trying");const c=this.sourceTrack;i||(n=this.sourceTrack)==null||n.stop(),this._isRecapturing=!0,this._lastRecaptureTime=Date.now();const I={useExactDeviceId:!0};if(t==="user"||t==="environment")I.facingMode=t;else{let C;(this.kind==="audio"?await kU():await Rv()).find(f=>f.deviceId===t)&&(C=t),I.deviceId=C}return this.capture(I,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),ms.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(C=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${C.message}`),this.emit("5",C),ms.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this,error:C})}).finally(()=>{i&&c?.stop()})}async getRecoverCaptureDeviceId(){const t=this instanceof FV;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const n=(HL.get(i)||0)+1;if(HL.set(i,n),n>=3&&this.enableAutoSwitchWhenRecapturing){const c=t?(await Rv()).find(I=>!HL.has(I.deviceId)):(await kU()).find(I=>!HL.has(I.deviceId));c&&(this.log.warn(`${i} capture fail ${n} times, change new ${c.deviceId}`),i=c.deviceId)}}return i}stopCapture(){var t;this.sourceTrack&&(this.sourceTrack.stop(),ms.emit(mn.LOCAL_TRACK_STOPPED,{track:this}),this.uninstallTrackEvent(this.sourceTrack)),this._inputTrack&&this.uninstallTrackEvent(this._inputTrack),(t=this.manager)==null||t.removeInput(this),this._onMuteTimeoutId&&clearTimeout(this._onMuteTimeoutId)}close(){super.close(),this.stopCapture()}};Cc([Su(Ar.INIT,"ready",{ignoreError:!0,sync:!0})],pv.prototype,"setStateToReady"),Cc([lEA()],pv.prototype,"capture"),Cc([Su("ready","publish",{ignoreError:!0,success(){ms.emit(mn.LOCAL_TRACK_PUBLISHED,{track:this,room:this.room}),this.emit("4",{mediaType:this.strMediaType,state:"started",prevState:"starting"}),this.log.info("published")},fail(t){var i;(i=this.room)==null||i.localTracks.delete(this);let n="error";const c=t instanceof fl?t:t.cause instanceof fl?t.cause:t;let I=!1;c instanceof fl&&(c.message.includes("timeout")?n="timeout":c.code===qg.API_CALL_ABORTED&&(I=!0,n="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:n,error:c}),this.log[I?"info":"error"]("publish failed",c)}}),H$(521714,!1)],pv.prototype,"publish"),Cc([UV(t=>async function(){const i=this.state==="publish"?"started":"starting";t.call(this),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:i,reason:"api-call"}),clearTimeout(this._encodeCheckTimeoutId)}),Su([],"ready",{sync:!0})],pv.prototype,"unpublish");var HL=new Map;ms.on(mn.SWITCH_DEVICE_SUCCESS,t=>{t.track.deviceId&&HL.delete(t.track.deviceId)});var kEA=class{constructor(t,i=!1){this.dataView=t,this.isSEI&&(i?this.addPreventionByte():this.removePreventionByte())}addPreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-2,n=[];let c=0;for(let C=t;C<=i;C++){const f=this.dataView.getInt8(C);switch(f){case 0:case 1:case 2:case 3:c===2&&(n.push(3),c=0),f===0?c+=1:c=0,n.push(f);break;default:c=0,n.push(f)}}n.push(this.dataView.getInt8(this.dataView.byteLength-1));const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...n]).buffer);this.dataView=I}removePreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-1,n=[];let c=0;for(let C=t;C<=i;C++)switch(this.dataView.getInt8(C)){case 0:c++,n.push(this.dataView.getInt8(C));break;case 3:c!==2&&n.push(this.dataView.getInt8(C)),c=0;break;default:n.push(this.dataView.getInt8(C)),c=0}const I=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...n]).buffer);this.dataView=I}get seiPayloadStartIndex(){let t=6;for(let i=6;i=this.dataView.byteLength?0:31&this.dataView.getUint8(t)}getStartCodeLength(){return this.dataView.byteLength>=4&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===0&&this.dataView.getUint8(3)===1?4:this.dataView.byteLength>=3&&this.dataView.getUint8(0)===0&&this.dataView.getUint8(1)===0&&this.dataView.getUint8(2)===1?3:0}get isIDR(){return this.naluType===5}get isSPS(){return this.naluType===7}get isPPS(){return this.naluType===8}get isSEI(){return this.naluType===6}},LEA=class{constructor(){Be(this,"_seiMessageList",[]),Be(this,"_smallSeiMessageList",[]),Be(this,"_seiPayloadType",243)}encodeSEINalu(t){const i=t.byteLength,n=parseInt(String(i/255),10),c=i%255,I=[];I.push(0,0,0,1,6,this._seiPayloadType);for(let f=0;f0&&t.data.byteLength>0){const c=9-this.getNaluCount(t.data);if(c<=0)return 0;const I=n.splice(0,c).reverse().map(this.encodeSEINalu.bind(this)),C=I.reduce((L,q)=>L+q.dataView.byteLength,0),f=new ArrayBuffer(C+t.data.byteLength),w=new DataView(f),_=new DataView(t.data);let N=0;for(let L=0;L{var c;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const I=FY(((c=this.room)==null?void 0:c.sdkAppId)||0)?wZ:RZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${I}`),this.setProfile(gB(Rn({},this.profile),{width:1920,height:1080})),this.applyProfile()}};this.on("input-media-track-changed",n),this.on("publish",n),this.handleCameraAdded=this.handleCameraAdded.bind(this),this.handleCameraRemoved=this.handleCameraRemoved.bind(this)}get facingMode(){if(qY&&this.mediaTrack)return this.mediaTrack.getSettings().facingMode}get contentHint(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)||""}get isQosClearFirst(){var t;return((t=this._inputTrack)==null?void 0:t.contentHint)==="detail"}get hasSmall(){var t;return!!((t=this.manager)!=null&&t.hasSmall)}async setMute(t){var i,n,c;if(rh(t)){if(this.muteImage===t)return;await((i=this.manager)==null?void 0:i.deleteWatermark("mute")),await((n=this.manager)==null?void 0:n.setWatermark({x:0,y:0,width:this.settings.width,height:this.settings.height,type:"mute",zIndex:999,imageUrl:t,fillVideo:!0})),this.muteImage=t,super.setMute(!1)}else this.muteImage&&(await((c=this.manager)==null?void 0:c.deleteWatermark("mute")),this.muteImage=void 0),super.setMute(t)}async capture({deviceId:t,facingMode:i,useExactDeviceId:n=!0,customSource:c,retryWhenExactFailed:I=!0}){const C={audio:!1,video:!0,facingMode:i||this.facingMode,cameraId:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,useExactDeviceId:n,retryWhenExactFailed:I,customSource:c};if(C.facingMode==="environment"){const f=await this.getDeviceIdWhenUsingBackCamera();f&&(C.cameraId=f)}return super.capture(C)}setProfile(t){var i;const n=this.fallbackProfile(t);if(n.bitrate&&(this.isNeedToSetBandwidth=n.bitrate!==this.profile.bitrate),this.isAllowed2k4k(this.profile))super.setProfile(n);else{const c=FY(((i=this.room)==null?void 0:i.sdkAppId)||0)?wZ:RZ;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${c}`),super.setProfile(gB(Rn({},this.profile),{width:1920,height:1080}))}}async applyProfile(){var t,i;if(!this.mediaTrack)return;const{width:n=0,height:c=0}=(this.sourceTrack||this.mediaTrack).getSettings(),I=n*c,C=this.settings,f=C.height!==this.profile.height||C.width!==this.profile.width||C.frameRate!==this.profile.frameRate;if(f&&(Uv===16&&this.deviceId?await this.recapture(this.deviceId):(p4(this.outMediaTrack)?await((t=this.outMediaTrack)==null?void 0:t.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})):await((i=this.sourceTrack||this.mediaTrack)==null?void 0:i.applyConstraints({width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate})),this.manager&&this.manager.changeInput(this)),this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1})),this.isNeedToSetBandwidth&&this.room&&this.room.setBandWidth){this.isNeedToSetBandwidth=!1;const{width:w=0,height:_=0}=(this.sourceTrack||this.mediaTrack).getSettings(),N=w*_;return f&&N&&I&&N===I?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:ei.VIDEO,videoType:ei.BIG})}}get settings(){const t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return qY&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:_7(this.settings,this.profile)}isAllowed2k4k(t){var i;return!this.room||!this.room.scheduleResult||!!this.isScreen||t.height*t.width<3686400||((i=this.room.scheduleResult.trtcAutoConf)==null?void 0:i["2k4k"])===1}isNeedToSwitchDevice(t){return!(!this.mediaTrack||this.deviceId===t||this.facingMode===t)}async switchDevice(t){try{if(!this.isNeedToSwitchDevice(t)&&!this.isUseCustomSource)return;const i={useExactDeviceId:!0,retryWhenExactFailed:!1};t==="user"||t==="environment"?i.facingMode=t:i.deviceId=t,this.sourceTrack&&this.sourceTrack.stop(),await this.capture(i),ms.emit(mn.SWITCH_DEVICE_SUCCESS,{track:this}),this.log.info("switch camera success")}catch(i){throw this.log.error(`switch camera failed ${i}`),this.deviceId&&this.recapture(this.deviceId),i}}async getDeviceIdWhenUsingBackCamera(){let t;try{if(A$&&!N4&&T$){const i=(await Rv(!0)).map(c=>{var I;return gB(Rn({},c),{capabilities:(I=c.getCapabilities)==null?void 0:I.call(c)})}).filter(c=>{var I,C;return(C=(I=c.capabilities)==null?void 0:I.facingMode)==null?void 0:C.includes("environment")});let n=i[0];i.forEach(c=>{var I,C,f,w;const{capabilities:_}=c;((I=_.width)!=null&&I.max&&((C=_.height)!=null&&C.max)?_.width.max*_.height.max:0)>((f=n.capabilities.width)!=null&&f.max&&((w=n.capabilities.height)!=null&&w.max)?n.capabilities.width.max*n.capabilities.height.max:0)&&(n=c)}),n?.capabilities&&(this._log.info("use max resolution back camera",n),t=n.deviceId)}}catch(i){this._log.warn("get max res camera failed",i)}return t}async updateSmallConfig(t){var i,n;this._log.info(`update small stream config: ${JSON.stringify(t)}`);const c=!this.small;this.small=this.fallbackProfile(t,!0),await((i=this.manager)==null?void 0:i.update()),c&&await((n=this.room)==null?void 0:n.enableSmall(!0)),this.log.info("update small stream config success")}fallbackProfile(t,i=!1){const n=t.width>t.height,c=Rn({},t);return t.width*t.height<=19200&&cC&&sD&&(this.log.warn(`${i?"small ":""}resolution is ${t.width}*${t.height}, fallback to 240*180 for android chrome`),c.width=n?240:180,c.height=n?180:240,c.bitrate=Math.max(t.bitrate,150)),t.width*t.height>921600&&RIA&&(c.width=n?1280:720,c.height=n?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),MIA(wQ,"14.3")&&a$(wQ,"14.0",!0)&&this.on("7",()=>{const I=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=I?640:480,this.profile.height=I?480:640,this.log.warn("reduce the resolution to 480p on iOS 14.0 ~ 14.2")):this.profile.width*this.profile.height>230400&&(this.profile.width=I?640:360,this.profile.height=I?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(sD||rC)&&!TIA()&&t.width*t.height<=230400&&t.width/t.height===16/9&&(this._scaleResolutionDownBy=1280/t.width,c.width=1280,c.height=720,this.log.warn(`capture 720p, scale: ${this._scaleResolutionDownBy}`)),c}stopSmall(){var t,i;this.small&&(delete this.small,(t=this.manager)==null||t.update(),(i=this.room)==null||i.enableSmall(!1))}listenDeviceChange(){DQ&&!DQ.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&DQ.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(t){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${$$[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(t)}`),this.recaptureMode===0){Ec(this.userId,{eventId:2003,param1:7,streamType:2});const n=await Rv();n[0]?this.recapture(n[0].deviceId):i=!0}i&&DQ.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(DQ.off("videoInputAdded",this.handleCameraAdded,this),this.log.warn(`camera added: ${JSON.stringify(t)}`),this.recapture(t.deviceId))}encodeFrame(t,i){if(!this.manager)return t;const n=i?8:this.mediaType;return this.manager.encodePipeline.reduceRight((c,I)=>I?I({frame:c,mediaType:n}):c,t)}get enableEncodeFrame(){return!!this.manager&&this.manager.encodePipeline.some(t=>t)}play(t,i){return er(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(t,i)}close(){DQ.off("videoInputAdded",this.handleCameraAdded,this),DQ.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}async recapture(t){try{await super.recapture(t)}catch(i){const n=(await Rv()).find(c=>c.deviceId!==t);if(!n)throw i;await super.recapture(n.deviceId)}}setContentHint(t){this.mediaTrack&&"contentHint"in this.mediaTrack&&(this.mediaTrack.contentHint!==t&&(this.log.info(`setContentHint ${t}`),this.mediaTrack.contentHint=t),this.outMediaTrack&&this.outMediaTrack.contentHint!==t&&(this.outMediaTrack.contentHint=t))}setRotation(t){this.manager&&(this.isScreen||er(t)||t!==this.rotation&&(this.rotation=t,this.manager.rotation=t))}};Cc([J$(function(t){this.setContentHint(t.contentHint||"motion")})],FV.prototype,"capture");var UEA=[-1,-1,1,-1,-1,1,1,1],FEA=[0,0,1,0,0,1,1,1],qL=class hW extends Ar{constructor(i,n){if(super(),this.context=i,Be(this,"name"),Be(this,"input"),Be(this,"output"),Be(this,"texture"),Be(this,"ctx2d",null),Be(this,"fbo"),Be(this,"width",0),Be(this,"height",0),Be(this,"x",0),Be(this,"y",0),Be(this,"program"),Be(this,"vertexShader"),Be(this,"fragmentShader"),Be(this,"totalFrames",0),Be(this,"dropFrames",0),Be(this,"matchInputSize",!0),Be(this,"texCoordBuffer"),Be(this,"positionBuffer"),Be(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Be(this,"cost",0),Be(this,"_canvas",null),Be(this,"_image"),Be(this,"log"),this.context.on("disconnect",this.close,this),this.name=n.name,this.log=n.logger,this.matchInputSize=n.matchInputSize!==!1,this.width=n.width||i.width,this.height=n.height||i.height,this._image=n.image,i instanceof UU)i.ctx&&n.create2d&&(typeof OffscreenCanvas=="function"&&Uv!==16?this._canvas=new OffscreenCanvas(this.width,this.height):(this._canvas=document.createElement("canvas"),this._canvas.width=this.width,this._canvas.height=this.height),this.ctx2d=this._canvas.getContext("2d"),this._image=this._canvas);else try{const c=i.ctx;this.texCoordBuffer=this.createBuffer(FEA),this.positionBuffer=this.createBuffer(UEA),n.createTexture!==!1&&(this.texture=c.createTexture(),this.useTexture(),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(c.TEXTURE_2D,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),c.pixelStorei(c.UNPACK_ALIGNMENT,1)),n.useFbo&&(this.fbo=c.createFramebuffer(),this.useBufferFrame(),this.useTexture(),c.texImage2D(c.TEXTURE_2D,0,c.RGBA,this.width,this.height,0,c.RGBA,c.UNSIGNED_BYTE,null),c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,this.texture,0)),n.useDefaultProgram?this.program=i.defaultProgam:(n.vertexShaderSource||n.fragmentShaderSource)&&(this.vertexShader=n.vertexShaderSource?i.createShader(c.VERTEX_SHADER,n.vertexShaderSource):i.defaultVShader,this.fragmentShader=n.fragmentShaderSource?i.createShader(c.FRAGMENT_SHADER,n.fragmentShaderSource):i.defaultFShader,this.program=i.createProgram(this.vertexShader,this.fragmentShader))}catch(c){this.context.destroy(new fl({code:qg.VIDEO_MANAGER_ERROR,extraCode:3,message:`create video node ${this.name} error ${c.message||c}`}))}}get image(){return this._image}set image(i){this._image=i}createFramebuffer(i){const n=this.context.ctx,c=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,c),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),c}connect(i,...n){return i.addInput(this,...n),this.output=i,i}addInput(i,...n){this.input=i,this.matchInputSize&&i.width&&i.height&&this.resize(i.width,i.height)}requestFrame(i){const n=Date.now();return!!(this.context instanceof BW&&this.render(i)||this.context instanceof UU&&this.render2d(i))&&(this.totalFrames++,this.cost=Date.now()-n,!0)}render2d(i){var n;return!!((n=this.input)!=null&&n.requestFrame(i))&&this.draw2d(this.input.image,0,0,this.width,this.height)}update(i=0){var n;(n=this.output)==null||n.update(i)}disconnect(...i){var n;(n=this.output)==null||n.removeInput(this,...i),delete this.output}removeInput(i,...n){delete this.input}close(){var i,n;if(this.context.off("disconnect",this.close,this),(i=this.output)==null||i.removeInput(this),delete this.output,(n=this.input)==null||n.disconnect(),this.context instanceof BW){const c=this.context.ctx;c.deleteBuffer(this.texCoordBuffer),c.deleteBuffer(this.positionBuffer),this.fbo&&c.deleteFramebuffer(this.fbo),this.texture&&c.deleteTexture(this.texture),this.vertexShader&&this.vertexShader!==this.context.defaultVShader&&c.deleteShader(this.vertexShader),this.fragmentShader&&this.fragmentShader!==this.context.defaultFShader&&c.deleteShader(this.fragmentShader),this.program&&this.program!==this.context.defaultProgam&&c.deleteProgram(this.program)}this._canvas&&(this._canvas.width=0,this._canvas.height=0,this.ctx2d=null),this.removeAllListeners()}useTexture(){this.useTextures(this.texture)}useInputTexture(){var i;this.useTextures((i=this.input)==null?void 0:i.texture)}useTextures(...i){const n=this.context.ctx;i.forEach((c,I)=>{c&&(n.activeTexture(n.TEXTURE0+I),n.bindTexture(n.TEXTURE_2D,c))})}useProgram(){this.context.ctx.useProgram(this.program)}useBufferFrame(){const i=this.context.ctx;i.bindFramebuffer(i.FRAMEBUFFER,this.fbo||null)}createBuffer(i){const n=this.context.ctx,c=n.createBuffer();return n.bindBuffer(n.ARRAY_BUFFER,c),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW),c}setTexBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.texCoordBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}setPosBuffer(i){const n=this.context.ctx;n.bindBuffer(n.ARRAY_BUFFER,this.positionBuffer),n.bufferData(n.ARRAY_BUFFER,new Float32Array(i),n.STATIC_DRAW)}changeBufferData(i,n){const c=this.context.ctx;c.bindBuffer(c.ARRAY_BUFFER,i),c.bufferData(c.ARRAY_BUFFER,new Float32Array(n),c.STATIC_DRAW)}setAttributes(...i){const n=this.context.ctx;i.forEach((c,I)=>{n.enableVertexAttribArray(I),n.bindBuffer(n.ARRAY_BUFFER,c),n.vertexAttribPointer(I,2,n.FLOAT,!1,0,0)})}getVertexPoint(i,n){return[i/this.width*2-1,n/this.height*2-1]}layout2texCoords(i){return[...this.getVertexPoint(i.x,i.y),...this.getVertexPoint(i.x+i.width,i.y),...this.getVertexPoint(i.x,i.y+i.height),...this.getVertexPoint(i.x+i.width,i.y+i.height)]}resize(i,n){if(this.width!==i||this.height!==n){if(this.width=i,this.height=n,this._canvas&&(this._canvas.width=i,this._canvas.height=n),this.texture&&this.fbo){this.useTexture();const c=this.context.ctx;c.texImage2D(c.TEXTURE_2D,0,c.RGBA,i,n,0,c.RGBA,c.UNSIGNED_BYTE,null)}this.output&&this.output.matchInputSize&&this.output.resize(i,n)}}draw(i,n){this.setAttributes(i||this.positionBuffer,n||this.texCoordBuffer);const c=this.context.ctx;c.drawArrays(c.TRIANGLE_STRIP,0,4)}draw2d(i,n,c,I,C,f,w,_,N){const L=!(er(f)||er(w)||er(_)||er(N));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(L?this.ctx2d.putImageData(i,n,c,f,w,_,N):this.ctx2d.putImageData(i,n,c),this.emit(hW.RENDER,this.ctx2d.canvas)):(L?this.ctx2d.drawImage(i,f,w,_,N,n,c,I,C):this.ctx2d.drawImage(i,n,c,I,C),this.emit(hW.RENDER,i)),typeof VideoFrame<"u"&&i instanceof VideoFrame&&i.close(),!0)}drawBackGround2d(i){this.ctx2d&&(this.ctx2d.save(),this.ctx2d.fillStyle=i,this.ctx2d.fillRect(0,0,this.width,this.height),this.ctx2d.restore())}getInfo(){var i;const{totalFrames:n,x:c,y:I,width:C,height:f,name:w,cost:_}=this,N=Date.now(),L=(n-this.lastInfo.totalFrames)/((N-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:n,x:c,y:I,width:C,height:f,timestamp:N,fps:L,name:w,cost:_},Rn({parent:(i=this.input)==null?void 0:i.getInfo()},this.lastInfo)}createTexture(i){const n=this.context.ctx,c=n.createTexture();return this.useTextures(c),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.pixelStorei(n.UNPACK_ALIGNMENT,1),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,i),c}};Be(qL,"RENDER","render"),Cc([Su(Ar.INIT,"connected",{sync:!0})],qL.prototype,"connect"),Cc([Su("connected",Ar.INIT,{ignoreError:!0,sync:!0})],qL.prototype,"disconnect"),Cc([Su([],"closed",{sync:!0})],qL.prototype,"close");var WY=qL,OEA=ih(mEA(250),W$(()=>performance.now()),q$()),PEA=t=>i=>{const n=performance.now();ih(OEA,wEA(c=>c-n{if(t!==this.context.frameRate&&(MQ.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof BW){const i=this.context.ctx.getError();i&&this.context.destroy(new fl({code:qg.VIDEO_MANAGER_ERROR,extraCode:5,message:`${this.name} req ${this._sequence} render ${this.totalFrames} faild ${i}`}))}},{fps:this.context.frameRate})}render(t){var i;return!!((i=this.input)!=null&&i.requestFrame(t))&&(this.useProgram(),this.useBufferFrame(),this.useInputTexture(),this.draw(),this.emit(WY.RENDER,this.context._canvas),!0)}addInput(t,...i){super.addInput(t,...i),this.start(this.context.frameRate)}update(t=0){this.state!=="closed"&&(this._intervalId&&(MQ.clearTask(this._intervalId),this._intervalId=0,t===1&&(this.log.info(`${this.name} use requestVideoFrameCallback`),this.checkVisibilityChange=()=>{document.hidden&&(this.start(this.context.frameRate),this.log.info(`${this.name} use timer`),document.removeEventListener("visibilitychange",this.checkVisibilityChange))},document.addEventListener("visibilitychange",this.checkVisibilityChange))),this.requestFrame(this._sequence++))}removeInput(t){super.removeInput(t),MQ.clearTask(this._intervalId)}resize(t,i){super.resize(t,i),this.context.setSize(t,i)}close(){super.close(),MQ.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},VEA=class extends YEA{constructor(t,i){super(t,i),Be(this,"_videoTrack"),Be(this,"_muteOb"),Be(this,"_closedOb",yE(this,"closed")),Be(this,"_subscription"),Be(this,"_canvasContainer"),Number(AF)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=t.canvas.captureStream().getVideoTracks(),this._muteOb=yE(this._videoTrack,"mute"),ih(yE(this._videoTrack,"ended"),ET(this._closedOb),Fv(()=>{this.context.destroy(new fl({code:qg.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=ih(this._muteOb,ET(this._closedOb),X$(PEA(5e3)),tT(()=>{var t;return!!((t=this._videoTrack)!=null&&t.muted)&&!document.hidden}),Fv(()=>{this.context.destroy(new fl({code:qg.VIDEO_MANAGER_ERROR,extraCode:7,message:"video track muted"}))}))}disableCheckMute(){var t;(t=this._subscription)==null||t.dispose()}get videoTrack(){return this._videoTrack}putCanvasIntoDom(){this.context._canvas&&this._canvasContainer&&(document.getElementById(this.context._canvas.id)||(this.log.info(`${this.name} put canvas to body`),document.body.appendChild(this._canvasContainer),this._canvasContainer.appendChild(this.context._canvas)))}render(t){return this.putCanvasIntoDom(),super.render(t)}render2d(t){return this.putCanvasIntoDom(),super.render2d(t)}close(){var t,i;super.close(),(t=this._videoTrack)==null||t.stop(),delete this._videoTrack,(i=this._canvasContainer)==null||i.remove()}},AAA=class extends WY{constructor(t,i){super(t,Rn({name:"imageSource"},i)),Be(this,"_lastImage"),Be(this,"_totalFrames",0),Be(this,"_autoResize",!1),Be(this,"_canvasRendered"),Be(this,"videoCallbackId",0),Be(this,"waitingFirstFrame",!0),Be(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,Uv===16&&(this._canvasRendered=j$(),ih(this._canvasRendered,pEA(this._image),GEA(n=>n instanceof HTMLCanvasElement?yE(n,"rendered"):yEA()),ET(yE(this,"closed")),Fv(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const t=this.image;this.videoCallbackId&&t.cancelVideoFrameCallback(this.videoCallbackId),x4()&&!document.hidden&&(this.videoCallbackId=t.requestVideoFrameCallback((i,n)=>{this.waitingFirstFrame&&this.onFirstFrame(),document.hidden||(this._totalFrames=n.presentedFrames,this.update(1))}))}_render(t,i){var n;let{width:c,height:I}=this;const{image:C}=this;if(C instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:c,videoHeight:I}=C,!c||!I)return!1;C.width=c,C.height=I}else if(C instanceof HTMLImageElement||C instanceof ImageData||C instanceof ImageBitmap){if({width:c,height:I}=C,C!==this._lastImage)this._lastImage=C;else if(c===this.width&&I===this.height)return!0}else C instanceof HTMLCanvasElement||C instanceof OffscreenCanvas?({width:c,height:I}=C,this._lastImage=C):typeof VideoFrame<"u"&&C instanceof VideoFrame&&({displayWidth:c,displayHeight:I}=C,(n=this._lastImage)==null||n.close(),this._lastImage=C);if(!this._autoResize)return!0;if(this.width===c&&this.height===I&&this.totalFrames){if(i){this.useTexture();const f=this.context.ctx;f.texSubImage2D(f.TEXTURE_2D,0,0,0,f.RGBA,f.UNSIGNED_BYTE,C)}}else{if(i){this.useTexture();const f=this.context.ctx;f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,C)}this.resize(c,I)}return!0}get image(){return this._image}set image(t){var i;(i=this._canvasRendered)==null||i.next(t),this._image=t}render(t){return this._render(t,!0)}render2d(t){return this._render(t,!1)}},eAA=class extends AAA{constructor(t,i,n){super(t,n),this._player=i,this.name="videoPlayerSource",ih(yE(this._player,Jn.PLAYER_STATE_CHANGED),ET(yE(this,"closed")),tT(({state:c})=>c==="PLAYING"),Fv(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},JEA=class extends eAA{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,i,n){super(t,new Yy({id:n.name,track:i,muted:!0,container:null,objectFit:"contain",log:n.logger}),n),this.name="videoTrackSource",this._player.play()}replaceTrack(t){this.waitingFirstFrame=!0,this._player.setTrack(t),this._player.play()}close(){super.close(),this._player.stop()}},HEA=class extends WY{constructor(t,i,n){super(t,gB(Rn({name:"textSource"},n),{create2d:!0})),Be(this,"hasChange",!0),Be(this,"content",""),this.ctx2d.textBaseline="top",this.content=i.content||"",i.font&&(this.font=i.font),i.color&&(this.color=i.color)}set font(t){this.ctx2d&&(this.ctx2d.font=t,this.hasChange=!0)}get font(){var t;return((t=this.ctx2d)==null?void 0:t.font)||""}set color(t){this.ctx2d&&(this.ctx2d.fillStyle=t,this.hasChange=!0)}get color(){var t;return((t=this.ctx2d)==null?void 0:t.fillStyle)||""}render2d(t){return!(!this.ctx2d||!this.hasChange)&&(this.ctx2d.clearRect(0,0,this.width,this.height),this.drawMultilineText(0,0),this.hasChange=!1,!0)}render(t){return!1}resize(t,i){if(!this.ctx2d)return;const{color:n,font:c}=this;super.resize(t,i),this.color=n,this.font=c}drawMultilineText(t=0,i=0,n=1.2){if(!this.ctx2d)return;const c=this.ctx2d.measureText(this.content);i+=c.fontBoundingBoxAscent||c.actualBoundingBoxAscent||0;const I=this.font.match(/(\d+)px/),C=(I?parseInt(I[1],10):16)*n,f=this.content.split(` +`);for(let w=0;w{this.destroy(new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(t){let i="";return t&&(i=t.message,this.error=t,Ir.addFailedEvent({key:512702,error:t})),this.disconnect(),this.log.info(`video context destroy${i}`?`: ${i}`:""),this.ctx&&(this.ctx.deleteShader(this.defaultVShader),this.ctx.deleteShader(this.defaultFShader),this.ctx.deleteProgram(this.defaultProgam),delete this.ctx),t}set width(t){var i;(i=this.ctx)==null||i.viewport(0,0,t,this.height),super.width=t,this._canvas2d&&(this._canvas2d.width=t)}set height(t){var i;(i=this.ctx)==null||i.viewport(0,0,this.width,t),super.height=t,this._canvas2d&&(this._canvas2d.height=t)}setSize(t,i){var r;(r=this.ctx)==null||r.viewport(0,0,t,i),super.setSize(t,i),this._canvas2d&&(this._canvas2d.width=t,this._canvas2d.height=i)}createShader(t,i){const r=this.ctx,l=r.createShader(t);return r.shaderSource(l,i),r.compileShader(l),l}createProgram(t,i){const r=this.ctx,l=r.createProgram();return r.attachShader(l,t),r.attachShader(l,i),r.linkProgram(l),r.getProgramParameter(l,r.LINK_STATUS)||this.log.error(r.getProgramInfoLog(l)),l}};de(xL,"UNAVAILABLE","unavailable"),Cc([Du(Xn.INIT,"created",{sync:!0,fail(t){this.log.error("video gl context create failed",t.cause),Ir.addFailedEvent({key:512700,error:t.cause||t})},success(){this.log.info("video context created use webgl"),Ir.addSuccessEvent({key:512700})}})],xL.prototype,"create"),Cc([Du("created",Xn.INIT,{ignoreError:!0,sync:!0,success(t){t&&this.emit(xL.UNAVAILABLE,t),this.removeAllListeners()}})],xL.prototype,"destroy");var tW=xL,RU=class extends vU{constructor(){super(...arguments),de(this,"ctx")}create(t){if(this.hasAlpha=t.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${vU._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:t.alpha,willReadFrequently:t.willReadFrequently}),!this.ctx)throw new ml({code:qg.VIDEO_MANAGER_ERROR,extraCode:2,message:"2d context not supported"});this._canvas.addEventListener("contextlost",()=>{this.log.error("2d context lost")}),this._canvas.addEventListener("contextrestored",()=>{this.log.warn("2d context restored")})}destroy(t){let i="";t&&(i=t.message,this.error=t,Ir.addFailedEvent({key:512703,error:t})),this.disconnect(),this.log.info("video context destroy "+(i?`: ${i}`:"")),delete this.ctx,this._canvas&&(this._canvas.remove(),this._canvas.width=0,this._canvas.height=0,delete this._canvas),this.removeAllListeners(),Ir.addSuccessEvent({key:512703})}};Cc([Du(Xn.INIT,"created",{sync:!0,fail(t){this.log.error("video 2d context create failed",t.cause),Ir.addFailedEvent({key:512701,error:t.cause||t})},success(){this.log.info("video context created use 2d"),Ir.addSuccessEvent({key:512701})}})],RU.prototype,"create"),Cc([Du("created",Xn.INIT,{ignoreError:!0,sync:!0})],RU.prototype,"destroy");var v4=q7();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:v4,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var BEA=async function(t){let i=null;const r=mEA(t);Wo.info(`getDisplayMedia with constraints: ${JSON.stringify(r)}`);const l=await navigator.mediaDevices.getDisplayMedia(r);t.systemAudio&&l.getAudioTracks().length===0&&(I4&&iD<74||ld||sC)&&Wo.warn("Your browser not support capture system audio");const I=l.getVideoTracks()[0];if(I){if(t.frameRate)try{await I.applyConstraints({frameRate:{min:t.frameRate,ideal:t.frameRate},width:t.width,height:t.height})}catch(h){Wo.warn(`screen applyConstraints failed: ${h}`)}t.captureElement&&await QEA(I,t.captureElement)}if(t.audio){const h=pEA(t);Wo.info(`getUserMedia with constraints: ${JSON.stringify(h)}`),i=await navigator.mediaDevices.getUserMedia(h),l.addTrack(i.getAudioTracks()[0])}return l};async function QEA(t,i){var r;if("CropTarget"in window&&"fromElement"in CropTarget&&mv(t.cropTo))try{if(((r=t.getCaptureHandle())==null?void 0:r.handle)!==v4)return;const l=await CropTarget.fromElement(i);await t.cropTo(l)}catch(l){Wo.warn(`cropTo target failed ${l}`)}}function pEA(t){const i={echoCancellation:t.echoCancellation,autoGainControl:t.autoGainControl,noiseSuppression:t.noiseSuppression,sampleRate:t.sampleRate,channelCount:t.channelCount};return $n(t.microphoneId)||(i.deviceId=t.microphoneId),{audio:i,video:!1}}function mEA(t){const i={preferCurrentTab:t.preferDisplaySurface==="current-tab"||!!t.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},r={width:ld?{max:t.width}:{ideal:t.width,max:t.width},height:ld?{max:t.height}:{ideal:t.height,max:t.height},frameRate:t.frameRate,displaySurface:t.preferDisplaySurface||"monitor"};if(i.video=r,t.systemAudio){const{echoCancellation:l=!0,noiseSuppression:I=!1,autoGainControl:h=!1}=t;i.audio={echoCancellation:l,noiseSuppression:I,autoGainControl:h,sampleRate:48e3}}return i}var fEA=BEA,yEA=class extends DV{constructor(t){super(t,2),de(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),de(this,"objectFit","contain"),de(this,"isScreen",!0),this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var t,i;try{return v4===((i=(t=this.mediaTrack)==null?void 0:t.getCaptureHandle())==null?void 0:i.handle)}catch{return}}async capture({systemAudio:t=!1,autoGainControl:i,echoCancellation:r,noiseSuppression:l,audioTrack:I,videoTrack:h,captureElement:f,preferDisplaySurface:w}){var _;try{const G=Yc();let U;return h||I?(U=new MediaStream,h&&U.addTrack(h),I&&U.addTrack(I)):(U=await fEA({audio:!1,systemAudio:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:i,echoCancellation:r,noiseSuppression:l,captureElement:f,preferDisplaySurface:w}),this.sourceTrack=U.getVideoTracks()[0]),await this.setInputMediaStreamTrack(U.getVideoTracks()[0]),ps.emit(mn.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Yc()-G,profile:this.profile,room:(_=this.manager)==null?void 0:_.room}),U}catch(G){throw this.log.error(`getDisplayMedia error observed ${G}`),G instanceof ml?G:new ml({code:qg.INITIALIZE_FAILED,name:G.name,message:G.message})}}async switchDevice(t){throw new Error("Method not implemented.")}};function DEA(t=30,i=2){return yV((r,l)=>function(...I){return new Promise((h,f)=>{const w=setTimeout(()=>{const _=new ml({code:qg.API_CALL_TIMEOUT,message:`checkPendingPromise ${l}() timeout ${t}s`});(this.log||this._log||Wo).warn(_),i===2?f(_):i===1&&h()},1e3*t);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(w),r.apply(this,I).then(h,f).finally(()=>{clearTimeout(w),this._checkPendingPromiseSet&&w&&this._checkPendingPromiseSet.delete(w)})})})}Cc([m$(function(t){this.setContentHint(t.contentHint||"detail")})],yEA.prototype,"capture");var M_=class iW extends S4{constructor(i,r,l){super({userId:r.userId,sdkAppId:i.sdkAppId,mediaType:l,room:i}),this.room=i,this.user=r,de(this,"tinyId"),de(this,"isRemote",!0),de(this,"jitterBufferDelay",0),de(this,"availableState"),de(this,"remotePublishState"),de(this,"_triggerCheckDecodeSubject",S$(fE(this,iW.STATE_SUBSCRIBE))),de(this,"ignoreUpdatePlayingState"),this.tinyId=r.tinyId,this.availableState=new Xn(`${r.userId}-${this.mediaType}-available`,"remote-track-available"),this.remotePublishState=new Xn(`${r.userId}-${this.mediaType}-remote-publish`,"remote-track-publish"),$C(D$(fE(this,Xn.STATECHANGED),fE(this.remotePublishState,Xn.STATECHANGED)),M$(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),kv(w=>{this.availableState.state!==(w?Xn.ON:Xn.OFF)&&(this.availableState.state=w?Xn.ON:Xn.OFF),this.isRemotePublished&&this.ignoreUpdatePlayingState||this.updatePlayingState(w)}));const I=$C(fE(this.player,Vn.ERROR),$_(w=>w.code===MediaError.MEDIA_ERR_DECODE)),h=$C(quA(5e3),$_(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:!(this.player.isPlaying||(this.kind===$t.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0))||(this.reportDecodeResult(!0),!1))),f=$C(VuA(I,h),gT(fE(this,Xn.INIT)));$C(this._triggerCheckDecodeSubject,$_(()=>!this.ignoreDecodeError),w$(f),kv(w=>{this.reportDecodeResult(!1,w)}))}setMute(i){this.isRemotePublished&&super.setMute(i)}setInputMediaStreamTrack(i){super.setInputMediaStreamTrack(i),this.isRemotePublished&&this.isSubscribed&&this.player.setTrack(this.outMediaTrack)}checkDecodeResult(){this._triggerCheckDecodeSubject.next(!0)}waitHasMediaTrack(){return new Promise(i=>{this.mediaTrack?i():this.once("input-media-track-changed",i)})}get ignoreDecodeError(){var i,r,l,I;return(I=(l=(r=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:r.hadRecentBadDownlink)==null?void 0:l.call(r,2))!=null&&I||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===iW.STATE_SUBSCRIBE}get isAvailable(){return this.availableState.state===Xn.ON}get isNeedPlay(){return this.isAvailable&&this.isPlayCalled}subscribe(i){return i}unsubscribe(){this.streamType==="main"&&this.kind==="video"&&this.room.changeType(!1,this.user)}reportDecodeResult(i,r){var l,I;const h=this.kind===$t.AUDIO;if(Ir[i?"addSuccessEvent":"addFailedEvent"]({key:h?504700:514702}),!h){const f=((l=this.room)==null?void 0:l.downlinkVideoCodec.toUpperCase())||"H264";Ir[i?"addSuccessEvent":"addFailedEvent"]({key:W7[`DECODE_${f}_RESULT`]}),i||this.log.warn(`${(I=this.room)==null?void 0:I.downlinkVideoCodec} decode failed`)}i||(Ir.addEnum({key:h?504701:514703,value:u4()}),oh.uploadEvent({log:`stat-decode-failed-${this.kind}-${P7()||Y7()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===$t.AUDIO?`audioLevel: ${this.getAudioLevel()}`:`framesDecoded: ${this.stat.framesDecoded>0}`}`),this.emit("decode-failed",{error:r}))}updatePlayingState(i){if(this.player.isPlayCalled&&this.player.setTrack(this.playerMediaTrack),this.isPlayCalled&&this.player.isStopped===i){if(i&&(!this.isSubscribed||!this.isRemotePublished||!this.outMediaTrack))return void this.log.info(`abort play, isSubscribed: ${this.isSubscribed} isAvailable: ${this.isRemotePublished} hasTrack: ${!!this.outMediaTrack} `);super.updatePlayingState(i)}}close(){super.close(),this.outMediaTrack&&this.uninstallTrackEvent(this.outMediaTrack)}onFlagChanged(){this.remotePublishState.state=this.isRemotePublished?Xn.ON:Xn.OFF,this.emit("remote-publish-changed",this.isRemotePublished)}onTrackMuted(){this.isNeedPlay&&super.onTrackMuted()}onTrackUnmuted(){this.isNeedPlay&&super.onTrackUnmuted()}onTrackEnded(){this.isNeedPlay&&super.onTrackEnded()}};de(M_,"STATE_SUBSCRIBE","subscribe"),Cc([DEA(5,1)],M_.prototype,"waitHasMediaTrack"),Cc([Du(Xn.INIT,M_.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),ps.emit(mn.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),f$(521716,!1)],M_.prototype,"subscribe"),Cc([Du(M_.STATE_SUBSCRIBE,Xn.INIT,{sync:!0,success(){this.log.info("unsubscribed"),ps.emit(mn.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],M_.prototype,"unsubscribe");var a3=new Map;function Ec(t,i){const r=nB(Rn({},i),{timestamp:jW()});a3.has(t)?a3.get(t).push(r):a3.set(t,[r])}ps.on(mn.JOIN_SUCCESS,({room:t})=>{Ec(t.userId,{eventId:32788})}),ps.on(mn.LEAVE_START,({room:t})=>{Ec(t.userId,{eventId:32789})}),ps.on(mn.LOCAL_TRACK_PUBLISHED,({track:t})=>{if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),Ec(t.room.userId,{eventId:i})}}),ps.on(mn.LOCAL_TRACK_UNPUBLISHED,({track:t})=>{if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),Ec(t.room.userId,{eventId:i})}}),ps.on(mn.TRACK_MUTED,({track:t})=>{t.room&&(t.kind===$t.AUDIO?Ec(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):Ec(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),ps.on(mn.TRACK_UNMUTED,({track:t})=>{t.room&&(t.kind===$t.AUDIO?Ec(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):Ec(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),ps.on(mn.REMOTE_TRACK_SUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&Ec(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&Ec(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&Ec(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),ps.on(mn.REMOTE_TRACK_UNSUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&Ec(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&Ec(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&Ec(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),ps.on(mn.SWITCH_DEVICE_SUCCESS,({track:t})=>{t.room&&Ec(t.room.userId,{eventId:t.kind===$t.VIDEO?32780:32781})}),ps.on(mn.LOCAL_TRACK_REPLACED,({track:t})=>{t.room&&Ec(t.room.userId,{eventId:t.kind===$t.VIDEO?32782:32783})}),ps.on(mn.SIGNAL_CONNECTION_STATE_CHANGED,({room:t,prevState:i,state:r})=>{let l;switch(r){case"CONNECTED":l=i==="RECONNECTING"?32795:32791;break;case"DISCONNECTED":l=i==="RECONNECTING"?32796:32790;break;case"RECONNECTING":l=32794}l&&Ec(t.userId,{eventId:l})}),ps.on(mn.PEER_CONNECTION_STATE_CHANGED,({room:t,prevState:i,state:r,remoteUserId:l})=>{const I=!!l;let h;switch(r){case"CONNECTED":h=i==="RECONNECTING"?I?32801:32798:I?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(h=I?32802:32799);break;case"RECONNECTING":h=I?32800:32797}h&&Ec(t.userId,{eventId:h,remoteUserId:l})}),ps.on(mn.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:t,userId:i,remoteUserId:r,codec:l,isHWCodec:I,prevImplementation:h,streamType:f})=>{let w=I?1:0;h||(w=I?3:2);const _={H264:0,H265:1,VP8:2}[l.toUpperCase()],G={eventId:4004,param1:w,param2:_,streamType:f||2};r&&(G.remoteUserId=r,G.eventId=4005),Ec(i,G),Ir.addEnum({key:r?514701:513701,value:w}),Ir.addEnum({key:r?514700:513700,value:_})}),ps.on(mn.LOCAL_TRACK_RECAPTURE,({track:t,error:i})=>{if(t.userId){const r={eventId:2003,param1:0};t.kind===$t.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),Ec(t.userId,r)}});dT(PU());dT(PU());var g3=0,G$=class b${constructor(i){this.core=i,de(this,"seq"),de(this,"log"),de(this,"localMixVideoTrack",null),de(this,"systemAudioTrackList",{}),de(this,"_mixVideoConfig"),de(this,"onScreenShareStop"),de(this,"eventListeners",new Map),g3+=1,this.seq=g3,this.log=i.log.createChild({id:`${this.getAlias()}${g3}`}),this.log.info("created")}getName(){return b$.Name}getAlias(){return"vmix"}getValidateRule(i){switch(i){case"start":return ScA(this.core);case"update":return McA(this.core);case"stop":return vcA(this.core)}}getGroup(){return"vmix"}async start(i){this.localMixVideoTrack||(this.localMixVideoTrack=new this.core.LocalMixVideoTrack(this.core.room.videoManager)),this._mixVideoConfig={canvasInfo:{width:1920,height:1080}},i=this.core.utils.deepCloneBasic(i);const{view:r,onScreenShareStop:l}=i,I=await this.parseMixOptions(i);return l&&(this.onScreenShareStop=l,this._mixVideoConfig.onScreenShareStop=l),this._updatePreview({view:r,track:this.localMixVideoTrack}),this.core.utils.isUndefined(r)||(this._mixVideoConfig.view=r),await this.localMixVideoTrack.startMix(),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:I}}async update(i){const{RtcError:r,ErrorCode:l}=this.core.errorModule;if(!this.localMixVideoTrack)throw new r({code:l.INVALID_OPERATION,message:"mixTrack doesn't initialize!"});i=this.core.utils.deepCloneBasic(i);const{view:I}=i,h=await this.parseMixOptions(i);return await this._updatePreview({view:I,track:this.localMixVideoTrack,prevConfig:this._mixVideoConfig}),this.core.utils.isUndefined(I)||(this._mixVideoConfig.view=I),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:h}}stop(){var i;this.eventListeners.forEach((r,l)=>{this.removeEventListeners(l)}),this.eventListeners.clear(),(i=this.localMixVideoTrack)==null||i.close(),this.localMixVideoTrack=null,Object.values(this.systemAudioTrackList).forEach(r=>r.stop()),this.systemAudioTrackList={},delete this.onScreenShareStop,delete this._mixVideoConfig}async parseMixOptions(i){const{RtcError:r,ErrorCode:l}=this.core.errorModule;if(!this.localMixVideoTrack||!this._mixVideoConfig)return{successOptions:{},failedDetails:[]};const I=[],h=Rn({},i),{canvasInfo:f,camera:w,screen:_,text:G,image:U,video:j}=i;f&&this.parseCanvasOptions(f);let lA=0,sA=0;const mA=[{key:"camera",options:w,parser:this.parseCameraOptions.bind(this)},{key:"screen",options:_,parser:this.parseScreenOptions.bind(this)},{key:"text",options:G,parser:this.parseTextOptions.bind(this)},{key:"image",options:U,parser:this.parseImageOptions.bind(this)},{key:"video",options:j,parser:this.parseVideoOptions.bind(this)}];for(const{key:IA,options:cA,parser:TA}of mA)if(cA){lA++;const WA=await TA(this.localMixVideoTrack,cA,this._mixVideoConfig[IA]||[]);this._mixVideoConfig[IA]=WA.finalOptions,h[IA]=WA.finalOptions,WA.errors.length>0&&(I.push(...WA.errors),WA.errors.length===cA.length&&sA++)}if(sA>0&&sA===lA)throw new r({code:l.INVALID_PARAMETER,message:"all sources mix failed",data:{failedDetails:I}});return{successOptions:h,failedDetails:I}}parseCanvasOptions(i){if(!this.localMixVideoTrack||!this._mixVideoConfig)return;const{canvasColor:r,width:l,height:I,frameRate:h}=i;r&&this.localMixVideoTrack.setMixBackground(r),h&&this.localMixVideoTrack.setFps(h),this.localMixVideoTrack.resizeMixCanvas(l,I),this._mixVideoConfig.canvasInfo=i}prepareSourceOptions(i,r){const l=new Set(i.map(I=>I.id));return{removeIdList:r.filter(I=>!l.has(I.id)).map(I=>I.id),preOptionsMap:new Map(r.map(I=>[I.id,I]))}}recordSourceError(i,r,l,I,h){h.push({id:i,error:r}),l.has(i)&&I.push(l.get(i))}async parseCameraOptions(i,r,l=[]){const{removeIdList:I,preOptionsMap:h}=this.prepareSourceOptions(r,l);this.log.debug("videomixer removeIdList",r,I,h);for(const _ of I)i.removeCameraSource(_),this.removeEventListeners(_);const f=[],w=[];for(const _ of r)try{await this.processSingleCameraSource(i,_),f.push(_)}catch(G){this.recordSourceError(_.id,G,h,f,w)}return{finalOptions:f,errors:w}}async processSingleCameraSource(i,r){const{id:l}=r;this.resolveCameraInternalTrack(i,r),i.inputLocalVideoTracks.has(l)?await this.updateExistingCameraSource(i,r):await this.addNewCameraSource(i,r)}async updateExistingCameraSource(i,r){var l,I;const{id:h,layout:f,profile:w}=r,_=(l=i.inputLocalVideoTracks.get(h))==null?void 0:l.mediaTrack;await this.updateCameraProfile(r);const G=(I=i.inputLocalVideoTracks.get(h))==null?void 0:I.mediaTrack,U=this.resolveVideoProfile(w);G!==_?i.updateCameraSource(h,f,G,U):i.updateCameraSource(h,f,null,U)}resolveCameraInternalTrack(i,r){var l;const{id:I,layout:h,profile:f,useInternalTrack:w}=r;if(w){if(i.inputLocalVideoTracks.get(I))return r;this.log.debug("resolve camera internal track",r,r.id,r.videoTrack),(l=this.core.trtc.localVideoTrack)!=null&&l.sourceTrack?(this.log.debug("resolve camera internal track outMediaTrack:",this.core.trtc.localVideoTrack.outMediaTrack,"sourceTrack:",this.core.trtc.localVideoTrack.sourceTrack),r.videoTrack=this.core.trtc.localVideoTrack.outMediaTrack,r.profile=this.core.trtc.localVideoTrack.profile):r.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(I);const _=U=>{var j,lA;const sA=i.inputLocalVideoTracks.get(I);this.log.debug(`camera internal track preprocessed event from ${(j=U.room)==null?void 0:j.userId} to ${this.core.room.userId}, is same instance:${U.room===this.core.room} ,new track:`,U.mediaTrack,sA?.mediaTrack,i.outMediaTrack),((lA=U.mediaTrack)==null?void 0:lA.kind)!==$t.AUDIO&&sA?.mediaTrack!==U.mediaTrack&&i.outMediaTrack!==U.mediaTrack&&U.room===this.core.room?sA&&U.mediaTrack&&i.updateCameraSource(I,h,U.mediaTrack):this.log.debug("camera internal track preprocessed event return")},G=U=>{var j,lA,sA,mA,IA,cA,TA,WA;const ue=i.inputLocalVideoTracks.get(I);this.log.debug(`camera internal track stopped ${((j=U.track)==null?void 0:j.mediaTrack)===ue?.mediaTrack||((lA=U.track)==null?void 0:lA.outMediaTrack)===ue?.mediaTrack||((sA=U.track)==null?void 0:sA.outMediaTrack)===i.outMediaTrack}`,(mA=U.track)==null?void 0:mA.mediaTrack,(IA=U.track)==null?void 0:IA.outMediaTrack,ue?.mediaTrack,i.outMediaTrack),!ue||((cA=U.track)==null?void 0:cA.mediaTrack)!==ue?.mediaTrack&&((TA=U.track)==null?void 0:TA.outMediaTrack)!==ue?.mediaTrack&&((WA=U.track)==null?void 0:WA.outMediaTrack)!==i.outMediaTrack||i.updateCameraSource(I,h,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("118",_),this.core.innerEmitter.on("117",G),this.eventListeners.has(I)||this.eventListeners.set(I,{}),this.eventListeners.get(I).captureSuccess=()=>{this.core.innerEmitter.off("118",_)},this.eventListeners.get(I).trackStop=()=>{this.core.innerEmitter.off("117",G)}}return r}async addNewCameraSource(i,r){const{id:l,layout:I,useInternalTrack:h}=r,f=await this.captureCamera(r);try{i.addCameraSource(l,f,I)}catch(w){throw f.close(),w}}resolveVideoProfile(i){if(!this.core.utils.isUndefined(i))return this.core.utils.isString(i)?this.core.constants.videoProfileMap[i]:i}async parseScreenOptions(i,r,l=[]){const{removeIdList:I,preOptionsMap:h}=this.prepareSourceOptions(r,l);for(const _ of I)i.removeScreenSource(_),this.removeSystemAudioTrack(_),this.removeEventListeners(_);const f=[],w=[];for(const _ of r)try{await this.processSingleScreenSource(i,_,h),f.push(_)}catch(G){this.recordSourceError(_.id,G,h,f,w)}return{finalOptions:f,errors:w}}async processSingleScreenSource(i,r,l){const{id:I,layout:h,useInternalTrack:f}=r;this.resolveScreenInternalTrack(i,r);const w=l.get(I),_=i.inputLocalScreenTracks.has(I),G=!w?.systemAudio&&r.systemAudio;_&&!G?this.updateExistingScreenSource(i,I,h,w,r):await this.addNewScreenSource(i,r,w)}updateExistingScreenSource(i,r,l,I,h){i.updateScreenSource(r,l),I?.systemAudio&&!h.systemAudio&&this.removeSystemAudioTrack(r)}resolveScreenInternalTrack(i,r){var l,I;const{id:h,layout:f,useInternalTrack:w}=r;if(w){if(i.inputLocalScreenTracks.get(h))return r;this.log.debug("resolve screen internal track",r,r.id,r.videoTrack),(l=this.core.trtc.localScreenTrack)!=null&&l.sourceTrack?(r.videoTrack=this.core.trtc.localScreenTrack.sourceTrack,r.profile=this.core.trtc.localScreenTrack.profile,(I=this.core.trtc.localScreenAudioTrack)!=null&&I.mediaTrack&&(r.audioTrack=this.core.trtc.localScreenAudioTrack.mediaTrack),delete r.captureElement,delete r.preferDisplaySurface,delete r.systemAudio):r.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(h);const _=U=>{var j,lA,sA,mA,IA,cA,TA;const WA=i.inputLocalScreenTracks.get(h);this.log.debug(`screen internal track capture success event from ${(j=U.room)==null?void 0:j.userId} to ${this.core.room.userId}, is same instance:${U.room===this.core.room}, isScreen:${(lA=U.track)==null?void 0:lA.isScreen} kind:${(sA=U.track)==null?void 0:sA.kind}`,WA,U.track.sourceTrack),(mA=U.track)!=null&&mA.isScreen&&((IA=U.track)==null?void 0:IA.kind)!==$t.AUDIO&&WA&&(this.log.debug("screen internal track capture success event ",(cA=U.track)==null?void 0:cA.sourceTrack),(TA=U.track)!=null&&TA.sourceTrack&&i.updateScreenSource(h,f,U.track.sourceTrack))},G=U=>{var j,lA;const sA=i.inputLocalScreenTracks.get(h);this.log.debug(`screen internal track stopped, is same track:${((j=U.track)==null?void 0:j.sourceTrack)===sA?.mediaTrack}, isScreen:${U.track.isScreen}`),U.track.isScreen&&((lA=U.track)==null?void 0:lA.sourceTrack)===sA?.mediaTrack&&i.updateScreenSource(h,f,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("102",_),this.core.innerEmitter.on("117",G),this.eventListeners.has(h)||this.eventListeners.set(h,{}),this.eventListeners.get(h).captureSuccess=()=>{this.core.innerEmitter.off("102",_)},this.eventListeners.get(h).trackStop=()=>{this.core.innerEmitter.off("117",G)}}return r}async addNewScreenSource(i,r,l){const{id:I,layout:h}=r,f=await this.captureScreen(r);!l?.systemAudio&&r.systemAudio&&i.inputLocalScreenTracks.has(I)&&i.removeScreenSource(I);try{i.addScreenSource(I,f,h)}catch(w){throw f.close(),w}}async parseTextOptions(i,r,l=[]){const{removeIdList:I,preOptionsMap:h}=this.prepareSourceOptions(r,l);for(const _ of I)i.removeTextSource(_);const f=[],w=[];for(const _ of r)try{h.has(_.id)?i.updateTextSource(_):i.addTextSource(_),f.push(_)}catch(G){this.recordSourceError(_.id,G,h,f,w)}return{finalOptions:f,errors:w}}async parseImageOptions(i,r,l=[]){const{removeIdList:I,preOptionsMap:h}=this.prepareSourceOptions(r,l);for(const _ of I)i.removeImageSource(_);const f=[],w=[];for(const _ of r)try{await this.processSingleImageSource(i,_,h),f.push(_)}catch(G){this.recordSourceError(_.id,G,h,f,w)}return{finalOptions:f,errors:w}}async processSingleImageSource(i,r,l){const{id:I,url:h,layout:f}=r,w=l.get(I);if(w){let _;w.url!==h&&(_=await this.core.utils.loadImage(h)),i.updateImageSource(I,f,_)}else{const _=await this.core.utils.loadImage(h);i.addImageSource(I,_,f)}}async parseVideoOptions(i,r,l=[]){const{removeIdList:I,preOptionsMap:h}=this.prepareSourceOptions(r,l);for(const _ of I)i.removeVideoSource(_);const f=[],w=[];for(const _ of r)try{await this.processSingleVideoSource(i,_,h),f.push(_)}catch(G){this.recordSourceError(_.id,G,h,f,w)}return{finalOptions:f,errors:w}}async processSingleVideoSource(i,r,l){const{id:I,url:h,layout:f}=r,w=l.get(I);if(w){let _;w.url!==h&&(_=await this.core.utils.loadVideo(h)),i.updateVideoSource(I,f,_)}else{const _=await this.core.utils.loadVideo(h);i.addVideoSource(I,_,f)}}createPlaceholderVideoTrack(){const i=document.createElement("canvas");i.width=1,i.height=1;const r=i.getContext("2d");if(!r)return i.captureStream(30).getVideoTracks()[0];let l=null;const I=1e3/30,h=i.captureStream(30).getVideoTracks()[0],f=()=>{r.fillStyle="rgba(255, 255, 255, 0)",r.fillRect(0,0,i.width,i.height),h.readyState==="live"&&(l=setTimeout(f,I))};f();const w=h.stop.bind(h);return h.stop=()=>{l&&(clearTimeout(l),l=null),w()},h}removeEventListeners(i){const r=this.eventListeners.get(i);r&&(r.captureSuccess&&r.captureSuccess(),r.trackStop&&r.trackStop(),this.eventListeners.delete(i))}async captureCamera(i){const{id:r,cameraId:l,videoTrack:I,profile:h}=i,f=new this.core.LocalVideoTrack;f.log.id+=`-${r}`;const w={};if(l?w.deviceId=l:this.core.utils.isUndefined(I)||(w.customSource=I),!this.core.utils.isUndefined(h)){const _=this.resolveVideoProfile(h);_&&f.setProfile(_)}return await f.capture(w),f}async updateCameraProfile(i){var r;const{id:l,cameraId:I,videoTrack:h,profile:f}=i,w=(r=this.localMixVideoTrack)==null?void 0:r.inputLocalVideoTracks.get(l);if(w&&(I?await w.switchDevice(I):this.core.utils.isUndefined(h)||await w.setInputMediaStreamTrack(h),!this.core.utils.isUndefined(f))){const _=this.resolveVideoProfile(f);_&&w.setProfile(_),I&&w.isNeedToSwitchDevice(I)||await w.applyProfile()}}async captureScreen(i){const{id:r,profile:l,captureElement:I,preferDisplaySurface:h,systemAudio:f,videoTrack:w,audioTrack:_}=i,G=new this.core.LocalScreenTrack;G.log.id+=`-${r}`;const U={captureElement:I,preferDisplaySurface:h,systemAudio:f,videoTrack:w,audioTrack:_};if(!this.core.utils.isUndefined(l))if(this.core.utils.isString(l)){const lA=this.core.constants.screenProfileMap[l];lA&&G.setProfile(lA)}else G.setProfile(l);const j=await G.capture(U);return f&&j.getAudioTracks().length>0?(this.systemAudioTrackList[r]=j.getAudioTracks()[0],this.log.info(`${r} system audio track captured`)):this.removeSystemAudioTrack(r),G.mediaTrack.addEventListener(this.core.constants.NAME.ENDED,()=>{this.handleScreenShareEnded(r)}),G}handleScreenShareEnded(i){var r,l,I;(r=this.localMixVideoTrack)==null||r.removeScreenSource(i),(l=this._mixVideoConfig)!=null&&l.screen&&(this._mixVideoConfig.screen=this._mixVideoConfig.screen.filter(h=>h.id!==i)),(I=this.onScreenShareStop)==null||I.call(this,i)}async _updatePreview({view:i,track:r,prevConfig:l}){if(this.core.utils.isUndefined(i)&&l?.view){const I=this.core.utils.getViewListFromView(l.view);return void(I.length>0&&await r.play(I))}if(!this.core.utils.isUndefined(i)){const I=this.core.utils.getViewListFromView(i);I.length>0?await r.play(I):r.stop()}}removeSystemAudioTrack(i){const r=this.systemAudioTrackList[i];r&&(r.stop(),this.log.info(`${i} system audio track stop`),delete this.systemAudioTrackList[i])}};de(G$,"Name","VideoMixer");var k$=G$,SEA=k$;const MEA=Object.freeze(Object.defineProperty({__proto__:null,VideoMixer:k$,default:SEA},Symbol.toStringTag,{value:"Module"})),vEA=kU(MEA);var REA=TL.exports,jZ;function wEA(){return jZ||(jZ=1,function(t,i){(function(r,l){l(i,krA(),raA,ZgA,ncA,EcA,vEA)})(REA,function(r,l,I,h,f,w,_){function G(q){return q&&typeof q=="object"&&"default"in q?q:{default:q}}var U=G(l),j=G(_),lA=function(q,L){return lA=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(oA,b){oA.__proto__=b}||function(oA,b){for(var x in b)Object.prototype.hasOwnProperty.call(b,x)&&(oA[x]=b[x])},lA(q,L)},sA=function(){return sA=Object.assign||function(q){for(var L,oA=1,b=arguments.length;oA=0;wA--)(x=q[wA])&&(uA=(tA<3?x(uA):tA>3?x(L,oA,uA):x(L,oA))||uA);return tA>3&&uA&&Object.defineProperty(L,oA,uA),uA}function IA(q,L,oA,b){return new(oA||(oA=Promise))(function(x,tA){function uA(pe){try{XA(b.next(pe))}catch(p){tA(p)}}function wA(pe){try{XA(b.throw(pe))}catch(p){tA(p)}}function XA(pe){var p;pe.done?x(pe.value):(p=pe.value,p instanceof oA?p:new oA(function(B){B(p)})).then(uA,wA)}XA((b=b.apply(q,[])).next())})}function cA(q,L){var oA,b,x,tA,uA={label:0,sent:function(){if(1&x[0])throw x[1];return x[1]},trys:[],ops:[]};return tA={next:wA(0),throw:wA(1),return:wA(2)},typeof Symbol=="function"&&(tA[Symbol.iterator]=function(){return this}),tA;function wA(XA){return function(pe){return function(p){if(oA)throw new TypeError("Generator is already executing.");for(;tA&&(tA=0,p[0]&&(uA=0)),uA;)try{if(oA=1,b&&(x=2&p[0]?b.return:p[0]?b.throw||((x=b.return)&&x.call(b),0):b.next)&&!(x=x.call(b,p[1])).done)return x;switch(b=0,x&&(p=[2&p[0],x.value]),p[0]){case 0:case 1:x=p;break;case 4:return uA.label++,{value:p[1],done:!1};case 5:uA.label++,b=p[1],p=[0];continue;case 7:p=uA.ops.pop(),uA.trys.pop();continue;default:if(x=uA.trys,!((x=x.length>0&&x[x.length-1])||p[0]!==6&&p[0]!==2)){uA=0;continue}if(p[0]===3&&(!x||p[1]>x[0]&&p[1]=q.length&&(q=void 0),{value:q&&q[b++],done:!q}}};throw new TypeError(L?"Object is not iterable.":"Symbol.iterator is not defined.")}function WA(q,L,oA){if(oA||arguments.length===2)for(var b,x=0,tA=L.length;x0&&qt[0]<4?1:+(qt[0]+qt[1])),!yg&&mc&&(!(qt=mc.match(/Edge\/(\d+)/))||qt[1]>=74)&&(qt=mc.match(/Chrome\/(\d+)/))&&(yg=+qt[1]);var Ea=yg,yn=Gn.String,ba=!!Object.getOwnPropertySymbols&&!Js(function(){var q=Symbol("symbol detection");return!yn(q)||!(Object(q)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),Sa=ba&&!Symbol.sham&&typeof Symbol.iterator=="symbol",$=Object,K=Sa?function(q){return typeof q=="symbol"}:function(q){var L=Hs("Symbol");return _o(L)&&Sg(L.prototype,$(q))},vA=String,qA=TypeError,Ae=function(q){if(_o(q))return q;throw qA(function(L){try{return vA(L)}catch{return"Object"}}(q)+" is not a function")},me=function(q,L){var oA=q[L];return $i(oA)?void 0:Ae(oA)},Pe=TypeError,Fe=Object.defineProperty,rt=function(q,L){try{Fe(Gn,q,{value:L,configurable:!0,writable:!0})}catch{Gn[q]=L}return L},Ct="__core-js_shared__",Rt=Gn[Ct]||rt(Ct,{}),Yt=xe(function(q){(q.exports=function(L,oA){return Rt[L]||(Rt[L]=oA!==void 0?oA:{})})("versions",[]).push({version:"3.32.1",mode:"global",copyright:"© 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.32.1/LICENSE",source:"https://github.com/zloirock/core-js"})}),Ii=Object,ct=function(q){return Ii(ng(q))},xt=as({}.hasOwnProperty),Ji=Object.hasOwn||function(q,L){return xt(ct(q),L)},Ki=0,qs=Math.random(),Mi=as(1 .toString),zo=function(q){return"Symbol("+(q===void 0?"":q)+")_"+Mi(++Ki+qs,36)},Mg=Gn.Symbol,sr=Yt("wks"),yr=Sa?Mg.for||Mg:Mg&&Mg.withoutSetter||zo,xn=function(q){return Ji(sr,q)||(sr[q]=ba&&Ji(Mg,q)?Mg[q]:yr("Symbol."+q)),sr[q]},Ml=TypeError,Ks=xn("toPrimitive"),aI=function(q,L){if(!Hn(q)||K(q))return q;var oA,b=me(q,Ks);if(b){if(oA=mo(b,q,L),!Hn(oA)||K(oA))return oA;throw Ml("Can't convert object to primitive value")}return function(x,tA){var uA,wA;if(_o(uA=x.toString)&&!Hn(wA=mo(uA,x))||_o(uA=x.valueOf)&&!Hn(wA=mo(uA,x)))return wA;throw Pe("Can't convert object to primitive value")}(q)},Wg=function(q){var L=aI(q,"string");return K(L)?L:L+""},fc=Gn.document,wu=Hn(fc)&&Hn(fc.createElement),Ma=function(q){return wu?fc.createElement(q):{}},vl=!pr&&!Js(function(){return Object.defineProperty(Ma("div"),"a",{get:function(){return 7}}).a!==7}),ye=Object.getOwnPropertyDescriptor,fe={f:pr?ye:function(q,L){if(q=Dg(q),L=Wg(L),vl)try{return ye(q,L)}catch{}if(Ji(q,L))return fr(!mo(cn.f,q,L),q[L])}},vg=pr&&Js(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),rg=String,Rg=TypeError,Dn=function(q){if(Hn(q))return q;throw Rg(rg(q)+" is not an object")},Dr=TypeError,ui=Object.defineProperty,no=Object.getOwnPropertyDescriptor,qc="enumerable",zg="configurable",wg="writable",Yr={f:pr?vg?function(q,L,oA){if(Dn(q),L=Wg(L),Dn(oA),typeof q=="function"&&L==="prototype"&&"value"in oA&&wg in oA&&!oA[wg]){var b=no(q,L);b&&b[wg]&&(q[L]=oA.value,oA={configurable:zg in oA?oA[zg]:b[zg],enumerable:qc in oA?oA[qc]:b[qc],writable:!1})}return ui(q,L,oA)}:ui:function(q,L,oA){if(Dn(q),L=Wg(L),Dn(oA),vl)try{return ui(q,L,oA)}catch{}if("get"in oA||"set"in oA)throw Dr("Accessors not supported");return"value"in oA&&(q[L]=oA.value),q}},yc=pr?function(q,L,oA){return Yr.f(q,L,fr(1,oA))}:function(q,L,oA){return q[L]=oA,q},Kc=Function.prototype,ag=pr&&Object.getOwnPropertyDescriptor,_u=Ji(Kc,"name"),SE={CONFIGURABLE:_u&&(!pr||pr&&ag(Kc,"name").configurable)},_g=as(Function.toString);_o(Rt.inspectSource)||(Rt.inspectSource=function(q){return _g(q)});var ka,Dc,ME,La=Rt.inspectSource,sa=Gn.WeakMap,Tg=_o(sa)&&/native code/.test(String(sa)),gI=Yt("keys"),hs=function(q){return gI[q]||(gI[q]=zo(q))},Lo={},da="Object already initialized",nr=Gn.TypeError,Vt=Gn.WeakMap;if(Tg||Rt.state){var Kt=Rt.state||(Rt.state=new Vt);Kt.get=Kt.get,Kt.has=Kt.has,Kt.set=Kt.set,ka=function(q,L){if(Kt.has(q))throw nr(da);return L.facade=q,Kt.set(q,L),L},Dc=function(q){return Kt.get(q)||{}},ME=function(q){return Kt.has(q)}}else{var Ng=hs("state");Lo[Ng]=!0,ka=function(q,L){if(Ji(q,Ng))throw nr(da);return L.facade=q,yc(q,Ng,L),L},Dc=function(q){return Ji(q,Ng)?q[Ng]:{}},ME=function(q){return Ji(q,Ng)}}var cI={get:Dc,enforce:function(q){return ME(q)?Dc(q):ka(q,{})}},rr=xe(function(q){var L=SE.CONFIGURABLE,oA=cI.enforce,b=cI.get,x=String,tA=Object.defineProperty,uA=as("".slice),wA=as("".replace),XA=as([].join),pe=pr&&!Js(function(){return tA(function(){},"length",{value:8}).length!==8}),p=String(String).split("String"),B=q.exports=function(v,N,O){uA(x(N),0,7)==="Symbol("&&(N="["+wA(x(N),/^Symbol\(([^)]*)\)/,"$1")+"]"),O&&O.getter&&(N="get "+N),O&&O.setter&&(N="set "+N),(!Ji(v,"name")||L&&v.name!==N)&&(pr?tA(v,"name",{value:N,configurable:!0}):v.name=N),pe&&O&&Ji(O,"arity")&&v.length!==O.arity&&tA(v,"length",{value:O.arity});try{O&&Ji(O,"constructor")&&O.constructor?pr&&tA(v,"prototype",{writable:!1}):v.prototype&&(v.prototype=void 0)}catch{}var z=oA(v);return Ji(z,"source")||(z.source=XA(p,typeof N=="string"?N:"")),v};Function.prototype.toString=B(function(){return _o(this)&&b(this).source||La(this)},"toString")}),qI=function(q,L,oA,b){b||(b={});var x=b.enumerable,tA=b.name!==void 0?b.name:L;if(_o(oA)&&rr(oA,tA,b),b.global)x?q[L]=oA:rt(L,oA);else{try{b.unsafe?q[L]&&(x=!0):delete q[L]}catch{}x?q[L]=oA:Yr.f(q,L,{value:oA,enumerable:!1,configurable:!b.nonConfigurable,writable:!b.nonWritable})}return q},za=Math.ceil,na=Math.floor,un=Math.trunc||function(q){var L=+q;return(L>0?na:za)(L)},Sn=function(q){var L=+q;return L!=L||L===0?0:un(L)},Tu=Math.max,Gg=Math.min,Ua=Math.min,jc=function(q){return q>0?Ua(Sn(q),9007199254740991):0},KI=function(q){return jc(q.length)},vE=function(q){return function(L,oA,b){var x,tA=Dg(L),uA=KI(tA),wA=function(XA,pe){var p=Sn(XA);return p<0?Tu(p+pe,0):Gg(p,pe)}(b,uA);if(q&&oA!=oA){for(;uA>wA;)if((x=tA[wA++])!=x)return!0}else for(;uA>wA;wA++)if((q||wA in tA)&&tA[wA]===oA)return q||wA||0;return!q&&-1}},lI={indexOf:vE(!1)}.indexOf,Nu=as([].push),Rl=function(q,L){var oA,b=Dg(q),x=0,tA=[];for(oA in b)!Ji(Lo,oA)&&Ji(b,oA)&&Nu(tA,oA);for(;L.length>x;)Ji(b,oA=L[x++])&&(~lI(tA,oA)||Nu(tA,oA));return tA},Sc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gu=Sc.concat("length","prototype"),bu={f:Object.getOwnPropertyNames||function(q){return Rl(q,Gu)}},wl={f:Object.getOwnPropertySymbols},rs=as([].concat),gs=Hs("Reflect","ownKeys")||function(q){var L=bu.f(Dn(q)),oA=wl.f;return oA?rs(L,oA(q)):L},ud=function(q,L,oA){for(var b=gs(L),x=Yr.f,tA=fe.f,uA=0;uAuA;)Yr.f(q,oA=x[uA++],b[oA]);return q},jI={f:ku},Zc=Hs("document","documentElement"),Xc="prototype",WI="script",EI=hs("IE_PROTO"),$c=function(){},Al=function(q){return"<"+WI+">"+q+""},va=function(q){q.write(Al("")),q.close();var L=q.parentWindow.Object;return q=null,L},bg=function(){try{Ca=new ActiveXObject("htmlfile")}catch{}var q,L,oA;bg=typeof document<"u"?document.domain&&Ca?va(Ca):(L=Ma("iframe"),oA="java"+WI+":",L.style.display="none",Zc.appendChild(L),L.src=String(oA),(q=L.contentWindow.document).open(),q.write(Al("document.F=Object")),q.close(),q.F):va(Ca);for(var b=Sc.length;b--;)delete bg[Xc][Sc[b]];return bg()};Lo[EI]=!0;var ys,Kn,vc=Object.create||function(q,L){var oA;return q!==null?($c[Xc]=Dn(q),oA=new $c,$c[Xc]=null,oA[EI]=q):oA=bg(),L===void 0?oA:jI.f(oA,L)},zI=Gn.RegExp,ZI=Js(function(){var q=zI(".","s");return!(q.dotAll&&q.exec(` -`)&&q.flags==="s")}),_E=Gn.RegExp,rh=Js(function(){var q=_E("(?b)","g");return q.exec("b").groups.a!=="b"||"b".replace(q,"$c")!=="bc"}),IC=cI.get,ah=Yt("native-string-replace",String.prototype.replace),el=RegExp.prototype.exec,kg=el,ro=as("".charAt),uC=as("".indexOf),TE=as("".replace),NE=as("".slice),hd=(Kn=/b*/g,mo(el,ys=/a/,"a"),mo(el,Kn,"a"),ys.lastIndex!==0||Kn.lastIndex!==0),GE=Cd.BROKEN_CARET,tl=/()??/.exec("")[1]!==void 0;(hd||tl||GE||ZI||rh)&&(kg=function(q){var L,oA,b,x,tA,uA,wA,XA=this,pe=IC(XA),p=Xg(q),B=pe.raw;if(B)return B.lastIndex=XA.lastIndex,L=mo(kg,B,p),XA.lastIndex=B.lastIndex,L;var v=pe.groups,N=GE&&XA.sticky,O=mo(qn,XA),z=XA.source,X=0,rA=p;if(N&&(O=TE(O,"y",""),uC(O,"g")===-1&&(O+="g"),rA=NE(p,XA.lastIndex),XA.lastIndex>0&&(!XA.multiline||XA.multiline&&ro(p,XA.lastIndex-1)!==` -`)&&(z="(?: "+z+")",rA=" "+rA,X++),oA=new RegExp("^(?:"+z+")",O)),tl&&(oA=new RegExp("^"+z+"$(?!\\s)",O)),hd&&(b=XA.lastIndex),x=mo(el,N?oA:XA,rA),N?x?(x.input=NE(x.input,X),x[0]=NE(x[0],X),x.index=XA.lastIndex,XA.lastIndex+=x[0].length):XA.lastIndex=0:hd&&x&&(XA.lastIndex=XA.global?x.index+x[0].length:b),tl&&x&&x.length>1&&mo(ah,x[0],oA,function(){for(tA=1;tA=wA?q?"":void 0:(b=hI(tA,uA))<55296||b>56319||uA+1===wA||(x=hI(tA,uA+1))<56320||x>57343?q?Qd(tA,uA):b:q?Oa(tA,uA,uA+2):x-56320+(b-55296<<10)+65536}},Pa={charAt:CC(!0)}.charAt,ur=function(q,L,oA){return L+(oA?Pa(q,L).length:1)},pd=TypeError,Ou=function(q,L){var oA=q.exec;if(_o(oA)){var b=mo(oA,q,L);return b!==null&&Dn(b),b}if(Cs(q)==="RegExp")return mo(dI,q,L);throw pd("RegExp#exec called on incompatible receiver")};(function(q,L,oA,b){var x=xn(q),tA=!Js(function(){var pe={};return pe[x]=function(){return 7},""[q](pe)!==7}),uA=tA&&!Js(function(){var pe=!1,p=/a/;return q==="split"&&((p={}).constructor={},p.constructor[dC]=function(){return p},p.flags="",p[x]=/./[x]),p.exec=function(){return pe=!0,null},p[x](""),!pe});if(!tA||!uA||oA){var wA=_n(/./[x]),XA=L(x,""[q],function(pe,p,B,v,N){var O=_n(pe),z=p.exec;return z===dI||z===il.exec?tA&&!N?{done:!0,value:wA(p,B,v)}:{done:!0,value:O(B,p,v)}:{done:!1}});qI(String.prototype,q,XA[0]),qI(il,x,XA[1])}})("match",function(q,L,oA){return[function(b){var x=ng(this),tA=$i(b)?void 0:me(b,q);return tA?mo(tA,b,x):new RegExp(b)[q](Xg(x))},function(b){var x=Dn(this),tA=Xg(b),uA=oA(L,x,tA);if(uA.done)return uA.value;if(!x.global)return Ou(x,tA);var wA=x.unicode;x.lastIndex=0;for(var XA,pe=[],p=0;(XA=Ou(x,tA))!==null;){var B=Xg(XA[0]);pe[p]=B,B===""&&(x.lastIndex=ur(tA,jc(x.lastIndex),wA)),p++}return p===0?null:pe}]});var Er=Array.isArray||function(q){return Cs(q)==="Array"},wc=TypeError,ol=function(q){if(q>9007199254740991)throw wc("Maximum allowed index exceeded");return q},Lg=function(q,L,oA){var b=Wg(L);b in q?Yr.f(q,b,fr(0,oA)):q[b]=oA},Oo=function(){},$g=[],Za=Hs("Reflect","construct"),Nl=/^\s*(?:class|function)\b/,Aa=as(Nl.exec),gh=!Nl.exec(Oo),js=function(q){if(!_o(q))return!1;try{return Za(Oo,$g,q),!0}catch{return!1}},XI=function(q){if(!_o(q))return!1;switch(gg(q)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gh||!!Aa(Nl,La(q))}catch{return!0}};XI.sham=!0;var Us,_c=!Za||Js(function(){var q;return js(js.call)||!js(Object)||!js(function(){q=!0})||q})?XI:js,Ac=xn("species"),dr=Array,Vr=function(q,L){return new(function(oA){var b;return Er(oA)&&(b=oA.constructor,(_c(b)&&(b===dr||Er(b.prototype))||Hn(b)&&(b=b[Ac])===null)&&(b=void 0)),b===void 0?dr:b}(q))(0)},Xa=xn("species"),bE=xn("isConcatSpreadable"),hC=Ea>=51||!Js(function(){var q=[];return q[bE]=!1,q.concat()[0]!==q}),ch=function(q){if(!Hn(q))return!1;var L=q[bE];return L!==void 0?!!L:Er(q)};tn({target:"Array",proto:!0,arity:1,forced:!(hC&&(Us="concat",Ea>=51||!Js(function(){var q=[];return(q.constructor={})[Xa]=function(){return{foo:1}},q[Us](Boolean).foo!==1})))},{concat:function(q){var L,oA,b,x,tA,uA=ct(this),wA=Vr(uA),XA=0;for(L=-1,b=arguments.length;L=5||Math.abs(b)>=5?(document.removeEventListener("mousemove",this.onMouseMove5px,!1),document.removeEventListener("mouseup",this.onMouseUp5px,!1),document.addEventListener("mousemove",this.onMouseMove,!1),document.addEventListener("mouseup",this.onMouseUp,!1)):lg.debug("".concat(this.logPrefix,"on Movable mouse move less than 5px"))},q.prototype.onMouseUp5px=function(){document.removeEventListener("mousemove",this.onMouseMove5px,!1),document.removeEventListener("mouseup",this.onMouseUp5px,!1)},q.prototype.onMouseMove=function(L){if(this.movable&&this.container){var oA=L.screenX-this.moveStartOfLeft,b=L.screenY-this.moveStartOfTop,x=this.originLeft+oA,tA=this.originTop+b,uA=this.movable.offsetWidth,wA=this.movable.offsetHeight,XA=this.container.offsetWidth,pe=this.container.offsetHeight;this.options.canExceedContainer||(x<0?x=0:x>XA-uA&&(x=XA-uA),tA<0?tA=0:tA>pe-wA&&(tA=pe-wA)),!this.options.calcPositionOnly&&this.movable&&(this.movable.style.left="".concat(x,"px"),this.movable.style.top="".concat(tA,"px")),this.emit("move",x,tA)}else lg.debug("".concat(this.logPrefix,"onMouseMove error:No 'movable' and 'container'."))},q.prototype.onMouseUp=function(){document.removeEventListener("mousemove",this.onMouseMove,!1),document.removeEventListener("mouseup",this.onMouseUp,!1),this.originLeft=0,this.originTop=0,this.moveStartOfLeft=0,this.moveStartOfTop=0},q.prototype.on=function(L,oA){var b=this.callbacksMap.get(L);b?b.push(oA):this.callbacksMap.set(L,[oA])},q.prototype.off=function(L,oA){var b=this.callbacksMap.get(L);b&&(b=b.filter(function(x){return x!=oA}),this.callbacksMap.set(L,b))},q.prototype.emit=function(L){for(var oA=[],b=1;b ").concat(L)),this.enabled=L,this.movable&&(this.movable.style.cursor=L?"move":"default",lg.debug("".concat(this.logPrefix,"setEnabled: cursor updated to '").concat(L?"move":"default","'")))},q.prototype.isEnabled=function(){return this.enabled},q}();(function(q){q[q.Both=0]="Both",q[q.Corner=1]="Corner",q[q.Edge=2]="Edge"})(aa||(aa={}));var PE="trtc-resizable-top-left-anchor",Vu="trtc-resizable-top-anchor",Ju="trtc-resizable-top-right-anchor",yI="trtc-resizable-left-anchor",gl="trtc-resizable-right-anchor",Lr="trtc-resizable-bottom-left-anchor",Ur="trtc-resizable-bottom-anchor",Ig="trtc-resizable-bottom-right-anchor",ar={resizeAnchor:{position:"absolute",width:"".concat(8,"px"),height:"".concat(8,"px"),border:"1px solid #3D7EFD",backgroundColor:"#FFFFFF"},topLeftAnchor:{top:"-".concat(4,"px"),left:"-".concat(4,"px"),cursor:"nw-resize"},topAnchor:{top:"-".concat(4,"px"),left:"calc(50% - ".concat(4,"px)"),cursor:"n-resize"},topRightAnchor:{top:"-".concat(4,"px"),right:"-".concat(4,"px"),cursor:"ne-resize"},leftAnchor:{top:"calc(50% - ".concat(4,"px)"),left:"-".concat(4,"px"),cursor:"w-resize"},rightAnchor:{top:"calc(50% - ".concat(4,"px)"),right:"-".concat(4,"px"),cursor:"e-resize"},bottomLeftAnchor:{bottom:"-".concat(4,"px"),left:"-".concat(4,"px"),cursor:"sw-resize"},bottomAnchor:{bottom:"-".concat(4,"px"),left:"calc(50% - ".concat(4,"px)"),cursor:"s-resize"},bottomRightAnchor:{bottom:"-".concat(4,"px"),right:"-".concat(4,"px"),cursor:"se-resize"}};function _r(q,L){for(var oA in L)q.style[oA]=L[oA]}var ic=function(){function q(L,oA,b){b===void 0&&(b={keepRatio:!1,stopPropagation:!1,anchorMode:aa.Both,canExceedContainer:!1}),this.logPrefix="[Resizable]",this.container=null,this.options={keepRatio:!1,stopPropagation:!1,anchorMode:aa.Both,canExceedContainer:!1},this.callbacksMap=new Map,this.topLeftAnchor=null,this.topAnchor=null,this.topRightAnchor=null,this.leftAnchor=null,this.rightAnchor=null,this.bottomLeftAnchor=null,this.bottomAnchor=null,this.bottomRightAnchor=null,this.currentAnchor=null,this.resizeStartLeft=0,this.resizeStartTop=0,this.originLeft=0,this.originTop=0,this.originWidth=0,this.originHeight=0,this.resizeTarget=L,this.container=oA||document.body,this.options={keepRatio:!!b.keepRatio||!1,stopPropagation:!!b.stopPropagation||!1,anchorMode:b.anchorMode||aa.Both,canExceedContainer:!!b.canExceedContainer||!1},this.mousedown=this.mousedown.bind(this),this.mousemove=this.mousemove.bind(this),this.mouseup=this.mouseup.bind(this),this.currentAnchor=null,this.createResizeAnchor(),this.resizeTarget.classList.add("trtc-resizable"),this.resizeTarget.style.position="absolute",this.resizeTarget.style.border="1px solid #3D7EFD",this.resizeTarget.style.boxSizing="border-box",this.initResizeEvent()}return q.prototype.createResizeAnchor=function(){var L,oA,b,x,tA,uA,wA,XA,pe=document.createElement("div");pe.className="trtc-resizable-resize-anchor ".concat(PE),_r(pe,Object.assign({},ar.resizeAnchor,ar.topLeftAnchor)),this.topLeftAnchor=pe;var p=document.createElement("div");p.className="trtc-resizable-resize-anchor ".concat(Vu),_r(p,Object.assign({},ar.resizeAnchor,ar.topAnchor)),this.topAnchor=p;var B=document.createElement("div");B.className="trtc-resizable-resize-anchor ".concat(Ju),_r(B,Object.assign({},ar.resizeAnchor,ar.topRightAnchor)),this.topRightAnchor=B;var v=document.createElement("div");v.className="trtc-resizable-resize-anchor ".concat(yI),_r(v,Object.assign({},ar.resizeAnchor,ar.leftAnchor)),this.leftAnchor=v;var N=document.createElement("div");N.className="trtc-resizable-resize-anchor ".concat(gl),_r(N,Object.assign({},ar.resizeAnchor,ar.rightAnchor)),this.rightAnchor=N;var O=document.createElement("div");O.className="trtc-resizable-resize-anchor ".concat(Lr),_r(O,Object.assign({},ar.resizeAnchor,ar.bottomLeftAnchor)),this.bottomLeftAnchor=O;var z=document.createElement("div");z.className="trtc-resizable-resize-anchor ".concat(Ur),_r(z,Object.assign({},ar.resizeAnchor,ar.bottomAnchor)),this.bottomAnchor=z;var X=document.createElement("div");X.className="trtc-resizable-resize-anchor ".concat(Ig),_r(X,Object.assign({},ar.resizeAnchor,ar.bottomRightAnchor)),this.bottomRightAnchor=X,this.options.anchorMode!==aa.Both&&this.options.anchorMode!==aa.Edge||((L=this.resizeTarget)===null||L===void 0||L.appendChild(p),(oA=this.resizeTarget)===null||oA===void 0||oA.appendChild(v),(b=this.resizeTarget)===null||b===void 0||b.appendChild(N),(x=this.resizeTarget)===null||x===void 0||x.appendChild(z)),this.options.anchorMode!==aa.Both&&this.options.anchorMode!==aa.Corner||((tA=this.resizeTarget)===null||tA===void 0||tA.appendChild(pe),(uA=this.resizeTarget)===null||uA===void 0||uA.appendChild(B),(wA=this.resizeTarget)===null||wA===void 0||wA.appendChild(O),(XA=this.resizeTarget)===null||XA===void 0||XA.appendChild(X))},q.prototype.initResizeEvent=function(){var L,oA,b,x,tA,uA,wA,XA;(L=this.topLeftAnchor)===null||L===void 0||L.addEventListener("mousedown",this.mousedown,!1),(oA=this.topAnchor)===null||oA===void 0||oA.addEventListener("mousedown",this.mousedown,!1),(b=this.topRightAnchor)===null||b===void 0||b.addEventListener("mousedown",this.mousedown,!1),(x=this.leftAnchor)===null||x===void 0||x.addEventListener("mousedown",this.mousedown,!1),(tA=this.rightAnchor)===null||tA===void 0||tA.addEventListener("mousedown",this.mousedown,!1),(uA=this.bottomLeftAnchor)===null||uA===void 0||uA.addEventListener("mousedown",this.mousedown,!1),(wA=this.bottomAnchor)===null||wA===void 0||wA.addEventListener("mousedown",this.mousedown,!1),(XA=this.bottomRightAnchor)===null||XA===void 0||XA.addEventListener("mousedown",this.mousedown,!1)},q.prototype.mousedown=function(L){if(L.button===0){if(L.preventDefault(),this.options.stopPropagation&&L.stopPropagation(),this.currentAnchor=L.target,this.resizeStartLeft=L.screenX,this.resizeStartTop=L.screenY,document.defaultView&&this.resizeTarget){var oA=document.defaultView.getComputedStyle(this.resizeTarget);this.originTop=window.parseInt(oA.top),this.originLeft=window.parseInt(oA.left),this.originWidth=this.resizeTarget.offsetWidth,this.originHeight=this.resizeTarget.offsetHeight,lg.debug("resize origin:",this.originTop,this.originLeft,this.originWidth,this.originHeight)}else lg.debug("".concat(this.logPrefix,"mouseDown 'resizeTarget' is null"));document.addEventListener("mousemove",this.mousemove,!1),document.addEventListener("mouseup",this.mouseup,!1)}},q.prototype.mousemove=function(L){if(this.container&&this.resizeTarget&&this.currentAnchor){var oA,b=this.currentAnchor.classList[1],x=this.originLeft,tA=this.originTop,uA=this.originWidth,wA=this.originHeight;switch(b){case PE:tA=(oA=this._resizeTop(L)).top,wA=oA.height,x=(oA=this._resizeLeft(L)).left,uA=oA.width,this.options.keepRatio&&(uA/this.originWidththis.container.offsetWidth-this.originLeft&&(uA=this.container.offsetWidth-this.originLeft,wA=this.originHeight*uA/this.originWidth,tA=this.originTop+this.originHeight-wA));break;case Ju:tA=(oA=this._resizeTop(L)).top,wA=oA.height,uA=this._resizeRight(L),this.options.keepRatio&&(uA/this.originWidththis.container.offsetHeight-this.originTop&&(wA=this.container.offsetHeight-this.originTop,uA=this.originWidth*wA/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case gl:uA=this._resizeRight(L),this.options.keepRatio&&((wA=uA*this.originHeight/this.originWidth)<20?uA=(wA=20)*this.originWidth/this.originHeight:!this.options.canExceedContainer&&wA>this.container.offsetHeight-this.originTop&&(uA=(wA=this.container.offsetHeight-this.originTop)*this.originWidth/this.originHeight));break;case Lr:wA=this._resizeBottom(L),x=(oA=this._resizeLeft(L)).left,uA=oA.width,this.options.keepRatio&&(uA/this.originWidththis.container.offsetWidth-this.originLeft&&(wA=(uA=this.container.offsetWidth-this.originLeft)*this.originHeight/this.originWidth));break;case Ig:wA=this._resizeBottom(L),uA=this._resizeRight(L),this.options.keepRatio&&(uA/this.originWidththis.originLeft+this.originWidth-20&&(b=this.originLeft+this.originWidth-20,x=20),{left:b,width:x}},q.prototype._resizeTop=function(L){var oA=L.screenY-this.resizeStartTop,b=this.originTop+oA,x=this.originHeight-oA;return!this.options.canExceedContainer&&b<0?(b=0,x=this.originHeight+this.originTop):b>this.originTop+this.originHeight-20&&(b=this.originTop+this.originHeight-20,x=20),{top:b,height:x}},q.prototype._resizeRight=function(L){if(!this.container)return lg.debug("".concat(this.logPrefix,"_resizeRight error. No container:"),this.container),0;var oA=L.screenX-this.resizeStartLeft,b=this.originWidth+oA;return b<20?b=20:!this.options.canExceedContainer&&b>this.container.offsetWidth-this.originLeft&&(b=this.container.offsetWidth-this.originLeft),b},q.prototype._resizeBottom=function(L){if(!this.container)return lg.debug("".concat(this.logPrefix,"_resizeBottom error. No container:"),this.container),0;var oA=L.screenY-this.resizeStartTop,b=this.originHeight+oA;return b<20?b=20:!this.options.canExceedContainer&&b>this.container.offsetHeight-this.originTop&&(b=this.container.offsetHeight-this.originTop),b},q.prototype.mouseup=function(){document.removeEventListener("mousemove",this.mousemove,!1),document.removeEventListener("mouseup",this.mouseup,!1),this.currentAnchor=null,this.resizeStartLeft=0,this.resizeStartTop=0,this.originLeft=0,this.originTop=0,this.originWidth=0,this.originHeight=0},q.prototype.on=function(L,oA){var b=this.callbacksMap.get(L);b?b.push(oA):this.callbacksMap.set(L,[oA])},q.prototype.off=function(L,oA){var b=this.callbacksMap.get(L);b&&(b=b.filter(function(x){return x!=oA}),this.callbacksMap.set(L,b))},q.prototype.emit=function(L){for(var oA=[],b=1;bx?b:x,this.previewWidth=this.mixingVideoWidth*this.previewScale,this.previewHeight=this.mixingVideoHeight*this.previewScale,this.previewLeft=(L-this.previewWidth)/2,this.previewTop=(oA-this.previewHeight)/2}else console.debug("".concat(this.logPrefix,"calcPreviewScale failed, no HTML element to display"))},q.prototype.updateOverlay=function(){if(this.moveAndResizeOverlay){var L=void 0,oA=void 0,b=void 0,x=void 0;if(this.selectedMediaIndex>=0){var tA=this.mediaList[this.selectedMediaIndex],uA={left:tA.rect.left*this.previewScale,top:tA.rect.top*this.previewScale,right:tA.rect.right*this.previewScale,bottom:tA.rect.bottom*this.previewScale};L="".concat(uA.left+this.previewLeft,"px"),oA="".concat(uA.top+this.previewTop,"px"),b="".concat(uA.right-uA.left,"px"),x="".concat(uA.bottom-uA.top,"px");var wA=tA.interaction||{},XA=wA.showBorder!==!1,pe=wA.showResizeAnchors!==!1,p=wA.draggable!==!1,B=wA.canExceedCanvas!==!1;this.logger.debug("".concat(this.logPrefix,"updateOverlay: interaction config -"),{showBorder:XA,showResizeAnchors:pe,draggable:p,canExceedCanvas:B}),this.updateCanExceedContainer(B),this.moveAndResizeOverlay.style.display="block",this.moveAndResizeOverlay.style.border=XA?"1px solid #3D7EFD":"none",this.resizableHandler&&this.resizableHandler.setVisible(pe),this.movableHandler&&(this.logger.debug("".concat(this.logPrefix,"updateOverlay: setting movableHandler.setEnabled(").concat(p,")")),this.movableHandler.setEnabled(p))}else L="".concat(this.previewLeft,"px"),oA="".concat(this.previewTop,"px"),b="0px",x="0px",this.moveAndResizeOverlay.style.display="none";this.moveAndResizeOverlay.style.left=L,this.moveAndResizeOverlay.style.top=oA,this.moveAndResizeOverlay.style.width=b,this.moveAndResizeOverlay.style.height=x}},q.prototype.onMove=function(L,oA){var b;console.debug("".concat(this.logPrefix,"onMove: ").concat(L," ").concat(oA));var x=this.mediaList[this.selectedMediaIndex];if(x&&this.moveAndResizeOverlay){var tA={left:L-this.previewLeft,top:oA-this.previewTop,right:L-this.previewLeft+this.moveAndResizeOverlay.offsetWidth,bottom:oA-this.previewTop+this.moveAndResizeOverlay.offsetHeight};this.doAdsorption(tA);var uA={left:Math.round(tA.left/this.previewScale),top:Math.round(tA.top/this.previewScale),right:Math.round(tA.right/this.previewScale),bottom:Math.round(tA.bottom/this.previewScale)};(b=this.eventEmitter)===null||b===void 0||b.emit("onSourceMoved",sA({},x),uA)}else console.debug("".concat(this.logPrefix,"onMove no selected media"))},q.prototype.doAdsorption=function(L){var oA=this.BOUNDARY_ADSORPTION_THRESHOLD;Math.abs(L.left)pe&&(pe=B,XA=L[p])}return XA},q.prototype.emitOnSelect=function(L){var oA;if(L){for(var b=this.mediaList.length,x=0;x=p.rect.left&&wA<=p.rect.right&&XA>=p.rect.top&&XA<=p.rect.bottom&&((oA=p.interaction)===null||oA===void 0?void 0:oA.selectable)!==!1&&(this.clickedMediaSources.push(p),this.mediaList[this.selectedMediaIndex]&&p.id===this.mediaList[this.selectedMediaIndex].id&&(this.oldSelectedIndex=this.clickedMediaSources.length-1))}this.mousedownLeft=L.screenX,this.mousedownTop=L.screenY}this.clickedMediaSources.length>0?this.eventButton===2&&this.oldSelectedIndex===-1?(this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMousedown find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected),this.clickedMediaSources.splice(0,this.clickedMediaSources.length)):(document.addEventListener("mousemove",this.onContainerMousemove,!1),document.addEventListener("mouseup",this.onContainerMouseup,!1)):(this.newSelected=null,console.debug("".concat(this.logPrefix,"onContainerMousedown find clicked media source:"),this.newSelected),this.emitOnSelect(null),this.mousedownLeft=null,this.mousedownTop=null,this.eventButton=null)}},q.prototype.onContainerMousemove=function(L){var oA;if(L.target&&this.container&&this.mousedownLeft!==null&&this.mousedownTop!==null){var b=L.screenX-this.mousedownLeft,x=L.screenY-this.mousedownTop;(Math.abs(b)>=5||Math.abs(x)>=5)&&(this.oldSelectedIndex>=0?(console.debug("".concat(this.logPrefix,"onContainerMousemove move or resize old selected media source, clear data:"),this.clickedMediaSources,this.oldSelectedIndex),this.clickedMediaSources.splice(0,this.clickedMediaSources.length),this.oldSelectedIndex=-1):this.clickedMediaSources.length>0&&(this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMousemove find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected),this.clickedMediaSources.splice(0,this.clickedMediaSources.length),(oA=this.moveAndResizeOverlay)===null||oA===void 0||oA.dispatchEvent(new MouseEvent("mousedown",{screenX:this.mousedownLeft,screenY:this.mousedownTop,button:this.eventButton}))))}},q.prototype.onContainerMouseup=function(L){if(document.removeEventListener("mousemove",this.onContainerMousemove,!1),document.removeEventListener("mouseup",this.onContainerMouseup,!1),console.debug("".concat(this.logPrefix,"onContainerMouseup data:"),this.clickedMediaSources,this.oldSelectedIndex),L.target&&this.container){if(this.clickedMediaSources.length>0)if(this.oldSelectedIndex>=0){if(this.eventButton===0){var oA=(this.oldSelectedIndex+1)%this.clickedMediaSources.length;this.newSelected=this.clickedMediaSources[oA],console.debug("".concat(this.logPrefix,"onContainerMouseup find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected)}}else this.newSelected=this.getMaxZOrderMedia(this.clickedMediaSources),console.debug("".concat(this.logPrefix,"onContainerMouseup find clicked media source:"),this.newSelected),this.emitOnSelect(this.newSelected)}else console.debug("".concat(this.logPrefix,"onContainerMouseup click outside of mixing video image")),this.emitOnSelect(null);this.mousedownLeft=null,this.mousedownTop=null,this.clickedMediaSources.splice(0,this.clickedMediaSources.length),this.oldSelectedIndex=-1,this.newSelected=null,this.eventButton=null},q.prototype.onRightButtonClicked=function(L){var oA;console.debug("".concat(this.logPrefix,"onRightButtonClicked:"),L.target,L.currentTarget,L.buttons),L.preventDefault(),(oA=this.eventEmitter)===null||oA===void 0||oA.emit("onRightButtonClicked",sA({},this.mediaList[this.selectedMediaIndex]))},q}(),Fl=function(){function q(L){if(this.logPrefix="[TRTCMediaMixingManager]",this.eventEmitter=new qe,this.publishParams={videoEncoderParams:{videoResolution:r.TRTCVideoResolution.TRTCVideoResolution_1280_720,resMode:r.TRTCVideoResolutionMode.TRTCVideoResolutionModeLandscape,videoFps:15,videoBitrate:1800},canvasColor:0},this.mediaMixingDesigner=null,this.sourceList=[],this.trtcSourceMap=new Map,this.mixVideoTrack=null,this.selectedSource=null,this.view=null,this.screensWithSystemAudio=new Set,q.mediaMixingManager)return q.mediaMixingManager;q.mediaMixingManager=this,this.logger=L.logger,this.trtc=L.trtc,this.trtcCloud=L.trtcCloud,this.onSourceSelected=this.onSourceSelected.bind(this),this.onSourceMoved=this.onSourceMoved.bind(this),this.onSourceResized=this.onSourceResized.bind(this),this.onRightButtonClicked=this.onRightButtonClicked.bind(this)}return q.prototype.destroy=function(){return IA(this,void 0,Promise,function(){var L,oA,b,x,tA;return cA(this,function(uA){switch(uA.label){case 0:this.view=null,uA.label=1;case 1:return uA.trys.push([1,3,,4]),[4,this.trtc.stopPlugin("VideoMixer")];case 2:return uA.sent(),[3,4];case 3:return L=uA.sent(),this.logger.error("".concat(this.logPrefix," destroy and stopPlugin error:"),L),[3,4];case 4:if(!(this.screensWithSystemAudio.size>0))return[3,12];uA.label=5;case 5:uA.trys.push([5,10,,11]),oA=0,b=Array.from(this.screensWithSystemAudio),uA.label=6;case 6:return oA1){var pe=[];this.queue=this.queue.filter(function(p,B){return B===0||p.functionName!==x||(pe.push(p),!1)}),pe.forEach(function(p){p.reject(new Error("aborted by newer task"))})}this.queue.push(wA)}return this.isRunning||this.callNext(),XA},q.prototype.shift=function(){return this.queue.shift()},q.prototype.callNext=function(){var L=this;if(!this.isRunning&&this.length!==0){var oA=this.queue[0],b=oA.fn,x=oA.args,tA=oA.context,uA=oA.resolve,wA=oA.reject;this.isRunning=!0,b.apply(tA,x).then(uA,wA).finally(function(){L.isRunning=!1,L.shift(),L.callNext()})}},q}(),DI=new WeakMap,iu=new WeakMap,Ba=new WeakMap;function cl(q,L){return L===void 0&&(L={}),function(oA,b,x){var tA=x.value,uA=L.deduplicate,wA=uA!==void 0&&uA;return x.value=function(){for(var XA=[],pe=0;pe0;if(L&&!this.isMessageListenerRegistered)return this.trtc.on(U.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),void(this.isMessageListenerRegistered=!0);!L&&this.isMessageListenerRegistered&&(this.trtc.off(U.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),this.isMessageListenerRegistered=!1)},q.prototype.log=function(){for(var L,oA,b=[],x=0;x0&&clearTimeout(su),su=window.setTimeout(function(){YE.apply(q,L),su=-1},Jr)}));var qu=new Map,fC=function(q){function L(b){b===void 0&&(b={});var x=q.call(this)||this;x._version="",x._frameWorkType=30,x._component=0,x._language=0,x._networkProxy={},x._localView=null,x._autoRecvAudio=!0,x._autoRecvVideo=!1,x._localTestView=null,x._isVideoPublish=!0,x._localRenderParams={rotation:r.TRTCVideoRotation.TRTCVideoRotation0,fillMode:r.TRTCVideoFillMode.TRTCVideoFillMode_Fill,mirrorType:r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto},x._encoderMirror=void 0,x._videoProfile={},x._isAudioPublish=!0,x._audioMuteType=!1,x._audioProfile=U.default.TYPE.AUDIO_PROFILE_STANDARD,x._captureVolume=100,x._playoutVolume=100,x._isSharingScreen=!1,x._remoteStreamConfig=new Map,x._remoteStreamMap=new Map,x._cameraList=[],x._microphoneList=[],x._speakerList=[],x._currentCamera={},x._currentMicrophone={},x._currentSpeaker={},x._currentCameraId="",x._currentMicrophoneId="",x._currentSpeakerId="",x._screenShareParams={option:{}},x._isMobile=$I,x._isFrontCamera=!0,x._cameraVideoTrack=null,x._smallStreamVideoProfile=void 0,x._qosPreference=void 0,x._defaultVideoProfile={width:640,height:480,frameRate:15,bitrate:900},x._defaultScreenProfile={width:1920,height:1080,frameRate:15,bitrate:1500},x._defaultSmallVideoProfile={width:160,height:120,frameRate:15,bitrate:200},x._isVirtualBackground=!1,x._isTestVirtualBackground=!1,x._isBeautyEnabled=!1,x._isTestBeautyEnabled=!1,x._remoteStatisticsUserIdList=[],x._hasJoinedRoom=!1,x._isExitingRoom=!1,x._version=mC;var tA=b.frameWorkType,uA=tA===void 0?30:tA,wA=b.component,XA=wA===void 0?0:wA,pe=b.language,p=pe===void 0?0:pe;return x._frameWorkType=uA,x._component=XA,x._language=p,x._trtc=U.default.create({enableSEI:L.enableSEI,assetsPath:L.assetsPath,enableVolumeControlInIOS:!0,plugins:[j.default,I.LEBPlayer,w.RealtimeTranscriber]}),x._testTrtc=U.default.create(),x._log=U.default._loggerManager,x.logger=new tc(ou,{seq:Hu++}),x._echoCancellation=void 0,x._noiseSuppression=void 0,x._autoGainControl=void 0,x._addTRTCEvents(),x.handleDeviceChange=x.handleDeviceChange.bind(x),qu.set(x,{fn:x.handleDeviceChange,self:x}),x}var oA;return function(b,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");function tA(){this.constructor=b}lA(b,x),b.prototype=x===null?Object.create(x):(tA.prototype=x.prototype,new tA)}(L,q),L.getPlugin=function(b){return b==="VirtualBackground"?h.VirtualBackground:b==="BasicBeauty"?f.BasicBeauty:b==="VideoMixer"?j.default:null},L.getTRTCShareInstance=function(b){return L.shareInstance||(L.shareInstance=new L(b)),L.shareInstance},L.setLogLevel=function(b,x){var tA,uA=((tA={})[r.TRTCLogLevel.TRTCLogLevelVerbose]=0,tA[r.TRTCLogLevel.TRTCLogLevelDebug]=1,tA[r.TRTCLogLevel.TRTCLogLevelInfo]=2,tA[r.TRTCLogLevel.TRTCLogLevelWarn]=3,tA[r.TRTCLogLevel.TRTCLogLevelError]=4,tA[r.TRTCLogLevel.TRTCLogLevelFatal]=4,tA[r.TRTCLogLevel.TRTCLogLevelNone]=5,tA),wA=uA[b];ds(wA)&&(wA=uA[r.TRTCLogLevel.TRTCLogLevelInfo]);var XA=!Pi(x)||x;U.default.setLogLevel(wA,XA)},L.destroyTRTCShareInstance=function(){L.shareInstance&&(L.shareInstance._destroy(),L.shareInstance=null),Array.from(L.subCloudMap.keys()).forEach(function(b){return b._destroy()})},L.callExperimentalAPI=function(b){console.log("static ".concat(Pt,".callExperimentalAPI"),b);var x=Rs(b);if(x!==b){var tA=x.api,uA=x.params;if(tA&&uA)try{switch(tA){case"enableSEI":L.enableSEI=uA.enable;break;case"setAssetsPath":L.assetsPath=uA.assetsPath}}catch(wA){throw wA}}},L.prototype.createSubCloud=function(){if(this!==L.shareInstance)return null;var b=new L;return this._inheritPropertiesToSubCloud(b),this._inheritEventsToSubCloud(b),L.subCloudMap.set(b,b),b},L.prototype.destroy=function(){this!==L.shareInstance?(L.subCloudMap.get(this)&&L.subCloudMap.delete(this),this._destroy()):L.destroyTRTCShareInstance()},L.prototype._destroy=function(){qu.delete(this),this.removeAllListeners(),this._trtc.off("*"),this._trtc.destroy(),this._trtc=null,this._testTrtc.off("*"),this._testTrtc.destroy(),this._testTrtc=null},L.prototype.getSDKVersion=function(){return this._version||""},L.prototype.enterRoom=function(b,x){return IA(this,void 0,Promise,function(){var tA,uA,wA,XA,pe,p,B,v,N,O,z,X,rA,DA,GA,VA,ee,Ee;return cA(this,function(We){switch(We.label){case 0:if(tA=b.sdkAppId,uA=b.userId,wA=b.userSig,XA=b.roomId,pe=b.strRoomId,p=b.role,B=b.privateMapKey,v=b.businessInfo,N=b.enableAutoPlayDialog,O=b.proxy,z=b.streamId,X=b.userDefineRecordId,this.logger.update({sdkAppId:tA,userId:uA}),this.logger.info("".concat(Pt,".enterRoom with params: "),b,x),O&&(this._networkProxy=O),!(tA&&uA&&wA))return[3,5];We.label=1;case 1:return We.trys.push([1,3,,4]),rA={sdkAppId:tA,userId:uA,userSig:wA,roomId:XA,strRoomId:pe,role:Do[p],scene:pA[x],autoReceiveAudio:this._autoRecvAudio,autoReceiveVideo:this._autoRecvVideo,frameWorkType:this._frameWorkType,component:this._component,language:this._language},rA=B?sA(sA({},rA),{privateMapKey:B}):rA,rA=v?sA(sA({},rA),{businessInfo:v}):rA,DA=N||this._enableAutoPlayDialog,rA=Pi(DA)?sA(sA({},rA),{enableAutoPlayDialog:DA}):rA,rA=this._networkProxy?sA(sA({},rA),{proxy:this._networkProxy}):rA,rA=z?sA(sA({},rA),{streamId:z}):rA,rA=X?sA(sA({},rA),{userDefineRecordId:X}):rA,rA=this._latencyLevel!==void 0?sA(sA({},rA),{latencyLevel:this._latencyLevel}):rA,GA=Qr(),[4,this._trtc.enterRoom(rA)];case 2:return We.sent(),this._hasJoinedRoom=!0,VA=Qr()-GA,this.emit("onEnterRoom",VA),[3,4];case 3:return ee=We.sent(),Ee=(Ee=this._transformTRTCErrorCode(ee,"enterRoom"))<0?Ee:-1,this.emit("onEnterRoom",Ee),this._callFunctionErrorManage(ee,"enterRoom"),[3,4];case 4:return[3,6];case 5:this._emitError(mI),We.label=6;case 6:return[2]}})})},L.prototype.exitRoom=function(){return IA(this,void 0,Promise,function(){var b;return cA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),this.logger.info("".concat(Pt,".exitRoom")),this._isExitingRoom=!0,this._isSharingScreen&&this.stopScreenShare(),this.resetTRTCCloud(),this.stopLocalPreview(),this.stopLocalAudio(),[4,this._trtc.exitRoom()];case 1:return x.sent(),this._hasJoinedRoom=!1,this._isExitingRoom=!1,this._isVideoPublish=!0,this._isAudioPublish=!0,this.emit("onExitRoom",nl.exitRoom),[3,3];case 2:return b=x.sent(),this._callFunctionErrorManage(b,"exitRoom"),[3,3];case 3:return[2]}})})},L.prototype.switchRole=function(b){return IA(this,void 0,void 0,function(){var x;return cA(this,function(tA){switch(tA.label){case 0:this.logger.info("".concat(Pt,".switchRole with param: "),b),tA.label=1;case 1:return tA.trys.push([1,3,,4]),[4,this._trtc.switchRole(Do[b])];case 2:return tA.sent(),this.emit("onSwitchRole",0,"switch role success, role = ".concat(b,", ").concat(Do[b])),[3,4];case 3:return x=tA.sent(),this.emit("onSwitchRole",x?.getCode(),x.message),[3,4];case 4:return[2]}})})},L.prototype.setDefaultStreamRecvMode=function(b,x){return IA(this,void 0,void 0,function(){return cA(this,function(tA){return this.logger.info("".concat(Pt,".setDefaultStreamRecvMode with param: "),{autoRecvAudio:b,autoRecvVideo:x}),Pi(b)&&(this._autoRecvAudio=b),Pi(x)&&(this._autoRecvVideo=x),[2]})})},L.prototype.resetTRTCCloud=function(){this._setIsAudioPublish(!0),this._setAudioMuteType(!1),this._echoCancellation=void 0,this._noiseSuppression=void 0,this._autoGainControl=void 0,this._isVirtualBackground=!1,this._isTestVirtualBackground=!1,this._remoteStatisticsUserIdList=[],this._resetBeautyStyle()},L.prototype._updateLocalVideo=function(){return IA(this,void 0,void 0,function(){var b;return cA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._trtc.updateLocalVideo(this._generateLocalVideoData())];case 1:return x.sent(),[3,3];case 2:if((b=x.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT)throw b;return[3,3];case 3:return[2]}})})},L.prototype._updateLocalTestVideo=function(){return IA(this,void 0,void 0,function(){var b;return cA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._testTrtc.updateLocalVideo(this._generateLocalTestVideoData())];case 1:return x.sent(),[3,3];case 2:if((b=x.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT)throw b;return[3,3];case 3:return[2]}})})},L.prototype._updateLocalScreen=function(){return IA(this,void 0,void 0,function(){var b;return cA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),[4,this._trtc.updateScreenShare(this._getScreenShareParams())];case 1:return x.sent(),[3,3];case 2:if((b=x.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT)throw b;return[3,3];case 3:return[2]}})})},L.prototype._updateRemoteVideo=function(b,x){return IA(this,void 0,void 0,function(){var tA;return cA(this,function(uA){switch(uA.label){case 0:if(!this._hasJoinedRoom||this._isExitingRoom)return[2];uA.label=1;case 1:return uA.trys.push([1,3,,4]),[4,this._trtc.updateRemoteVideo(this._generateRemoteVideoData(b,x))];case 2:return uA.sent(),[3,4];case 3:if((tA=uA.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT)throw tA;return[3,4];case 4:return[2]}})})},L.prototype.startLocalPreview=function(){for(var b=[],x=0;x9)throw new Error("beautyLevel must be between 0 and 9");if(wA<0||wA>9)throw new Error("whitenessLevel must be between 0 and 9");if(XA<0||XA>9)throw new Error("ruddinessLevel must be between 0 and 9");z.label=1;case 1:return z.trys.push([1,8,,9]),B=wA/9,v=XA/9,(p=uA/9)===0&&B===0&&v===0?[4,b.stopPlugin(rn)]:[3,3];case 2:return z.sent(),pe?this._isTestBeautyEnabled=!1:this._isBeautyEnabled=!1,[3,7];case 3:return N={beauty:p,brightness:B,ruddy:v},x?[3,5]:[4,b.startPlugin(rn,N)];case 4:return z.sent(),pe?this._isTestBeautyEnabled=!0:this._isBeautyEnabled=!0,[3,7];case 5:return[4,b.updatePlugin(rn,N)];case 6:z.sent(),z.label=7;case 7:return[3,9];case 8:throw O=z.sent(),pe?this.logger.error("".concat(Pt,".").concat("setTestBeautyStyle"," fail: "),O):this.logger.error("".concat(Pt,".").concat("setBeautyStyle"," fail: "),O),O;case 9:return[2]}})})},L.prototype._resetBeautyStyle=function(){return IA(this,void 0,void 0,function(){return cA(this,function(b){switch(b.label){case 0:return this._isBeautyEnabled?[4,this._trtc.stopPlugin(rn)]:[3,2];case 1:b.sent(),this._isBeautyEnabled=!1,b.label=2;case 2:return this._isTestBeautyEnabled?[4,this._testTrtc.stopPlugin(rn)]:[3,4];case 3:b.sent(),this._isTestBeautyEnabled=!1,b.label=4;case 4:return[2]}})})},L.prototype.getMicDevicesList=function(){return IA(this,void 0,Promise,function(){var b,x,tA;return cA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Pt,".getMicDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,U.default.getMicrophoneList()];case 2:return b=uA.sent(),x=b.map(function(wA){return sA(sA({},wA),{deviceName:wA.label})}),this._microphoneList=b,JSON.stringify(this._currentMicrophone)!=="{}"?[3,4]:(this._currentMicrophone=this.getDefaultDeviceInfo(b),this._currentMicrophoneId=this._currentMicrophone.deviceId,[4,this.setCurrentMicDevice(this._currentMicrophoneId)]);case 3:uA.sent(),uA.label=4;case 4:return[2,Promise.resolve(x)];case 5:return tA=uA.sent(),this._callFunctionErrorManage(tA,"getMicDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},L.prototype.setCurrentMicDevice=function(b){var x;return IA(this,void 0,Promise,function(){var tA;return cA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Pt,".setCurrentMicDevice with params: "),{micId:b}),uA.label=1;case 1:return uA.trys.push([1,4,,5]),b?(this._setCurrentMicrophoneId(b),[4,this._updateLocalAudio()]):[2,!1];case 2:return uA.sent(),[4,this._updateLocalTestAudio()];case 3:return uA.sent(),this._currentMicrophone=this._microphoneList.find(function(wA){return wA.deviceId===b})||{},[3,5];case 4:throw tA=uA.sent(),this._setCurrentMicrophoneId((x=this._currentMicrophone)===null||x===void 0?void 0:x.deviceId),this._callFunctionErrorManage(tA,"setCurrentMicDevice"),tA;case 5:return[2]}})})},L.prototype.getCurrentMicDevice=function(){this.logger.info("".concat(Pt,".getCurrentMicDevice"));var b=this._currentMicrophone,x=b.deviceId,tA=b.label,uA=b.kind,wA=b.groupId;return new Oe(x,tA,uA,tA,wA)},L.prototype.getSpeakerDevicesList=function(){return IA(this,void 0,Promise,function(){var b,x,tA;return cA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Pt,".getSpeakerDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,U.default.getSpeakerList()];case 2:return b=uA.sent(),x=b.map(function(wA){return sA(sA({},wA),{deviceName:wA.label})}),this._speakerList=b,JSON.stringify(this._currentSpeaker)!=="{}"?[3,4]:(this._currentSpeaker=this.getDefaultDeviceInfo(b),this._currentSpeakerId=this._currentSpeaker.deviceId,[4,this.setCurrentSpeakerDevice(this._currentSpeakerId)]);case 3:uA.sent(),uA.label=4;case 4:return[2,Promise.resolve(x)];case 5:return tA=uA.sent(),this._callFunctionErrorManage(tA,"getSpeakerDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},L.prototype.setCurrentSpeakerDevice=function(b){return IA(this,void 0,Promise,function(){var x;return cA(this,function(tA){switch(tA.label){case 0:this.logger.info("".concat(Pt,".setCurrentSpeakerDevice with params: "),{speakerId:b}),tA.label=1;case 1:return tA.trys.push([1,3,,4]),b?[4,U.default.setCurrentSpeaker(b)]:[2,!1];case 2:return tA.sent(),this._setCurrentSpeakerId(b),this._currentSpeaker=this._speakerList.find(function(uA){return uA.deviceId===b})||{},[3,4];case 3:throw x=tA.sent(),this._callFunctionErrorManage(x,"setCurrentSpeakerDevice"),x;case 4:return[2]}})})},L.prototype.getCurrentSpeakerDevice=function(){this.logger.info("".concat(Pt,".getCurrentSpeakerDevice"));var b=this._currentSpeaker,x=b.deviceId,tA=b.label,uA=b.kind,wA=b.groupId;return new Oe(x,tA,uA,tA,wA)},L.prototype.startCameraDeviceTest=function(b){return IA(this,void 0,void 0,function(){var x;return cA(this,function(tA){switch(tA.label){case 0:if(this.logger.info("".concat(Pt,".startCameraDeviceTest with params: "),b),!b)return[2];this._setLocalTestView(b),tA.label=1;case 1:return tA.trys.push([1,3,,7]),[4,this._testTrtc.startLocalVideo(this._generateLocalTestVideoData())];case 2:return tA.sent(),[3,7];case 3:return(x=tA.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestVideo()];case 4:return tA.sent(),[3,6];case 5:throw this._callFunctionErrorManage(x,"startCameraDeviceTest"),x;case 6:return[3,7];case 7:return[2]}})})},L.prototype.stopCameraDeviceTest=function(){return IA(this,void 0,void 0,function(){return cA(this,function(b){switch(b.label){case 0:return this.logger.info("".concat(Pt,".stopCameraDeviceTest")),this._setLocalTestView(null),[4,this._testTrtc.stopLocalVideo()];case 1:return b.sent(),[2]}})})},L.prototype.startMicDeviceTest=function(b){return IA(this,void 0,void 0,function(){var x,tA=this;return cA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Pt,".startMicDeviceTest with params: "),b),uA.label=1;case 1:return uA.trys.push([1,3,,7]),[4,this._testTrtc.startLocalAudio(this._generateLocalTestAudioData())];case 2:return uA.sent(),[3,7];case 3:return(x=uA.sent()).code!==U.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestAudio()];case 4:return uA.sent(),[3,6];case 5:throw this._callFunctionErrorManage(x,"startMicDeviceTest"),x;case 6:return[3,7];case 7:return this._testTrtc.on(U.default.EVENT.AUDIO_VOLUME,function(wA){wA?.result.forEach(function(XA){var pe=XA.userId,p=XA.volume;pe===""&&tA.emit("onTestMicVolume",p)})}),[4,this._testTrtc.enableAudioVolumeEvaluation(b)];case 8:return uA.sent(),[2]}})})},L.prototype.stopMicDeviceTest=function(){return IA(this,void 0,void 0,function(){return cA(this,function(b){switch(b.label){case 0:return this.logger.info("".concat(Pt,".stopMicDeviceTest")),[4,this._testTrtc.stopLocalAudio()];case 1:return b.sent(),[2]}})})},L.prototype.callExperimentalAPI=function(b){return IA(this,void 0,void 0,function(){var x,tA,uA;return cA(this,function(wA){switch(wA.label){case 0:if(this.logger.info("".concat(Pt,".callExperimentalAPI"),b),(x=Rs(b))===b)return[2];if(tA=x.api,uA=x.params,!tA||!uA)return[2];wA.label=1;case 1:switch(wA.trys.push([1,25,,26]),tA){case"setFramework":return[3,2];case"enableAudioAEC":return[3,3];case"enableAudioANS":return[3,4];case"enableAudioAGC":return[3,5];case"KeyMetricsStats":return[3,6];case"setNetworkProxy":return[3,7];case"enableVirtualBackground":return[3,8];case"enableTestVirtualBackground":return[3,10];case"enableTestBeautyStyle":return[3,12];case"setVideoEncodeParamEx":return[3,14];case"enableAutoPlayDialog":return[3,15];case"setAudienceLatencyLevel":return[3,16];case"switchPlaybackQuality":return[3,17];case"requestPictureInPicture":return[3,19];case"exitPictureInPicture":return[3,21]}return[3,23];case 2:return this._handleSetFrameWork(uA),[3,24];case 3:return this._echoCancellation=!!uA.enable,[3,24];case 4:return this._noiseSuppression=!!uA.enable,[3,24];case 5:return this._autoGainControl=!!uA.enable,[3,24];case 6:return this._handleKeyMetricsStats(uA),[3,24];case 7:return this._networkProxy=uA,[3,24];case 8:return[4,this.setVirtualBackground(uA)];case 9:return wA.sent(),[3,24];case 10:return[4,this.setTestVirtualBackground(uA)];case 11:return wA.sent(),[3,24];case 12:return[4,this.setTestBeautyStyle(uA.style,uA.beautyLevel,uA.whitenessLevel,uA.ruddinessLevel)];case 13:return wA.sent(),[3,24];case 14:return this._setVideoEncodeParamEx(uA),[3,24];case 15:return this._enableAutoPlayDialog=!!uA.enable,[3,24];case 16:return this._latencyLevel=uA.latencyLevel,[3,24];case 17:return[4,this._switchPlaybackQuality(uA)];case 18:return wA.sent(),[3,24];case 19:return[4,this._requestPictureInPicture()];case 20:return wA.sent(),[3,24];case 21:return[4,this._exitPictureInPicture()];case 22:return wA.sent(),[3,24];case 23:return[3,24];case 24:return[3,26];case 25:throw wA.sent();case 26:return[2]}})})},L.prototype._handleSetFrameWork=function(b){var x=b.frameWork,tA=b.component,uA=b.language;zr(x)&&(this._frameWorkType=x),zr(tA)&&(this._component=tA),zr(uA)&&(this._language=uA)},L.prototype._handleKeyMetricsStats=function(b){var x=b.key,tA=b.opt,uA=b.value,wA=b.version,XA=tA===Jn;U.default._addKVStat({type:tA,key:x,value:uA,version:wA,useUV:XA,base:100})},L.prototype._setVideoEncodeParamEx=function(b){return IA(this,void 0,void 0,function(){return cA(this,function(x){switch(x.label){case 0:switch(b.streamType){case r.TRTCVideoStreamType.TRTCVideoStreamTypeBig:return[3,1];case r.TRTCVideoStreamType.TRTCVideoStreamTypeSub:return[3,3]}return[3,5];case 1:return[4,this.setVideoEncoderParam(b)];case 2:case 4:return x.sent(),[3,6];case 3:return[4,this.setSubStreamEncoderParam(b)];case 5:return[3,6];case 6:return[2]}})})},L.prototype._switchPlaybackQuality=function(b){return IA(this,void 0,void 0,function(){var x,tA,uA,wA,XA,pe,p,B;return cA(this,function(v){switch(v.label){case 0:if(tA=(x=b||{}).quality,uA=x.stream_list,wA=uA===void 0?[]:uA,!tA||wA.length===0)return[2];for(XA=null,pe=0,p=wA;pe1&&x[1]),height:+(x.length>2&&x[2])}},L.prototype._getTRTCVideoProfile=function(b,x){x===void 0&&(x={});var tA=x.videoWidth,uA=x.videoHeight,wA=x.videoResolution,XA=x.videoFps,pe=x.videoBitrate,p=x.resMode,B=x.resolutionMode,v={};switch(b){case r.TRTCVideoStreamType.TRTCVideoStreamTypeSub:v=this._defaultScreenProfile;break;case r.TRTCVideoStreamType.TRTCVideoStreamTypeSmall:v=this._defaultSmallVideoProfile;break;case r.TRTCVideoStreamType.TRTCVideoStreamTypeBig:default:v=this._defaultVideoProfile}if(ds(wA))ds(tA)||(v.width=tA),ds(uA)||(v.height=uA);else{var N=this._getTRTCResolution(wA);v.width=N.width,v.height=N.height}if(!ds(p)&&p===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait||!ds(B)&&B===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait){var O=v.height,z=v.width;v.width=O,v.height=z}return XA&&(v.frameRate=XA),pe&&(v.bitrate=pe),v},L.prototype._getTRTCStreamType=function(b){var x;return((x={})[r.TRTCVideoStreamType.TRTCVideoStreamTypeBig]=U.default.TYPE.STREAM_TYPE_MAIN,x[r.TRTCVideoStreamType.TRTCVideoStreamTypeSmall]=U.default.TYPE.STREAM_TYPE_MAIN,x[r.TRTCVideoStreamType.TRTCVideoStreamTypeSub]=U.default.TYPE.STREAM_TYPE_SUB,x)[b]},L.prototype._getTRTCFillMode=function(b){var x;return((x={})[r.TRTCVideoFillMode.TRTCVideoFillMode_Fill]=sl.COVER,x[r.TRTCVideoFillMode.TRTCVideoFillMode_Fit]=sl.CONTAIN,x)[b]},L.prototype._getTRTCCloudVideoFillMode=function(b){var x;return((x={})[sl.COVER]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fill,x[sl.CONTAIN]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fit,x)[b]},L.prototype._getTRTCCloudMirrorType=function(b){return b===!0?r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable:r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable},L.prototype._getLocalRenderMirror=function(b){var x;return b===r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto?!this._getIsMobile()||this._getIsFrontCamera():((x={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[b]},L.prototype._getTRTCLocalMirror=function(b,x){var tA=this._getLocalRenderMirror(b);return ds(x)?!!tA&&"both":tA&&x?"both":tA&&!x?"view":!tA&&x?"publish":!(!tA&&!x)&&"view"},L.prototype._getTRTCRemoteMirror=function(b){var x;return((x={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto]=!1,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[b]},L.prototype._getTRTCQosPreference=function(b){var x;return((x={})[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceSmooth]=U.default.TYPE.QOS_PREFERENCE_SMOOTH,x[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceClear]=U.default.TYPE.QOS_PREFERENCE_CLEAR,x)[b]},L.prototype._getTRTCAudioQuality=function(b){var x;return((x={})[r.TRTCAudioQuality.TRTCAudioQualitySpeech]=U.default.TYPE.AUDIO_PROFILE_STANDARD,x[r.TRTCAudioQuality.TRTCAudioQualityDefault]=U.default.TYPE.AUDIO_PROFILE_STANDARD,x[r.TRTCAudioQuality.TRTCAudioQualityMusic]=U.default.TYPE.AUDIO_PROFILE_HIGH_STEREO,x)[b]},L.prototype._getTRTCCloudDeviceType=function(b){return{camera:r.TRTCDeviceType.TRTCDeviceTypeCamera,microphone:r.TRTCDeviceType.TRTCDeviceTypeMic,speaker:r.TRTCDeviceType.TRTCDeviceTypeSpeaker}[b]},L.prototype._getTRTCCloudDeviceState=function(b){return{add:r.TRTCDeviceState.TRTCDeviceStateAdd,remove:r.TRTCDeviceState.TRTCDeviceStateRemove,active:r.TRTCDeviceState.TRTCDeviceStateActive}[b]},L.prototype._getTRTCCloudQuality=function(b){return[r.TRTCQuality.TRTCQuality_Unknown,r.TRTCQuality.TRTCQuality_Excellent,r.TRTCQuality.TRTCQuality_Good,r.TRTCQuality.TRTCQuality_Poor,r.TRTCQuality.TRTCQuality_Bad,r.TRTCQuality.TRTCQuality_Vbad,r.TRTCQuality.TRTCQuality_Down][b]},L.prototype._generateLocalVideoData=function(){var b={view:this._getLocalView(),publish:this._getIsVideoPublish(),option:{profile:this._getVideoProfile(),small:this._getSmallStreamVideoProfile()||!1,mirror:this._getTRTCLocalMirror(this._localRenderParams.mirrorType,this._encoderMirror),fillMode:this._getTRTCFillMode(this._localRenderParams.fillMode)}};return this._cameraVideoTrack?b&&Object.assign(b.option,{videoTrack:this._cameraVideoTrack}):this._getIsMobile()?b&&Object.assign(b.option,{useFrontCamera:this._getIsFrontCamera()}):b&&Object.assign(b.option,{cameraId:this._getCurrentCameraId()}),this._getQosPreference()&&b&&Object.assign(b.option,{qosPreference:this._getQosPreference()}),b},L.prototype._generateLocalTestVideoData=function(){var b={view:this._getLocalTestView(),publish:!1,option:{profile:this._getVideoProfile(),mirror:this._getTRTCLocalMirror(this._localRenderParams.mirrorType,this._encoderMirror),fillMode:this._getTRTCFillMode(this._localRenderParams.fillMode)}};return this._getIsMobile()?b&&Object.assign(b.option,{useFrontCamera:this._getIsFrontCamera()}):b&&Object.assign(b.option,{cameraId:this._getCurrentCameraId()}),b},L.prototype._generateLocalAudioData=function(){var b={publish:this._getIsAudioPublish(),mute:this._getAudioMuteType(),muteKeepVolumeDetection:!0,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile(),captureVolume:this._getCaptureVolume()}};return Pi(this._echoCancellation)&&(b.option.echoCancellation=this._echoCancellation),Pi(this._autoGainControl)&&(b.option.autoGainControl=this._autoGainControl),Pi(this._noiseSuppression)&&(b.option.noiseSuppression=this._noiseSuppression),b},L.prototype._generateLocalTestAudioData=function(){return{publish:!1,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile()}}},L.prototype._generateRemoteVideoData=function(b,x){return wn(this._remoteStreamConfig.get("".concat(b,"_").concat(this._getTRTCStreamType(x))))},L.prototype._addTRTCEvents=function(){var b=this;this._trtc.on(U.default.EVENT.ERROR,function(x){x&&b.emit("onError",x.code,x.message)}),this._trtc.on(U.default.EVENT.REMOTE_USER_ENTER,function(x){x?.userId&&b.emit("onRemoteUserEnterRoom",x.userId)}),this._trtc.on(U.default.EVENT.REMOTE_USER_EXIT,function(x){x?.userId&&b.emit("onRemoteUserLeaveRoom",x.userId)}),this._trtc.on(U.default.EVENT.REMOTE_AUDIO_AVAILABLE,function(x){x?.userId&&b.emit("onUserAudioAvailable",x.userId,!0)}),this._trtc.on(U.default.EVENT.REMOTE_AUDIO_UNAVAILABLE,function(x){x?.userId&&b.emit("onUserAudioAvailable",x.userId,!1)}),this._trtc.on(U.default.EVENT.REMOTE_VIDEO_AVAILABLE,function(x){b._emitVideoAvailable(x,!0)}),this._trtc.on(U.default.EVENT.REMOTE_VIDEO_UNAVAILABLE,function(x){b._emitVideoAvailable(x,!1)}),this._trtc.on(U.default.EVENT.AUDIO_VOLUME,function(x){x?.result&&b.emit("onUserVoiceVolume",x?.result,(x?.result||[]).length)}),this._trtc.on(U.default.EVENT.KICKED_OUT,function(x){var tA={banned:nl.banned,room_disband:nl.roomDisband};zr(tA[x.reason])&&b.emit("onExitRoom",tA[x.reason])}),this._trtc.on(U.default.EVENT.NETWORK_QUALITY,function(x){var tA=x.uplinkNetworkQuality,uA=x.downlinkNetworkQuality,wA=new jo("",b._getTRTCCloudQuality(tA)),XA=[];b._remoteStatisticsUserIdList.length>0&&(XA=b._remoteStatisticsUserIdList.map(function(pe){return new jo(pe,b._getTRTCCloudQuality(uA))})),b.emit("onNetworkQuality",wA,XA)}),this._trtc.on(U.default.EVENT.AUTOPLAY_FAILED,function(x){b.emit("onAutoPlayFailed",x)}),this._trtc.on(U.default.EVENT.SEI_MESSAGE,function(x){if(x.data&&typeof x.data=="object"&&x.data instanceof ArrayBuffer){for(var tA=new Uint8Array(x.data),uA="",wA=0;wA0?B.video.map(function(DA){var GA=new oo;return GA.width=DA.width,GA.height=DA.height,GA.frameRate=DA.frameRate,GA.videoBitrate=DA.bitrate,GA.audioBitrate=B.audio.bitrate||0,GA.streamType=N[DA.videoType],GA}):[];if(O.length===0&&B.audio.bitrate>0){var z=new oo;z.audioBitrate=B.audio.bitrate||0,O.push(z)}var X=[];v.forEach(function(DA){var GA=[],VA=DA.userId,ee=DA.audio.bitrate;if(DA.video&&DA.video.forEach(function(We){var ot=new bi;ot.userId=VA,ot.width=We.width,ot.height=We.height,ot.frameRate=We.frameRate,ot.videoBitrate=We.bitrate,ot.audioBitrate=ee||0,ot.streamType=N[We.videoType],GA.push(ot)}),GA.length===0){var Ee=new bi;Ee.userId=VA,Ee.audioBitrate=ee||0,GA.push(Ee)}X.push.apply(X,GA)});var rA=new vs;rA.upLoss=wA,rA.downLoss=XA,rA.rtt=uA,rA.sentBytes=pe,rA.receivedBytes=p,rA.localStatisticsArray=O,rA.localStatisticsArraySize=O.length,rA.remoteStatisticsArray=X,rA.remoteStatisticsArraySize=X.length,b.emit("onStatistics",rA)}),this._trtc.on(U.default.EVENT.SCREEN_SHARE_STOPPED,function(){b.emit("onScreenCaptureStopped",0),b._clearScreenShareParams(),b._isSharingScreen=!1}),this._trtc.on(U.default.EVENT.PUBLISH_STATE_CHANGED,function(x){var tA=x.mediaType;x.state==="started"&&(tA==="audio"?b.emit("onSendFirstLocalAudioFrame"):tA==="video"?b.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeBig):tA==="screen"&&b.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeSub))}),this._trtc.on(U.default.EVENT.FIRST_VIDEO_FRAME,function(x){var tA=x.userId,uA=x.streamType,wA=x.width,XA=x.height;b.emit("onFirstVideoFrame",tA,uA,wA,XA)}),this._trtc.on(U.default.EVENT.AUDIO_PLAY_STATE_CHANGED,function(x){var tA=x.userId;x.state==="PLAYING"&&b.emit("onFirstAudioFrame",tA)}),this._trtc.on(U.default.EVENT.DEVICE_CHANGED,function(x){var tA=x.type,uA=x.device,wA=x.action,XA=uA.deviceId;if(wA==="active"){switch(tA){case"camera":b._currentCameraId=XA,b._currentCamera=uA;break;case"microphone":b._currentMicrophoneId=XA,b._currentMicrophone=uA;break;case"speaker":b._currentSpeakerId=XA,b._currentSpeaker=uA}b.emitOnDeviceChange(XA,b._getTRTCCloudDeviceType(tA),b._getTRTCCloudDeviceState(wA))}}),this._trtc.on(U.default.EVENT.CUSTOM_MESSAGE,function(x){x&&b.emit("onRecvCustomCmdMsg",x.userId,x.cmdId,x.seq,x?.data)}),this._trtc.on(U.default.EVENT.CONNECTION_STATE_CHANGED,function(x){b._hasJoinedRoom&&!b._isExitingRoom&&(x.prevState==="CONNECTED"&&x.state==="DISCONNECTED"?b.emit("onConnectionLost"):x.prevState==="DISCONNECTED"&&x.state==="CONNECTING"?b.emit("onTryToReconnect"):x.prevState==="CONNECTING"&&x.state==="CONNECTED"&&b.emit("onConnectionRecovery"))}),this._trtc.on(U.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(x){b.emit("onPictureInPictureStateChanged",x)})},L.prototype._removeTRTCEvents=function(){this._trtc.off("*")},L.prototype._emitVideoAvailable=function(b,x){var tA=b.userId,uA=b.streamType;x?this._remoteStreamMap.set("".concat(tA,"_").concat(uA),!0):this._remoteStreamMap.delete("".concat(tA,"_").concat(uA)),uA===U.default.TYPE.STREAM_TYPE_SUB?tA&&this.emit("onUserSubStreamAvailable",tA,x):tA&&this.emit("onUserVideoAvailable",tA,x)},L.prototype._setLocalView=function(b){this._localView=b},L.prototype._getLocalView=function(){return this._localView},L.prototype._setIsMobile=function(b){this._isMobile=b},L.prototype._getIsMobile=function(){return this._isMobile},L.prototype._setIsFrontCamera=function(b){this._isFrontCamera=b},L.prototype._getIsFrontCamera=function(){return this._isFrontCamera},L.prototype._getSmallStreamVideoProfile=function(){return this._smallStreamVideoProfile},L.prototype._setSmallStreamVideoProfile=function(b){this._smallStreamVideoProfile=b},L.prototype._setIsVideoPublish=function(b){this._isVideoPublish=b},L.prototype._getIsVideoPublish=function(){return this._isVideoPublish},L.prototype._setVideoProfile=function(b){this._videoProfile=b},L.prototype._getVideoProfile=function(){return this._videoProfile},L.prototype._setQosPreference=function(b){this._qosPreference=b},L.prototype._getQosPreference=function(){return this._qosPreference},L.prototype._setLocalTestView=function(b){this._localTestView=b},L.prototype._getLocalTestView=function(){return this._localTestView},L.prototype._setScreenShareParams=function(b){var x=b.view,tA=b.systemAudio,uA=b.fillMode,wA=b.profile,XA=b.videoTrack,pe=b.qosPreference;ds(x)||(this._screenShareParams.view=x),ds(tA)||(this._screenShareParams.option.systemAudio=tA),ds(uA)||(this._screenShareParams.option.fillMode=uA),ds(wA)||(this._screenShareParams.option.profile=wA),ds(XA)||(this._screenShareParams.option.videoTrack=XA),ds(pe)||(this._screenShareParams.option.qosPreference=pe),ds(b.streamType)||(this._screenShareParams.streamType=this._getTRTCStreamType(b.streamType))},L.prototype._clearScreenShareParams=function(){var b,x,tA,uA,wA;!((b=this._screenShareParams)===null||b===void 0)&&b.view&&delete this._screenShareParams.view,!((tA=(x=this._screenShareParams)===null||x===void 0?void 0:x.option)===null||tA===void 0)&&tA.systemAudio&&delete this._screenShareParams.option.systemAudio,!((wA=(uA=this._screenShareParams)===null||uA===void 0?void 0:uA.option)===null||wA===void 0)&&wA.videoTrack&&delete this._screenShareParams.option.videoTrack},L.prototype._getScreenShareParams=function(){return this._screenShareParams},L.prototype._setIsAudioPublish=function(b){this._isAudioPublish=b},L.prototype._getIsAudioPublish=function(){return this._isAudioPublish},L.prototype._setAudioMuteType=function(b){this._audioMuteType=b},L.prototype._getAudioMuteType=function(){return this._audioMuteType},L.prototype._setAudioProfile=function(b){this._audioProfile=b},L.prototype._getAudioProfile=function(){return this._audioProfile},L.prototype._getCaptureVolume=function(){return this._captureVolume},L.prototype._setCaptureVolume=function(b){this._captureVolume=b},L.prototype._setCurrentCameraId=function(b){this._currentCameraId=b},L.prototype._getCurrentCameraId=function(){return this._currentCameraId},L.prototype._setCurrentMicrophoneId=function(b){this._currentMicrophoneId=b},L.prototype._getCurrentMicrophoneId=function(){return this._currentMicrophoneId},L.prototype._setCurrentSpeakerId=function(b){this._currentSpeakerId=b},L.prototype._getCurrentSpeakerId=function(){return this._currentSpeakerId},L.prototype._setRemoteStreamConfig=function(b,x,tA){var uA=this._remoteStreamConfig.get("".concat(b,"_").concat(this._getTRTCStreamType(x)));uA||(uA={userId:b,streamType:this._getTRTCStreamType(x),option:{mirror:this._getTRTCRemoteMirror(r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable),fillMode:this._getTRTCFillMode(r.TRTCVideoFillMode.TRTCVideoFillMode_Fit)}});var wA=tA.view,XA=tA.mirrorType,pe=tA.fillMode,p=tA.small;ds(wA)||(uA.view=wA),ds(XA)||(uA.option.mirror=this._getTRTCRemoteMirror(XA)),ds(pe)||(uA.option.fillMode=this._getTRTCFillMode(pe)),ds(p)||(uA.option.small=p),this._remoteStreamConfig.set("".concat(b,"_").concat(this._getTRTCStreamType(x)),uA)},L.prototype._inheritPropertiesToSubCloud=function(b){b._frameWorkType=this._frameWorkType,b._component=this._component,b._language=this._language,b._networkProxy=sA({},this._networkProxy),b._latencyLevel=this._latencyLevel,b._enableAutoPlayDialog=this._enableAutoPlayDialog},L.prototype._inheritEventsToSubCloud=function(b){var x=this;b._trtc.on(U.default.EVENT.AUTOPLAY_FAILED,function(tA){x.emit("onAutoPlayFailed",tA)}),b._trtc.on(U.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(tA){x.emit("onPictureInPictureStateChanged",tA)})},L.prototype.handleDeviceChange=function(){return IA(this,void 0,void 0,function(){var b=this;return cA(this,function(x){return U.default.getCameraList().then(function(tA){return IA(b,void 0,void 0,function(){return cA(this,function(uA){switch(uA.label){case 0:return this._cameraList.length===tA.length?[2]:[4,this.deviceChangeManage(this._cameraList,tA,r.TRTCDeviceType.TRTCDeviceTypeCamera)];case 1:return uA.sent(),this._cameraList=tA,[2]}})})}),U.default.getMicrophoneList().then(function(tA){return IA(b,void 0,void 0,function(){return cA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._microphoneList,tA,r.TRTCDeviceType.TRTCDeviceTypeMic)];case 1:return uA.sent(),this._microphoneList=tA,[2]}})})}),U.default.getSpeakerList().then(function(tA){return IA(b,void 0,void 0,function(){return cA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._speakerList,tA,r.TRTCDeviceType.TRTCDeviceTypeSpeaker)];case 1:return uA.sent(),this._speakerList=tA,[2]}})})}),[2]})})},L.prototype.isSameDevice=function(b,x){var tA=b&&b.deviceId&&b.groupId&&b.label,uA=x&&x.deviceId&&x.groupId&&x.label;return!(!tA||!uA)&&b.deviceId===x.deviceId&&b.groupId===x.groupId&&b.label===x.label},L.prototype.deviceChangeManage=function(b,x,tA){return IA(this,void 0,void 0,function(){var uA,wA,XA,pe,p;return cA(this,function(B){switch(B.label){case 0:return uA=void 0,b.length!==x.length&&(wA=(x||[]).map(function(v){return v.deviceId}),XA=new Oe,b.length>x.length?(XA=b.filter(function(v){return!wA.includes(v.deviceId)})[0]||{},uA=r.TRTCDeviceState.TRTCDeviceStateRemove):(wA=(b||[]).map(function(v){return v.deviceId}),XA=x.filter(function(v){return!wA.includes(v.deviceId)})[0]||{},uA=r.TRTCDeviceState.TRTCDeviceStateAdd),pe=XA.deviceId,this.emitOnDeviceChange(pe,tA,uA)),p=this.getDefaultDeviceInfo(x),tA!==r.TRTCDeviceType.TRTCDeviceTypeCamera||uA!==r.TRTCDeviceState.TRTCDeviceStateRemove?[3,3]:this.isSameDevice(this._currentCamera,p)?[2]:p.deviceId?[4,this.autoChangeDevice(tA,p)]:[3,2];case 1:B.sent(),B.label=2;case 2:B.label=3;case 3:return tA!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,6]:this.isSameDevice(this._currentMicrophone,p)?[2]:p.deviceId?[4,this.autoChangeDevice(tA,p)]:[3,5];case 4:B.sent(),B.label=5;case 5:B.label=6;case 6:return tA!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,9]:this.isSameDevice(this._currentSpeaker,p)?[2]:p.deviceId?[4,this.autoChangeDevice(tA,p)]:[3,8];case 7:B.sent(),B.label=8;case 8:B.label=9;case 9:return[2]}})})},L.prototype.getDefaultDeviceInfo=function(b){var x=new Oe;if(b.length===0)return x;var tA=b.filter(function(uA){return uA.deviceId==="default"});return x=tA.length>0?tA[0]:b[0]},L.prototype.autoChangeDevice=function(b,x){return IA(this,void 0,void 0,function(){var tA,uA,wA;return cA(this,function(XA){switch(XA.label){case 0:return tA=x.deviceId,b!==r.TRTCDeviceType.TRTCDeviceTypeCamera?[3,6]:(this._setCurrentCameraId(tA),[4,this._updateLocalVideo()]);case 1:XA.sent(),XA.label=2;case 2:return XA.trys.push([2,4,,5]),[4,this._testTrtc.updateLocalVideo({option:{cameraId:tA}})];case 3:return XA.sent(),[3,5];case 4:return uA=XA.sent(),console.log("testTRTC error",JSON.stringify(uA)),uA.code,U.default.ERROR_CODE.OPERATION_ABORT,[3,5];case 5:this._currentCameraId=tA,this._currentCamera=x,this.emitOnDeviceChange(tA,b,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=6;case 6:return b!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,12]:(this._setCurrentMicrophoneId(tA),[4,this._updateLocalAudio()]);case 7:XA.sent(),XA.label=8;case 8:return XA.trys.push([8,10,,11]),[4,this._testTrtc.updateLocalAudio({option:{microphoneId:tA}})];case 9:return XA.sent(),[3,11];case 10:return wA=XA.sent(),console.log("testTRTC error",JSON.stringify(wA)),wA.code,U.default.ERROR_CODE.OPERATION_ABORT,[3,11];case 11:this._currentMicrophoneId=tA,this._currentMicrophone=x,this.emitOnDeviceChange(tA,b,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=12;case 12:return b!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,14]:[4,U.default.setCurrentSpeaker(tA)];case 13:XA.sent(),this._currentSpeakerId=tA,this._currentSpeaker=x,this.emitOnDeviceChange(tA,b,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=14;case 14:return[2]}})})},L.prototype.emitOnDeviceChange=function(b,x,tA){this.emit("onDeviceChange",b,x,tA)},L.prototype.getMediaMixingManager=function(){return new Fl({logger:this.logger,trtc:this._trtc,trtcCloud:this})},L.prototype.getAITranscriberManager=function(){return new xE({logger:this.logger,trtc:this._trtc})},L.shareInstance=null,L.subCloudMap=new Map,L.enableSEI=!1,L.assetsPath="",mA([(oA="exitRoom",function(b,x,tA){var uA=tA.value;return tA.value=function(){for(var wA,XA,pe,p,B=[],v=0;vH.length)&&(BA=H.length);for(var yA=0,NA=new Array(BA);yA=0;--on){var os=this.tryEntries[on],Eg=os.completion;if(os.tryLoc==="root")return yo("end");if(os.tryLoc<=this.prev){var Ol=zA.call(os,"catchLoc"),fd=zA.call(os,"finallyLoc");if(Ol&&fd){if(this.prev=0;--yo){var on=this.tryEntries[yo];if(on.tryLoc<=this.prev&&zA.call(on,"finallyLoc")&&this.prev=0;--ni){var yo=this.tryEntries[ni];if(yo.finallyLoc===Ri)return this.complete(yo.completion,yo.afterLoc),qr(yo),ci}},catch:function(Ri){for(var ni=this.tryEntries.length-1;ni>=0;--ni){var yo=this.tryEntries[ni];if(yo.tryLoc===Ri){var on=yo.completion;if(on.type==="throw"){var os=on.arg;qr(yo)}return os}}throw new Error("illegal catch attempt")},delegateYield:function(Ri,ni,yo){return this.delegate={iterator:Ku(Ri),resultName:ni,nextLoc:yo},this.method==="next"&&(this.arg=void 0),ci}},yA}(H.exports);try{regeneratorRuntime=BA}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=BA:Function("r","regeneratorRuntime = r")(BA)}});var sA,mA,IA=function(H){return H&&H.Math==Math&&H},cA=IA(typeof globalThis=="object"&&globalThis)||IA(typeof window=="object"&&window)||IA(typeof self=="object"&&self)||IA(typeof j=="object"&&j)||function(){return this}()||Function("return this")(),TA=function(H){try{return!!H()}catch{return!0}},WA=!TA(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ue={}.propertyIsEnumerable,Ce=Object.getOwnPropertyDescriptor,xe={f:Ce&&!ue.call({1:2},1)?function(H){var BA=Ce(this,H);return!!BA&&BA.enumerable}:ue},Qe=function(H,BA){return{enumerable:!(1&H),configurable:!(2&H),writable:!(4&H),value:BA}},ut={}.toString,ft=function(H){return ut.call(H).slice(8,-1)},je="".split,Mt=TA(function(){return!Object("z").propertyIsEnumerable(0)})?function(H){return ft(H)=="String"?je.call(H,""):Object(H)}:Object,jt=function(H){if(H==null)throw TypeError("Can't call method on "+H);return H},Et=function(H){return Mt(jt(H))},re=function(H){return typeof H=="function"},qe=function(H){return typeof H=="object"?H!==null:re(H)},yt=function(H){return re(H)?H:void 0},Me=function(H,BA){return arguments.length<2?yt(cA[H]):cA[H]&&cA[H][BA]},Oe=Me("navigator","userAgent")||"",gt=cA.process,Fi=cA.Deno,To=gt&>.versions||Fi&&Fi.version,io=To&&To.v8;io?mA=(sA=io.split("."))[0]<4?1:sA[0]+sA[1]:Oe&&(!(sA=Oe.match(/Edge\/(\d+)/))||sA[1]>=74)&&(sA=Oe.match(/Chrome\/(\d+)/))&&(mA=sA[1]);var Eo=mA&&+mA,Vs=!!Object.getOwnPropertySymbols&&!TA(function(){var H=Symbol();return!String(H)||!(Object(H)instanceof Symbol)||!Symbol.sham&&Eo&&Eo<41}),ki=Vs&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ns=ki?function(H){return typeof H=="symbol"}:function(H){var BA=Me("Symbol");return re(BA)&&Object(H)instanceof BA},jo=function(H){try{return String(H)}catch{return"Object"}},Ao=function(H){if(re(H))return H;throw TypeError(jo(H)+" is not a function")},Zt=function(H,BA){var yA=H[BA];return yA==null?void 0:Ao(yA)},oo=function(H,BA){try{Object.defineProperty(cA,H,{value:BA,configurable:!0,writable:!0})}catch{cA[H]=BA}return BA},bi=cA["__core-js_shared__"]||oo("__core-js_shared__",{}),vs=lA(function(H){(H.exports=function(BA,yA){return bi[BA]||(bi[BA]=yA!==void 0?yA:{})})("versions",[]).push({version:"3.18.2",mode:"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})}),HA=function(H){return Object(jt(H))},ce={}.hasOwnProperty,Ve=Object.hasOwn||function(H,BA){return ce.call(HA(H),BA)},Ot=0,nt=Math.random(),It=function(H){return"Symbol("+String(H===void 0?"":H)+")_"+(++Ot+nt).toString(36)},ei=vs("wks"),ti=cA.Symbol,be=ki?ti:ti&&ti.withoutSetter||It,Ze=function(H){return Ve(ei,H)&&(Vs||typeof ei[H]=="string")||(Vs&&Ve(ti,H)?ei[H]=ti[H]:ei[H]=be("Symbol."+H)),ei[H]},wt=Ze("toPrimitive"),Nt=function(H,BA){if(!qe(H)||ns(H))return H;var yA,NA=Zt(H,wt);if(NA){if(yA=NA.call(H,BA),!qe(yA)||ns(yA))return yA;throw TypeError("Can't convert object to primitive value")}return function(zA,we){var le,Ne;if(re(le=zA.toString)&&!qe(Ne=le.call(zA))||re(le=zA.valueOf)&&!qe(Ne=le.call(zA)))return Ne;throw TypeError("Can't convert object to primitive value")}(H)},Oi=function(H){var BA=Nt(H,"string");return ns(BA)?BA:String(BA)},po=cA.document,No=qe(po)&&qe(po.createElement),so=function(H){return No?po.createElement(H):{}},Go=!WA&&!TA(function(){return Object.defineProperty(so("div"),"a",{get:function(){return 7}}).a!=7}),An=Object.getOwnPropertyDescriptor,rn={f:WA?An:function(H,BA){if(H=Et(H),BA=Oi(BA),Go)try{return An(H,BA)}catch{}if(Ve(H,BA))return Qe(!xe.f.call(H,BA),H[BA])}},Es=function(H){if(qe(H))return H;throw TypeError(String(H)+" is not an object")},an=Object.defineProperty,Do={f:WA?an:function(H,BA,yA){if(Es(H),BA=Oi(BA),Es(yA),Go)try{return an(H,BA,yA)}catch{}if("get"in yA||"set"in yA)throw TypeError("Accessors not supported");return"value"in yA&&(H[BA]=yA.value),H}},pA=WA?function(H,BA,yA){return Do.f(H,BA,Qe(1,yA))}:function(H,BA,yA){return H[BA]=yA,H},Jn=Function.toString;re(bi.inspectSource)||(bi.inspectSource=function(H){return Jn.call(H)});var Qr,ds,zr,Pi=bi.inspectSource,Rs=cA.WeakMap,or=re(Rs)&&/native code/.test(Pi(Rs)),en=vs("keys"),wn=function(H){return en[H]||(en[H]=It(H))},qt={},yg=cA.WeakMap;if(or||bi.state){var On=bi.state||(bi.state=new yg),Gn=On.get,Js=On.has,pr=On.set;Qr=function(H,BA){if(Js.call(On,H))throw new TypeError("Object already initialized");return BA.facade=H,pr.call(On,H,BA),BA},ds=function(H){return Gn.call(On,H)||{}},zr=function(H){return Js.call(On,H)}}else{var Pn=wn("state");qt[Pn]=!0,Qr=function(H,BA){if(Ve(H,Pn))throw new TypeError("Object already initialized");return BA.facade=H,pA(H,Pn,BA),BA},ds=function(H){return Ve(H,Pn)?H[Pn]:{}},zr=function(H){return Ve(H,Pn)}}var mr={set:Qr,get:ds,has:zr,enforce:function(H){return zr(H)?ds(H):Qr(H,{})},getterFor:function(H){return function(BA){var yA;if(!qe(BA)||(yA=ds(BA)).type!==H)throw TypeError("Incompatible receiver, "+H+" required");return yA}}},mo=Function.prototype,gn=WA&&Object.getOwnPropertyDescriptor,Sl=Ve(mo,"name"),cn={PROPER:Sl&&function(){}.name==="something",CONFIGURABLE:Sl&&(!WA||WA&&gn(mo,"name").configurable)},fr=lA(function(H){var BA=cn.CONFIGURABLE,yA=mr.get,NA=mr.enforce,zA=String(String).split("String");(H.exports=function(we,le,Ne,ge){var Ue,vt=!!ge&&!!ge.unsafe,Wt=!!ge&&!!ge.enumerable,ci=!!ge&&!!ge.noTargetGet,Dt=ge&&ge.name!==void 0?ge.name:le;re(Ne)&&(String(Dt).slice(0,7)==="Symbol("&&(Dt="["+String(Dt).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!Ve(Ne,"name")||BA&&Ne.name!==Dt)&&pA(Ne,"name",Dt),(Ue=NA(Ne)).source||(Ue.source=zA.join(typeof Dt=="string"?Dt:""))),we!==cA?(vt?!ci&&we[le]&&(Wt=!0):delete we[le],Wt?we[le]=Ne:pA(we,le,Ne)):Wt?we[le]=Ne:oo(le,Ne)})(Function.prototype,"toString",function(){return re(this)&&yA(this).source||Pi(this)})}),Ls=Math.ceil,Jc=Math.floor,ms=function(H){var BA=+H;return BA!=BA||BA===0?0:(BA>0?Jc:Ls)(BA)},as=Math.max,Ru=Math.min,Wa=Math.min,Cs=function(H){return H>0?Wa(ms(H),9007199254740991):0},sg=function(H){return Cs(H.length)},HI=function(H){return function(BA,yA,NA){var zA,we=Et(BA),le=sg(we),Ne=function(ge,Ue){var vt=ms(ge);return vt<0?as(vt+Ue,0):Ru(vt,Ue)}(NA,le);if(H&&yA!=yA){for(;le>Ne;)if((zA=we[Ne++])!=zA)return!0}else for(;le>Ne;Ne++)if((H||Ne in we)&&we[Ne]===yA)return H||Ne||0;return!H&&-1}},As={indexOf:HI(!1)},$i=As.indexOf,pc=function(H,BA){var yA,NA=Et(H),zA=0,we=[];for(yA in NA)!Ve(qt,yA)&&Ve(NA,yA)&&we.push(yA);for(;BA.length>zA;)Ve(NA,yA=BA[zA++])&&(~$i(we,yA)||we.push(yA));return we},ng=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Dg=ng.concat("length","prototype"),ua={f:Object.getOwnPropertyNames||function(H){return pc(H,Dg)}},bo={f:Object.getOwnPropertySymbols},Zr=Me("Reflect","ownKeys")||function(H){var BA=ua.f(Es(H)),yA=bo.f;return yA?BA.concat(yA(H)):BA},_o=function(H,BA){for(var yA=Zr(BA),NA=Do.f,zA=rn.f,we=0;we=51||!TA(function(){var BA=[];return(BA.constructor={})[Ii]=function(){return{foo:1}},BA[H](Boolean).foo!==1})},xt=Ze("isConcatSpreadable"),Ji=Eo>=51||!TA(function(){var H=[];return H[xt]=!1,H.concat()[0]!==H}),Ki=ct("concat"),qs=function(H){if(!qe(H))return!1;var BA=H[xt];return BA!==void 0?!!BA:Ea(H)};fs({target:"Array",proto:!0,forced:!Ji||!Ki},{concat:function(H){var BA,yA,NA,zA,we,le=HA(this),Ne=Yt(le,0),ge=0;for(BA=-1,NA=arguments.length;BA9007199254740991)throw TypeError("Maximum allowed index exceeded");for(yA=0;yA=9007199254740991)throw TypeError("Maximum allowed index exceeded");yn(Ne,ge++,we)}return Ne.length=ge,Ne}});var Mi,zo=Object.keys||function(H){return pc(H,ng)},Mg=WA?Object.defineProperties:function(H,BA){Es(H);for(var yA,NA=zo(BA),zA=NA.length,we=0;zA>we;)Do.f(H,yA=NA[we++],BA[yA]);return H},sr=Me("document","documentElement"),yr=wn("IE_PROTO"),xn=function(){},Ml=function(H){return" - + +
diff --git a/app/video_companion/src/App.vue b/app/video_companion/src/App.vue index 736b9c7c6..e70d6785f 100644 --- a/app/video_companion/src/App.vue +++ b/app/video_companion/src/App.vue @@ -3,6 +3,10 @@ import { TUICallKit } from '@trtc/calls-uikit-vue' import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue' import type { Ref } from 'vue' import { captureVideoStage } from './video-screenshot' +import ImAiPanel from './ImAiPanel.vue' +import { appendAiDraft, shouldClearSubmittedDraft } from './im-ai' +import type { ImAiAction, ImAiState } from './im-ai' +import { aiPanelBounds, clampAiPanelWidth, resizeAiPanelByKey } from './im-ai-layout' interface ChatMessage { id: string @@ -68,6 +72,11 @@ const props = defineProps<{ localRecordingState: Readonly> liveCaptions: Readonly> patientCase: Readonly> + contextKey: Readonly> + imAiState: Readonly> + onRequestImAi: (action: ImAiAction) => void + onRegenerateImAi: (action: ImAiAction) => void + onCancelImAi: () => void onSendText: (text: string) => Promise onSendAttachment: (file: File) => Promise onLoadMore: () => Promise @@ -79,6 +88,94 @@ const props = defineProps<{ }>() const draft = ref('') +let draftRevision = 0 +const composerInput = ref(null) +const aiToggle = ref(null) +const aiOpen = ref(false) +const aiMedia = window.matchMedia('(max-width: 980px)') +const aiDrawer = ref(aiMedia.matches) +const updateAiDrawer = (event: MediaQueryListEvent) => { aiDrawer.value = event.matches } +aiMedia.addEventListener('change', updateAiDrawer) +onBeforeUnmount(() => aiMedia.removeEventListener('change', updateAiDrawer)) +const aiViewportWidth = ref(window.innerWidth) +const aiWideWidth = ref(330) +const aiDrawerWidth = ref(360) +const aiResizeHandle = ref(null) +const aiResizing = ref(false) +const aiBounds = computed(() => aiPanelBounds(aiViewportWidth.value, aiDrawer.value)) +const aiPanelWidth = computed(() => clampAiPanelWidth( + aiDrawer.value ? aiDrawerWidth.value : aiWideWidth.value, aiViewportWidth.value, aiDrawer.value, +)) +let aiResizeDrag: { pointerId: number; startX: number; startWidth: number; drawer: boolean } | null = null + +function setAiPanelWidth(width: number): void { + const next = clampAiPanelWidth(width, aiViewportWidth.value, aiDrawer.value) + if (aiDrawer.value) aiDrawerWidth.value = next + else aiWideWidth.value = next +} + +function endAiResize(restore = false): void { + const drag = aiResizeDrag + aiResizeDrag = null + aiResizing.value = false + if (!drag) return + if (restore) { + if (drag.drawer) aiDrawerWidth.value = drag.startWidth + else aiWideWidth.value = drag.startWidth + } + if (aiResizeHandle.value?.hasPointerCapture(drag.pointerId)) { + aiResizeHandle.value.releasePointerCapture(drag.pointerId) + } +} + +function startAiResize(event: PointerEvent): void { + if (event.button !== 0 || !event.isPrimary || aiResizeDrag) return + event.preventDefault() + aiResizeHandle.value?.focus() + try { + aiResizeHandle.value?.setPointerCapture(event.pointerId) + } catch { return } + aiResizeDrag = { pointerId: event.pointerId, startX: event.clientX, startWidth: aiPanelWidth.value, drawer: aiDrawer.value } + aiResizing.value = true +} + +function moveAiResize(event: PointerEvent): void { + if (!aiResizeDrag || event.pointerId !== aiResizeDrag.pointerId) return + setAiPanelWidth(aiResizeDrag.startWidth + aiResizeDrag.startX - event.clientX) +} + +function onAiResizeKeydown(event: KeyboardEvent): void { + if (event.key === 'Escape' && aiResizeDrag) { + event.preventDefault() + event.stopPropagation() + endAiResize(true) + return + } + const width = resizeAiPanelByKey(event.key, aiPanelWidth.value, aiViewportWidth.value, aiDrawer.value, event.shiftKey) + if (width === null) return + event.preventDefault() + endAiResize() + setAiPanelWidth(width) +} + +const updateAiViewport = () => { + endAiResize() + aiViewportWidth.value = window.innerWidth +} +const releaseAiResize = () => endAiResize() +window.addEventListener('resize', updateAiViewport) +window.addEventListener('blur', releaseAiResize) +watch([aiDrawer, aiOpen], () => endAiResize()) +onBeforeUnmount(() => { + endAiResize() + window.removeEventListener('resize', updateAiViewport) + window.removeEventListener('blur', releaseAiResize) +}) +const aiDraftNotice = ref('') +watch(draft, () => { + draftRevision += 1 + if (!draft.value) aiDraftNotice.value = '' +}, { flush: 'sync' }) const actionBusy = ref(false) const localError = ref('') const messageList = ref(null) @@ -221,14 +318,57 @@ async function runAction(action: () => Promise): Promise { } async function sendText(): Promise { + if (!props.chatReady.value || actionBusy.value) return const content = draft.value.trim() if (!content) return + const submitted = { text: draft.value, contextKey: props.contextKey.value, revision: draftRevision } await runAction(async () => { await props.onSendText(content) - draft.value = '' + if (shouldClearSubmittedDraft( + { text: draft.value, contextKey: props.contextKey.value, revision: draftRevision }, submitted, + )) draft.value = '' }) } +function onComposerKeydown(event: KeyboardEvent): void { + if (event.key !== 'Enter' || event.shiftKey || event.ctrlKey || event.altKey || event.metaKey) return + if (event.isComposing || event.keyCode === 229) return + event.preventDefault() + void sendText() +} + +async function closeAi(): Promise { + aiOpen.value = false + await nextTick() + aiToggle.value?.focus() +} + +async function applyAiDraft(): Promise { + aiDraftNotice.value = '' + try { + draft.value = appendAiDraft(draft.value, props.imAiState.value, props.contextKey.value) + localError.value = '' + aiDraftNotice.value = '已填入草稿,请复核编辑后手动发送。' + aiOpen.value = false + await nextTick() + composerInput.value?.focus() + composerInput.value?.setSelectionRange(draft.value.length, draft.value.length) + } catch (error) { + localError.value = error instanceof Error ? error.message : '无法填入草稿,请重试。' + // Keep the draft intact and expose the composer feedback in compact windows. + aiOpen.value = false + await nextTick() + composerInput.value?.focus() + } +} + +watch(() => props.contextKey.value, () => { + draft.value = '' + localError.value = '' + aiDraftNotice.value = '' + aiOpen.value = false +}, { flush: 'sync' }) + async function selectAttachment(event: Event): Promise { const input = event.target as HTMLInputElement const file = input.files?.[0] @@ -284,8 +424,8 @@ watch(