diff --git a/admin/src/views/first_visit/conversion/index.vue b/admin/src/views/first_visit/conversion/index.vue index 60b127ced..b43d9d102 100644 --- a/admin/src/views/first_visit/conversion/index.vue +++ b/admin/src/views/first_visit/conversion/index.vue @@ -145,7 +145,7 @@

明细数据列表

-

展开部门可查看人员明细;挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/预约,接诊率=接诊诊单/加粉

+

展开部门可查看人员明细;加粉=区间有效加粉(按员工+客户去重,须会话同意,剔除已删客户);挂号=已支付且实收低于 10 元的订单,预约=有效预约记录;开口率=开口/加粉,挂号率=挂号/加粉,面诊率=面诊/预约,预约接诊率=接诊诊单/面诊,面诊接诊率=面诊/挂号,接诊率=接诊诊单/加粉

{{ dashboard.rows.length }} 个顶层节点
@@ -196,9 +196,12 @@ - + + + + @@ -327,7 +330,7 @@ const timeOptions = [ { label: '自定义', value: 'custom' } ] const metricCards: Array<{ key: string; label: string; type: MetricType; hint: string }> = [ - { key: 'add_fans_count', label: '加粉数', type: 'count', hint: '企微新增客户' }, + { key: 'add_fans_count', label: '加粉数', type: 'count', hint: '区间有效加粉:去重,须会话同意,剔除已删客户' }, { key: 'total_open_count', label: '开口数', type: 'count', hint: '来源于个人业绩录入' }, { key: 'interview_count', label: '面诊', type: 'count', hint: '已完成预约' }, { key: 'completed_order_count', label: '接诊诊单', type: 'count', hint: '业务订单,按创建人归属并过滤无效单' }, diff --git a/admin/src/views/first_visit/my_patients/components/ProgressPanel.vue b/admin/src/views/first_visit/my_patients/components/ProgressPanel.vue index 6810881a8..53e7be0f4 100644 --- a/admin/src/views/first_visit/my_patients/components/ProgressPanel.vue +++ b/admin/src/views/first_visit/my_patients/components/ProgressPanel.vue @@ -1,843 +1,1028 @@ - - - - - + + + + + diff --git a/app/README.md b/app/README.md index d56f95c4a..f7a65226c 100644 --- a/app/README.md +++ b/app/README.md @@ -22,7 +22,7 @@ Windows 打包机需预先安装 `uv` 与 Node.js 20+;脚本会自动处理项 ## 已实现范围 -- 账号密码登录、token 会话、记住账号(不保存密码)和退出登录。 +- 账号密码登录、token 会话、通过系统凭据管理器安全记住密码和退出登录。 - 登录后读取 `/adminapi/auth.admin/mySelf`,按 `permissions` 动态控制页面和操作按钮;`*` 超级权限兼容现有后台。 - 接诊台:今日待接诊/已过号、患者详情、医生备注、通知医助、完成接诊、发起视频面诊。 - 挂号列表:对齐管理端 `tcm/appointment/list`,支持状态 Tab、日期/确认/部门筛选、通话、完成、开方与取消挂号。 @@ -76,7 +76,7 @@ DOCTOR_VERIFY_SSL=true - 响应 envelope:`code=1` 成功、`0` 业务失败、`-1` 登录失效、`10` 需绑定企业微信。 - 权限与数据范围:完全以后端 `/auth.admin/mySelf` 返回为准。 -环境配置不会保存密码、TRTC SecretKey 或腾讯云长期凭据。登录 token 优先存入系统凭据库;无法使用时仅回退到用户配置目录中的受限文件。 +环境配置不会保存明文密码、TRTC SecretKey 或腾讯云长期凭据。登录密码优先存入系统凭据管理器;Windows 凭据后端不可用时仅保存当前 Windows 用户可解密的 DPAPI 密文。登录 token 优先存入系统凭据库,无法使用时仅回退到用户配置目录中的受限文件。 ## 视频伴随页 diff --git a/app/src/doctor_workstation/app.py b/app/src/doctor_workstation/app.py index 04aa2e3e9..939b4a5f5 100644 --- a/app/src/doctor_workstation/app.py +++ b/app/src/doctor_workstation/app.py @@ -9,7 +9,7 @@ import time from contextlib import suppress from typing import Any -from PySide6.QtCore import QObject, Qt, QTimer +from PySide6.QtCore import QLibraryInfo, QLocale, QObject, Qt, QTimer, QTranslator from PySide6.QtGui import QGuiApplication, QIcon from PySide6.QtWidgets import ( QApplication, @@ -43,7 +43,71 @@ from doctor_workstation.ui.widgets import ( from doctor_workstation.video import BackendMode, launch_video_call from doctor_workstation.video.window import WEBENGINE_AVAILABLE -LOGGER = logging.getLogger(__name__) +LOGGER = logging.getLogger(__name__) + + +class _ChineseQtTranslator(QTranslator): + """Guarantee Chinese labels for common Qt standard buttons. + + Qt's packaged ``qtbase_zh_CN`` catalog remains the primary source for + framework text. This small fallback also keeps release builds localized + when a packager omits the optional ``.qm`` files. + """ + + _BUTTON_TEXT = { + "OK": "确定", + "Open": "打开", + "Save": "保存", + "Save All": "全部保存", + "Cancel": "取消", + "Close": "关闭", + "Yes": "是", + "Yes to All": "全部确认", + "No": "否", + "No to All": "全部否定", + "Abort": "中止", + "Retry": "重试", + "Ignore": "忽略", + "Discard": "放弃", + "Help": "帮助", + "Apply": "应用", + "Reset": "重置", + "Restore Defaults": "恢复默认设置", + "Don't Save": "不保存", + } + + def translate( + self, + context: str, + source_text: str, + disambiguation: str | None = None, + n: int = -1, + ) -> str: + del context, disambiguation, n + return self._BUTTON_TEXT.get(source_text.replace("&", ""), "") + + +def _install_chinese_translations(application: QApplication) -> None: + """Install Simplified Chinese Qt catalogs once for the whole process.""" + + if getattr(application, "_doctor_workstation_chinese_translators", None): + return + + QLocale.setDefault(QLocale("zh_CN")) + translators: list[QTranslator] = [] + translations_path = QLibraryInfo.path( + QLibraryInfo.LibraryPath.TranslationsPath + ) + for catalog in ("qt_zh_CN", "qtbase_zh_CN"): + translator = QTranslator(application) + if translator.load(catalog, translations_path): + application.installTranslator(translator) + translators.append(translator) + + fallback = _ChineseQtTranslator(application) + application.installTranslator(fallback) + translators.append(fallback) + application._doctor_workstation_chinese_translators = translators # type: ignore[attr-defined] class _UnconfiguredRepository: @@ -200,11 +264,12 @@ class ApplicationController(QObject): def _show_login(self) -> None: if self.login_window is None: - self.login_window = LoginWindow( - self._base_repository(), - self.config, - self.demo_repository, - ) + self.login_window = LoginWindow( + self._base_repository(), + self.config, + self.demo_repository, + credential_store=self.token_store, + ) self.login_window.login_succeeded.connect(self._on_login_succeeded) self.login_window.config_changed.connect(self._on_config_changed) self.login_window.demo_mode_changed.connect(self._on_demo_mode_changed) @@ -212,8 +277,9 @@ class ApplicationController(QObject): else: self.login_window.repository = self._base_repository() self.login_window.config = self.config - if not self.login_window.demo_check.isChecked(): - self.login_window.active_repository = self._base_repository() + if not self.login_window.demo_check.isChecked(): + self.login_window.active_repository = self._base_repository() + self.login_window.restore_remembered_credentials() self.login_window.show() self.login_window.raise_() self.login_window.activateWindow() @@ -498,20 +564,40 @@ class ApplicationController(QObject): if parent is None or self.current_repository is None: return patient_id = payload.get("patient_id") - diagnosis_id = payload.get("diagnosis_id") - patient_name = str(payload.get("patient_name") or "患者") + diagnosis_id = payload.get("diagnosis_id") + patient_name = str(payload.get("patient_name") or "患者") + open_im = str(payload.get("mode") or "video").lower() == "im" if patient_id in (None, "") or diagnosis_id in (None, ""): show_toast(parent, "患者或诊单信息不完整,无法发起视频。", "danger", 4200) return - call_key = str(diagnosis_id) - if ( - call_key in self.video_pending - or call_key in self.video_calls - or call_key in self.demo_video_dialogs - ): - show_toast(parent, "该问诊的视频正在准备或通话中。", "info", 3600) - return + call_key = str(diagnosis_id) + existing_call = self.video_calls.get(call_key) + if open_im and existing_call is not None and getattr(existing_call, "open_im", False): + qt_window = getattr(existing_call, "qt_window", None) + if qt_window is not None: + qt_window.show() + qt_window.raise_() + qt_window.activateWindow() + show_toast(parent, "该患者的 IM 会话已经打开。", "info", 3200) + return + if ( + call_key in self.video_pending + or existing_call is not None + or call_key in self.demo_video_dialogs + ): + show_toast(parent, "该问诊的视频正在准备或通话中。", "info", 3600) + return + + closed_previous_im = False + if open_im: + for key, call in tuple(self.video_calls.items()): + if key == call_key or not getattr(call, "open_im", False): + continue + closed_previous_im = True + self.video_calls.pop(key, None) + with suppress(Exception): + call.close() if self.current_demo_mode: dialog = DemoVideoDialog(patient_name, parent) @@ -525,7 +611,11 @@ class ApplicationController(QObject): dialog.show() return - show_toast(parent, "正在获取安全通话凭证…", "info") + show_toast( + parent, + "正在打开患者 IM 会话…" if open_im else "正在获取安全通话凭证…", + "info", + ) repository = self.current_repository marker = object() self.video_pending[call_key] = marker @@ -536,23 +626,35 @@ class ApplicationController(QObject): diagnosis_id=int(diagnosis_id), ) - run_async( - get_ticket, - on_success=lambda ticket: self._launch_video( - ticket, - diagnosis_id=diagnosis_id, - patient_id=patient_id, - repository=repository, - call_key=call_key, - marker=marker, - ), - on_error=lambda error: self._video_ticket_error( - call_key, - marker, - parent, - error, - ), - ) + def request_ticket() -> None: + if self.video_pending.get(call_key) is not marker: + return + run_async( + get_ticket, + on_success=lambda ticket: self._launch_video( + ticket, + diagnosis_id=diagnosis_id, + patient_id=patient_id, + repository=repository, + call_key=call_key, + marker=marker, + open_im=open_im, + patient_name=patient_name, + ), + on_error=lambda error: self._video_ticket_error( + call_key, + marker, + parent, + error, + ), + ) + + # Tencent IM may take a brief moment to release the previous browser + # connection. The admin version also has only one ChatDialog instance. + if closed_previous_im: + QTimer.singleShot(400, request_ticket) + else: + request_ticket() def _video_ticket_error( self, @@ -579,9 +681,11 @@ class ApplicationController(QObject): diagnosis_id: Any, patient_id: Any, repository: Any, - call_key: str, - marker: object, - ) -> None: + call_key: str, + marker: object, + open_im: bool = False, + patient_name: str = "患者", + ) -> None: if self.video_pending.get(call_key) is not marker: return self.video_pending.pop(call_key, None) @@ -604,9 +708,11 @@ class ApplicationController(QObject): patient_id=patient_id, backend_mode=mode, local_dist=video_dist_path(), - remote_url=self.config.video_web_url or None, - logger=logging.getLogger("doctor_workstation.video"), - ) + remote_url=self.config.video_web_url or None, + logger=logging.getLogger("doctor_workstation.video"), + open_im=open_im, + patient_name=patient_name, + ) except Exception as error: LOGGER.exception("video call could not be launched") show_toast( @@ -682,7 +788,8 @@ def _create_application(argv: list[str]) -> QApplication: QGuiApplication.setHighDpiScaleFactorRoundingPolicy( Qt.HighDpiScaleFactorRoundingPolicy.PassThrough ) - application = QApplication(argv) + application = QApplication(argv) + _install_chinese_translations(application) application.setApplicationName("甄养堂医生工作站") application.setApplicationDisplayName("甄养堂医生工作站") application.setOrganizationName("ZhenYangTang") diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py index bc5ebe12c..c3b8b3522 100644 --- a/app/src/doctor_workstation/services/mock_repository.py +++ b/app/src/doctor_workstation/services/mock_repository.py @@ -593,6 +593,28 @@ class DemoDoctorRepository: safe_name = source.name.replace("\\", "_").replace("/", "_") return f"/demo/uploads/{kind}/{material_id}-{safe_name}" + def upload_material_bytes( + self, + content: bytes, + filename: str, + material_type: Literal["image", "video", "file"], + cid: int = 0, + ) -> str: + """Return a synthetic server URI for an in-memory demo capture.""" + + if cid < 0: + raise ValueError("cid must be non-negative") + if not content: + raise ValueError("material content must not be empty") + safe_name = Path(filename).name.strip().replace("\\", "_").replace("/", "_") + if not safe_name: + raise ValueError("filename is required") + kind = _material_kind(material_type) + with self._lock: + material_id = self._next_material_id + self._next_material_id += 1 + return f"/demo/uploads/{kind}/{material_id}-{safe_name}" + def add_doctor_note( self, diagnosis_id: int, diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index 0be9c1fbd..97d34f9de 100644 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -8,6 +8,7 @@ import time from collections.abc import Mapping from contextlib import suppress from datetime import date +from io import BytesIO from os import PathLike from pathlib import Path from typing import Any, Final, Literal, Protocol @@ -109,6 +110,15 @@ class DoctorRepository(Protocol): ) -> str: """Upload one local note material and return its server URI.""" + def upload_material_bytes( + self, + content: bytes, + filename: str, + material_type: Literal["image", "video", "file"], + cid: int = 0, + ) -> str: + """Upload an in-memory capture and return its server URI.""" + def get_prescription_template(self, template_id: int) -> PrescriptionTemplate: """Return one prescription-library record.""" @@ -960,6 +970,34 @@ class RemoteDoctorRepository: ) return _normalise_material_reference(payload, endpoint) + def upload_material_bytes( + self, + content: bytes, + filename: str, + material_type: Literal["image", "video", "file"], + cid: int = 0, + ) -> str: + """Upload a trusted in-memory capture without a local plaintext file.""" + + if cid < 0: + raise ValueError("cid must be non-negative") + if not content: + raise ValueError("material content must not be empty") + if len(content) > 10 * 1024 * 1024: + raise ValueError("material content exceeds 10 MB") + safe_name = Path(filename).name.strip() + if not safe_name or safe_name in {".", ".."}: + raise ValueError("filename is required") + kind = _material_kind(material_type) + mime_type = mimetypes.guess_type(safe_name)[0] or "application/octet-stream" + endpoint = f"upload/{kind}" + payload = self.client.post_multipart( + endpoint, + files={"file": (safe_name, BytesIO(content), mime_type)}, + data={"cid": str(cid)}, + ) + return _normalise_material_reference(payload, endpoint) + def notify_assistant(self, appointment_id: int) -> Any: """Ask the server to notify the assigned medical assistant.""" diff --git a/app/src/doctor_workstation/services/token_store.py b/app/src/doctor_workstation/services/token_store.py index 3d20663f9..3c3a52e37 100644 --- a/app/src/doctor_workstation/services/token_store.py +++ b/app/src/doctor_workstation/services/token_store.py @@ -2,6 +2,9 @@ from __future__ import annotations +import base64 +import ctypes +import hashlib import json import os import stat @@ -28,12 +31,13 @@ _AUTO_KEYRING = object() class TokenStore: - """Store access tokens, but never user passwords. + """Store tokens and optional login passwords with OS-protected storage. If a working ``keyring`` backend is importable, the token is stored there and the JSON file contains at most the remembered account name and the - non-secret API scope. Otherwise the JSON file is atomically written with - owner-only ``0600`` permissions. + non-secret API scope. Login passwords use the keyring first; on Windows, + an unavailable keyring falls back to a DPAPI-encrypted blob that only the + current Windows user can decrypt. Plaintext passwords are never written. """ def __init__( @@ -103,7 +107,7 @@ class TokenStore: """Persist a token plus optional account and API-scope metadata. Passing an empty ``account`` explicitly forgets a previously remembered - account. Passwords are never accepted or persisted. + account and its keyring password. """ cleaned = token.strip() @@ -115,6 +119,17 @@ class TokenStore: data = self._read_file() if account is not None: account_value = account.strip() + previous_account = str(data.get("account") or "").strip() + previous_scope = self._normalise_scope(data.get("scope")) + next_scope = ( + self._normalise_scope(scope) if scope is not None else previous_scope + ) + if previous_account and ( + previous_account != account_value + or (account_value and previous_scope != next_scope) + ): + self.clear_password(account=previous_account, scope=previous_scope) + data.pop("credential", None) if account_value: data["account"] = account_value else: @@ -137,7 +152,7 @@ class TokenStore: self._write_file(data) def clear_token(self) -> None: - """Delete the token while retaining an explicitly remembered account.""" + """Delete the token while retaining remembered login credentials.""" if self._uses_keyring and self._keyring is not None: try: @@ -146,11 +161,12 @@ class TokenStore: self._uses_keyring = False data = self._read_file() data.pop("token", None) - data.pop("scope", None) + if not data.get("account"): + data.pop("scope", None) self._write_file(data) def load_account(self) -> str | None: - """Load the remembered login account; no password is ever stored.""" + """Load the non-secret remembered login account.""" value = self._read_file().get("account") return str(value) if isinstance(value, str) and value else None @@ -167,13 +183,104 @@ class TokenStore: self._write_file(data) def clear_account(self) -> None: - """Forget the remembered account without changing the stored token.""" + """Forget the remembered account and its keyring password.""" + data = self._read_file() + self.clear_password( + account=str(data.get("account") or ""), + scope=str(data.get("scope") or ""), + ) self.save_account("") + def load_password(self, *, account: str, scope: str) -> str | None: + """Load one scoped password from keyring or a Windows DPAPI blob.""" + + target = self._password_target(account, scope) + if not target: + return None + if self._uses_keyring and self._keyring is not None: + try: + value = self._keyring.get_password(self.service_name, target) + if value: + return str(value) + except Exception: + self._uses_keyring = False + data = self._read_file() + if self._password_target( + str(data.get("account") or ""), + str(data.get("scope") or ""), + ) != target: + return None + credential = data.get("credential") + if not isinstance(credential, str) or not credential: + return None + return self._unprotect_password(credential, target) + + def save_password(self, password: str, *, account: str, scope: str) -> bool: + """Save one password using keyring or Windows user-scoped DPAPI.""" + + target = self._password_target(account, scope) + if not target or not password: + return False + data = self._read_file() + previous_target = self._password_target( + str(data.get("account") or ""), + str(data.get("scope") or ""), + ) + if ( + previous_target + and previous_target != target + and self._uses_keyring + and self._keyring is not None + ): + with suppress(Exception): + self._keyring.delete_password(self.service_name, previous_target) + if self._uses_keyring and self._keyring is not None: + try: + self._keyring.set_password(self.service_name, target, password) + except Exception: + self._uses_keyring = False + else: + data["account"] = account.strip() + data["scope"] = self._normalise_scope(scope) + data.pop("credential", None) + self._write_file(data) + return True + protected = self._protect_password(password, target) + if not protected: + return False + data["account"] = account.strip() + data["scope"] = self._normalise_scope(scope) + data["credential"] = protected + self._write_file(data) + return True + + def clear_password(self, *, account: str, scope: str) -> None: + """Delete one scoped login password from the OS keyring.""" + + target = self._password_target(account, scope) + if not target: + return + if self._uses_keyring and self._keyring is not None: + with suppress(Exception): + self._keyring.delete_password(self.service_name, target) + data = self._read_file() + stored_target = self._password_target( + str(data.get("account") or ""), + str(data.get("scope") or ""), + ) + if stored_target == target and "credential" in data: + data.pop("credential", None) + self._write_file(data) + def clear(self) -> None: """Delete both token and remembered account information.""" + data = self._read_file() + self.clear_password( + account=str(data.get("account") or ""), + scope=str(data.get("scope") or ""), + ) if self._uses_keyring and self._keyring is not None: try: self._keyring.delete_password(self.service_name, self.token_name) @@ -225,6 +332,120 @@ class TokenStore: return str(value or "").strip().rstrip("/") + def _password_target(self, account: str, scope: str) -> str: + """Return an opaque keyring name isolated by account and API server.""" + + clean_account = account.strip().casefold() + clean_scope = self._normalise_scope(scope).casefold() + if not clean_account or not clean_scope: + return "" + digest = hashlib.sha256(f"{clean_scope}\n{clean_account}".encode()).hexdigest() + return f"login-password:{digest}" + + def _protect_password(self, password: str, target: str) -> str | None: + """Return a Windows DPAPI blob, or ``None`` on unsupported systems.""" + + if os.name != "nt": + return None + try: + encrypted = self._crypt_protect( + password.encode("utf-8"), + self._credential_entropy(target), + ) + except (OSError, ValueError): + return None + return base64.b64encode(encrypted).decode("ascii") + + def _unprotect_password(self, protected: str, target: str) -> str | None: + """Decrypt a Windows DPAPI blob for this account/server target.""" + + if os.name != "nt": + return None + try: + encrypted = base64.b64decode(protected, validate=True) + plaintext = self._crypt_unprotect( + encrypted, + self._credential_entropy(target), + ) + return plaintext.decode("utf-8") + except (OSError, UnicodeError, ValueError): + return None + + def _credential_entropy(self, target: str) -> bytes: + return hashlib.sha256(f"{self.service_name}\n{target}".encode()).digest() + + @staticmethod + def _crypt_protect(data: bytes, entropy: bytes) -> bytes: + from ctypes import wintypes + + class DataBlob(ctypes.Structure): + _fields_ = [ + ("size", wintypes.DWORD), + ("data", ctypes.POINTER(ctypes.c_ubyte)), + ] + + def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]: + buffer = ctypes.create_string_buffer(value) + blob = DataBlob( + len(value), + ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)), + ) + return blob, buffer + + source, _source_buffer = make_blob(data) + optional_entropy, _entropy_buffer = make_blob(entropy) + destination = DataBlob() + if not ctypes.windll.crypt32.CryptProtectData( + ctypes.byref(source), + None, + ctypes.byref(optional_entropy), + None, + None, + 0x01, + ctypes.byref(destination), + ): + raise ctypes.WinError() + try: + return ctypes.string_at(destination.data, destination.size) + finally: + ctypes.windll.kernel32.LocalFree(destination.data) + + @staticmethod + def _crypt_unprotect(data: bytes, entropy: bytes) -> bytes: + from ctypes import wintypes + + class DataBlob(ctypes.Structure): + _fields_ = [ + ("size", wintypes.DWORD), + ("data", ctypes.POINTER(ctypes.c_ubyte)), + ] + + def make_blob(value: bytes) -> tuple[DataBlob, ctypes.Array[Any]]: + buffer = ctypes.create_string_buffer(value) + blob = DataBlob( + len(value), + ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)), + ) + return blob, buffer + + source, _source_buffer = make_blob(data) + optional_entropy, _entropy_buffer = make_blob(entropy) + destination = DataBlob() + if not ctypes.windll.crypt32.CryptUnprotectData( + ctypes.byref(source), + None, + ctypes.byref(optional_entropy), + None, + None, + 0x01, + ctypes.byref(destination), + ): + raise ctypes.WinError() + try: + return ctypes.string_at(destination.data, destination.size) + finally: + ctypes.windll.kernel32.LocalFree(destination.data) + def _read_file(self) -> dict[str, Any]: try: content = self.path.read_text(encoding="utf-8") @@ -234,10 +455,18 @@ class TokenStore: if not isinstance(value, dict): return {} # Explicit allow-list guarantees accidental password-like fields are ignored. - return {key: value[key] for key in ("token", "account", "scope") if key in value} + return { + key: value[key] + for key in ("token", "account", "scope", "credential") + if key in value + } def _write_file(self, data: dict[str, Any]) -> None: - safe = {key: data[key] for key in ("token", "account", "scope") if data.get(key)} + safe = { + key: data[key] + for key in ("token", "account", "scope", "credential") + if data.get(key) + } if not safe: with suppress(OSError): self.path.unlink(missing_ok=True) diff --git a/app/src/doctor_workstation/ui/login.py b/app/src/doctor_workstation/ui/login.py index aaaad27e0..8b557dca5 100644 --- a/app/src/doctor_workstation/ui/login.py +++ b/app/src/doctor_workstation/ui/login.py @@ -2,6 +2,7 @@ from __future__ import annotations +from contextlib import suppress from typing import Any from PySide6.QtCore import QPoint, QSettings, Qt, QTimer, Signal @@ -70,8 +71,9 @@ class LoginWindow(QMainWindow): ``login_succeeded`` emits a dictionary containing ``user``, ``session``, ``repository`` and ``demo_mode``. Keeping the selected repository in the payload lets the composition root construct the shell without guessing. - ``remember_account`` is captured before the worker starts and is forwarded - to the repository so every account metadata store follows the same choice. + The remember-password choice is captured before the worker starts. The + repository receives the corresponding account-metadata flag, while this + window stores the password only after authentication succeeds. """ login_succeeded = Signal(object) @@ -87,6 +89,7 @@ class LoginWindow(QMainWindow): config: Any | None = None, demo_repository: Any | None = None, settings: QSettings | None = None, + credential_store: Any | None = None, parent: QWidget | None = None, ) -> None: super().__init__(parent) @@ -96,9 +99,12 @@ class LoginWindow(QMainWindow): demo_repository = getattr(config, "demo_repository", None) self.demo_repository = demo_repository self.settings = settings or QSettings("ZhenYangTang", "DoctorWorkstation") + self.credential_store = credential_store self.active_repository = repository self.authenticated_user: Any = None self._loading = False + self._restored_account = "" + self._restored_scope = "" self.setWindowTitle("甄养堂 · 医生工作站") self.setMinimumSize(860, 590) @@ -214,7 +220,7 @@ class LoginWindow(QMainWindow): layout.addLayout(brand_row) layout.addStretch(2) - eyebrow = QLabel("DOCTOR WORKSTATION") + eyebrow = QLabel("医生工作站") eyebrow.setStyleSheet( "color:#4F63D9; font-size:11px; font-weight:700; letter-spacing:1px;" ) @@ -300,8 +306,8 @@ class LoginWindow(QMainWindow): card_layout.addLayout(password_row) choices = QHBoxLayout() - self.remember_check = _VisibleCheckBox("记住账号") - self.remember_check.setToolTip("仅保存账号,不保存密码") + self.remember_check = _VisibleCheckBox("记住密码") + self.remember_check.setToolTip("密码使用系统安全凭据或 Windows DPAPI 加密,不保存明文") choices.addWidget(self.remember_check) choices.addStretch(1) self.demo_check = _VisibleCheckBox("演示模式") @@ -394,8 +400,6 @@ class LoginWindow(QMainWindow): def _restore_settings(self) -> None: configured_account = getattr(self.config, "remembered_account", "") remembered = str(self.settings.value("auth/remembered_account", configured_account) or "") - self.account_edit.setText(remembered) - self.remember_check.setChecked(bool(remembered)) configured_url = getattr(self.config, "base_url", "") or getattr( self.config, "api_base_url", "" ) @@ -418,11 +422,49 @@ class LoginWindow(QMainWindow): self.allow_self_signed_check.setChecked(not verify_ssl) if self.demo_repository is not None and bool(getattr(self.config, "demo_mode", False)): self.demo_check.setChecked(True) + self.account_edit.setText(remembered) + self.restore_remembered_credentials() if remembered: self.password_edit.setFocus() else: self.account_edit.setFocus() + def _credential_scope(self) -> str: + if hasattr(self, "server_url_edit"): + scope = self.server_url_edit.text().strip() + if scope: + return scope.rstrip("/") + return str( + getattr(self.config, "base_url", "") + or getattr(self.config, "api_base_url", "") + or "" + ).strip().rstrip("/") + + def restore_remembered_credentials(self) -> None: + """Restore a password from the OS keyring without touching config files.""" + + configured_account = getattr(self.config, "remembered_account", "") + account = str( + self.settings.value("auth/remembered_account", configured_account) or "" + ).strip() + scope = self._credential_scope() + password = "" + should_restore = _setting_bool( + self.settings.value("auth/remember_password", False), + False, + ) + loader = getattr(self.credential_store, "load_password", None) + if should_restore and account and scope and callable(loader): + try: + password = str(loader(account=account, scope=scope) or "") + except Exception: + password = "" + self.account_edit.setText(account) + self.password_edit.setText(password) + self.remember_check.setChecked(bool(password)) + self._restored_account = account if password else "" + self._restored_scope = scope if password else "" + def _toggle_password(self, visible: bool) -> None: self.password_edit.setEchoMode( QLineEdit.EchoMode.Normal if visible else QLineEdit.EchoMode.Password @@ -557,6 +599,7 @@ class LoginWindow(QMainWindow): payload, account, remember_account, + password, ), on_error=self._on_login_error, on_finished=lambda: self._set_loading(False), @@ -604,15 +647,39 @@ class LoginWindow(QMainWindow): payload: dict[str, Any], account: str, remember_account: bool | None = None, + password: str | None = None, ) -> None: if remember_account is None: remember_account = self.remember_check.isChecked() + scope = self._credential_scope() + is_demo = bool(payload.get("demo_mode")) + password_saved = False + clearer = getattr(self.credential_store, "clear_password", None) + if callable(clearer) and self._restored_account and ( + not remember_account + or self._restored_account != account + or self._restored_scope != scope + ): + with suppress(Exception): + clearer(account=self._restored_account, scope=self._restored_scope) if remember_account: self.settings.setValue("auth/remembered_account", account) + saver = getattr(self.credential_store, "save_password", None) + if not is_demo and password and scope and callable(saver): + try: + password_saved = bool(saver(password, account=account, scope=scope)) + except Exception: + password_saved = False else: self.settings.remove("auth/remembered_account") + if callable(clearer): + with suppress(Exception): + clearer(account=account, scope=scope) + self.settings.setValue("auth/remember_password", password_saved) self.settings.sync() self._emit_config_update(remembered_account=account if remember_account else "") + self._restored_account = account if password_saved else "" + self._restored_scope = scope if password_saved else "" self.password_edit.clear() self.authenticated_user = payload.get("user") self.login_succeeded.emit(payload) diff --git a/app/src/doctor_workstation/ui/pages/appointments.py b/app/src/doctor_workstation/ui/pages/appointments.py index 8f5e443b7..55e3879ea 100644 --- a/app/src/doctor_workstation/ui/pages/appointments.py +++ b/app/src/doctor_workstation/ui/pages/appointments.py @@ -843,6 +843,7 @@ class AppointmentsPage(QWidget): "patient_id": patient_id, "diagnosis_id": diagnosis_id, "patient_name": first_value(row, "patient_name", default="患者"), + "mode": "im", "record": row, } ) diff --git a/app/src/doctor_workstation/ui/pages/reception.py b/app/src/doctor_workstation/ui/pages/reception.py index 8709b8252..4b09efc3d 100644 --- a/app/src/doctor_workstation/ui/pages/reception.py +++ b/app/src/doctor_workstation/ui/pages/reception.py @@ -8,9 +8,10 @@ from datetime import date, timedelta from pathlib import Path from typing import Any -from PySide6.QtCore import Qt, QTimer, Signal -from PySide6.QtGui import QTextCursor +from PySide6.QtCore import Qt, QTimer, QUrl, Signal +from PySide6.QtGui import QDesktopServices, QPixmap, QTextCursor from PySide6.QtWidgets import ( + QDialog, QFileDialog, QFrame, QGridLayout, @@ -22,6 +23,7 @@ from PySide6.QtWidgets import ( QMessageBox, QPushButton, QScrollArea, + QSizePolicy, QSplitter, QStackedWidget, QTabBar, @@ -118,6 +120,13 @@ def _attachment_name(value: object) -> str: return name or text +def _is_image_attachment(value: object) -> bool: + """Return whether a server attachment can be previewed as an image.""" + + path = str(value or "").split("?", 1)[0].split("#", 1)[0].lower() + return path.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp")) + + def _is_local_material_reference(value: str) -> bool: """Reject local filesystem references before a note JSON is constructed.""" @@ -139,12 +148,14 @@ class QueueRow(QWidget): layout.setContentsMargins(12, 9, 12, 9) layout.setSpacing(5) top = QHBoxLayout() + top.setSpacing(8) name = QLabel( display_text(first_value(record, "patient_name", "name", default="未命名患者")) ) name.setStyleSheet("font-size:14px; font-weight:700; color:#172033;") - top.addWidget(name) - top.addStretch(1) + name.setMinimumWidth(0) + name.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) + top.addWidget(name, 1) status_number = _as_int(first_value(record, "status", default=1), 1) or 1 badge = StatusBadge( display_text( @@ -157,7 +168,12 @@ class QueueRow(QWidget): ), STATUS_KIND.get(status_number, "neutral"), ) - top.addWidget(badge) + badge.setMinimumWidth(max(54, badge.sizeHint().width())) + top.addWidget( + badge, + 0, + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignTop, + ) layout.addLayout(top) time = first_value( record, "appointment_time_text", "appointment_time", "time", default="时间待确认" @@ -168,6 +184,10 @@ class QueueRow(QWidget): f"{display_text(first_value(record, 'age'))}岁" ) meta.setProperty("role", "muted") + # Long timestamps must not dictate the minimum width of the whole + # queue row and push the status badge underneath the viewport edge. + meta.setMinimumWidth(0) + meta.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Preferred) layout.addWidget(meta) assistant = first_value(record, "assistant_name", default=None) if assistant: @@ -211,6 +231,7 @@ class ReceptionPage(QWidget): self._pending_tongue_images: list[str] = [] self._pending_report_files: list[str] = [] self._note_busy = False + self._attachment_preview_generation = 0 self._can_complete = has_permission(self.permissions, "doctor.appointment/complete") self._can_note = has_permission(self.permissions, "doctor.appointment/addDoctorNote") @@ -335,7 +356,8 @@ class ReceptionPage(QWidget): self.notify_button = QPushButton("通知医助") self.notify_button.clicked.connect(self._notify_assistant) action_row.addWidget(self.notify_button) - self.video_button = QPushButton("发起视频") + self.video_button = QPushButton("IM 问诊") + self.video_button.setToolTip("打开患者 IM,可发送消息并从会话中发起视频") self.video_button.setProperty("variant", "secondary") self.video_button.clicked.connect(self._request_video) action_row.addWidget(self.video_button) @@ -1245,13 +1267,25 @@ class ReceptionPage(QWidget): ("report_files", "检查报告"), ): for path in _sequence(first_value(note, image_type, default=[])): + path_text = str(path).strip() attachment = QWidget() attachment_layout = QHBoxLayout(attachment) attachment_layout.setContentsMargins(0, 0, 0, 0) - label = QLabel(f"{caption}:{_attachment_name(path)}") - label.setToolTip(str(path)) + label = QLabel(f"{caption}:{_attachment_name(path_text)}") + label.setToolTip(path_text) label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) attachment_layout.addWidget(label, 1) + preview_button = QPushButton( + "预览" if _is_image_attachment(path_text) else "打开" + ) + preview_button.setProperty("variant", "secondary") + preview_button.setEnabled(bool(path_text)) + preview_button.clicked.connect( + lambda _checked=False, current_path=path_text, button=preview_button: ( + self._preview_note_attachment(current_path, button) + ) + ) + attachment_layout.addWidget(preview_button) if self._can_note and note_id is not None: delete_button = QPushButton("删除") delete_button.setProperty("variant", "secondary") @@ -1266,6 +1300,97 @@ class ReceptionPage(QWidget): layout.addWidget(attachment) self.notes_layout.addWidget(card) + def _preview_note_attachment(self, path: str, button: QPushButton) -> None: + """Preview note images in-app and open non-image reports safely.""" + + target = str(path or "").strip() + if not target: + return + if not _is_image_attachment(target): + url = QUrl(target) + if ( + not url.isValid() + or url.scheme().lower() not in {"https", "http"} + or not url.host() + ): + show_toast(self, "附件地址无效,无法打开。", "warning", 4200) + return + if not QDesktopServices.openUrl(url): + show_toast(self, "系统未能打开该附件。", "danger", 4200) + return + + download = getattr(self.repository, "download_public_image", None) + if not callable(download): + show_toast(self, "当前数据源不支持图片预览。", "warning", 4200) + return + self._attachment_preview_generation += 1 + generation = self._attachment_preview_generation + button.setEnabled(False) + button.setText("加载中…") + run_async( + lambda: invoke(self.repository, "download_public_image", url=target), + on_success=lambda payload: self._show_note_image_preview( + target, payload, button, generation + ), + on_error=lambda error: self._note_image_preview_failed( + error, button, generation + ), + ) + + def _show_note_image_preview( + self, + path: str, + payload: Any, + button: QPushButton, + generation: int, + ) -> None: + if generation != self._attachment_preview_generation: + return + button.setEnabled(True) + button.setText("预览") + content = bytes(payload or b"") + pixmap = QPixmap() + if not content or len(content) > 10 * 1024 * 1024 or not pixmap.loadFromData(content): + show_toast(self, "服务器返回的图片无法预览。", "danger", 4600) + return + dialog = QDialog(self) + dialog.setWindowTitle(f"预览 · {_attachment_name(path)}") + dialog.setModal(True) + dialog.resize(920, 680) + layout = QVBoxLayout(dialog) + layout.setContentsMargins(14, 14, 14, 14) + scroll = QScrollArea(dialog) + scroll.setWidgetResizable(True) + image = QLabel() + image.setAlignment(Qt.AlignmentFlag.AlignCenter) + image.setPixmap( + pixmap.scaled( + 880, + 620, + Qt.AspectRatioMode.KeepAspectRatio, + Qt.TransformationMode.SmoothTransformation, + ) + ) + scroll.setWidget(image) + layout.addWidget(scroll, 1) + close_button = QPushButton("关闭") + close_button.setProperty("variant", "primary") + close_button.clicked.connect(dialog.accept) + layout.addWidget(close_button, 0, Qt.AlignmentFlag.AlignRight) + dialog.exec() + + def _note_image_preview_failed( + self, + error: Exception, + button: QPushButton, + generation: int, + ) -> None: + if generation != self._attachment_preview_generation: + return + button.setEnabled(True) + button.setText("预览") + show_toast(self, f"图片预览失败:{friendly_error(error)}", "danger", 5200) + def _reset_detail_content(self, seed: Any = None) -> None: self.patient_name_label.setText( display_text(first_value(seed, "patient_name", "name", default="—")) @@ -1753,6 +1878,7 @@ class ReceptionPage(QWidget): "patient_name", default=first_value(diagnosis, "patient_name", default="患者"), ), + "mode": "im", "record": self._selected_record, } self.video_requested.emit(payload) diff --git a/app/src/doctor_workstation/ui/widgets.py b/app/src/doctor_workstation/ui/widgets.py index 25fddc2ad..fe55d1553 100644 --- a/app/src/doctor_workstation/ui/widgets.py +++ b/app/src/doctor_workstation/ui/widgets.py @@ -25,7 +25,13 @@ from PySide6.QtWidgets import ( QWidget, ) -from doctor_workstation.core.errors import AuthenticationExpiredError +from doctor_workstation.core.errors import ( + ApiHttpError, + ApiProtocolError, + ApiTimeoutError, + ApiTransportError, + AuthenticationExpiredError, +) AuthenticationExpiredHandler = Callable[[AuthenticationExpiredError], bool] _AUTHENTICATION_EXPIRED_HANDLER: AuthenticationExpiredHandler | None = None @@ -331,7 +337,45 @@ def friendly_error(error: Any) -> str: "服务器证书不受系统信任。若这是可信内网的自签名服务器,请展开“服务器设置”," "勾选“信任自签名证书(仅内网调试)”后重新登录,设置会自动应用。" ) - return text or "操作未完成,请稍后重试。" + if isinstance(error, AuthenticationExpiredError): + return "登录状态已失效,请重新登录。" + if isinstance(error, ApiTimeoutError) or "timed out" in lowered or "timeout" in lowered: + return "连接服务器超时,请检查网络后重试。" + if isinstance(error, ApiProtocolError) or any( + marker in lowered + for marker in ( + "api response envelope", + "api response is not valid json", + "invalid json", + ) + ): + return "服务器返回的数据格式不正确,请联系管理员检查接口。" + if isinstance(error, ApiHttpError): + status_code = getattr(error, "status_code", None) + suffix = f"(状态码 {status_code})" if status_code else "" + return f"服务器请求失败{suffix},请稍后重试。" + if isinstance(error, ApiTransportError) or any( + marker in lowered + for marker in ( + "connection refused", + "connecterror", + "connection error", + "failed to connect", + "getaddrinfo failed", + "name or service not known", + "network is unreachable", + ) + ): + return "无法连接服务器,请检查服务器地址与网络。" + if any(marker in lowered for marker in ("unauthorized", "forbidden", "permission denied")): + return "当前账号无权执行此操作。" + if "not found" in lowered: + return "未找到所需数据。" + if any("\u4e00" <= character <= "\u9fff" for character in text): + return text + if isinstance(error, TypeError): + return "程序执行失败,请重试;若问题持续出现,请联系管理员。" + return "操作未完成,请稍后重试。" class PageHeader(QWidget): @@ -379,6 +423,10 @@ class StatusBadge(QLabel): self.setObjectName("StatusBadge") self.setAlignment(Qt.AlignmentFlag.AlignCenter) self.setSizePolicy(QSizePolicy.Policy.Maximum, QSizePolicy.Policy.Fixed) + # QSS padding alone is not a reliable minimum on every Windows DPI + # scale. Keep enough physical row height so badge text is never + # squeezed into the thin coloured strip seen in list item widgets. + self.setMinimumHeight(24) self.set_kind(kind) def set_kind(self, kind: str) -> None: diff --git a/app/src/doctor_workstation/video/launcher.py b/app/src/doctor_workstation/video/launcher.py index a45883f00..d59f1ae7c 100644 --- a/app/src/doctor_workstation/video/launcher.py +++ b/app/src/doctor_workstation/video/launcher.py @@ -359,6 +359,8 @@ class VideoCallLauncher: *, diagnosis_id: Any = None, patient_id: Any = None, + open_im: bool = False, + patient_name: str = "患者", ) -> Any: request = self.prepare( ticket, @@ -374,6 +376,8 @@ class VideoCallLauncher: remote_url=self.remote_url, logger=self.logger, browser_opener=self.browser_opener, + open_im=open_im, + patient_name=patient_name, ) @@ -388,6 +392,8 @@ def launch_video_call( remote_url: str | None = None, logger: Any = None, browser_opener: Callable[[str], bool] | None = None, + open_im: bool = False, + patient_name: str = "患者", ) -> Any: """Normalize a ticket and open a call with the requested backend.""" @@ -402,4 +408,6 @@ def launch_video_call( ticket, diagnosis_id=diagnosis_id, patient_id=patient_id, + open_im=open_im, + patient_name=patient_name, ) diff --git a/app/src/doctor_workstation/video/lifecycle.py b/app/src/doctor_workstation/video/lifecycle.py index 1f9a3dbcd..97c7ca4ff 100644 --- a/app/src/doctor_workstation/video/lifecycle.py +++ b/app/src/doctor_workstation/video/lifecycle.py @@ -262,6 +262,53 @@ class OrderedCallLifecycle: self._bind_future = self._worker.submit("bind", operation) return self._bind_future + def save_screenshot(self, content: bytes, filename: str) -> Future[str]: + """Upload one video frame and append it to the diagnosis doctor notes.""" + + if not content: + raise ValueError("screenshot content must not be empty") + if len(content) > 10 * 1024 * 1024: + raise ValueError("screenshot content exceeds 10 MB") + clean_name = str(filename or "callshot.jpg").strip() or "callshot.jpg" + with self._lock: + if self._end_future is not None: + raise RuntimeError("video call has already ended") + upload = getattr(self.repository, "upload_material_bytes", None) + add_note = getattr(self.repository, "add_doctor_note", None) + if not callable(upload) or not callable(add_note): + raise ValueError("video repository does not implement screenshot storage") + + def operation() -> str: + reference = str( + _call_repository_method( + upload, + { + "content": content, + "filename": clean_name, + "material_type": "image", + "cid": 0, + }, + ) + or "" + ).strip() + if not reference: + raise ValueError("screenshot upload returned no server reference") + _call_repository_method( + add_note, + { + "diagnosis_id": self.request.diagnosis_id, + "content": "", + "tongue_images": [reference], + }, + ) + self.logger.info( + "video screenshot stored in doctor notes", + extra={"video_call": self.request.safe_log_context()}, + ) + return reference + + return self._worker.submit("screenshot", operation) + def end(self, reason: str) -> Future[bool]: with self._lock: if self._end_future is not None: diff --git a/app/src/doctor_workstation/video/window.py b/app/src/doctor_workstation/video/window.py index c8cf16747..9bf05f01d 100644 --- a/app/src/doctor_workstation/video/window.py +++ b/app/src/doctor_workstation/video/window.py @@ -7,6 +7,8 @@ actual call requires an isolated QtWebEngine profile and an active QApplication. from __future__ import annotations +import base64 +import binascii import json import logging import sys @@ -181,11 +183,33 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration if isinstance(message, Mapping) and message.get("source") == "doctor-call": self._callback(message) + @Slot(str) # type: ignore[misc] + def saveScreenshot(self, data_url: str) -> None: # noqa: N802 - Qt bridge API + """Forward one bounded JPEG data URL to the trusted desktop host.""" + + if not isinstance(data_url, str) or len(data_url) > 14 * 1024 * 1024: + self._callback( + { + "source": "doctor-call", + "event": "screenshot-invalid", + "message": "截屏图片过大,无法保存。", + } + ) + return + self._callback( + { + "source": "doctor-call", + "event": "screenshot", + "dataUrl": data_url, + } + ) + class _EmbeddedVideoWindow(QMainWindow): # type: ignore[misc, valid-type] status_changed = Signal(str) # type: ignore[misc] call_ended = Signal(str) # type: ignore[misc] call_error = Signal(str) # type: ignore[misc] _start_completed = Signal(bool) # type: ignore[misc] + _screenshot_completed = Signal(bool, str) # type: ignore[misc] def __init__( self, @@ -194,12 +218,19 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration lifecycle: OrderedCallLifecycle, *, logger: logging.Logger, + lifecycle_factory: Callable[[], OrderedCallLifecycle], + open_im: bool = False, + patient_name: str = "患者", ) -> None: super().__init__() self.request = request self.location = location self.lifecycle = lifecycle + self._lifecycle_factory = lifecycle_factory + self._lifecycles = [lifecycle] self.logger = logger + self.open_im = bool(open_im) + self.patient_name = str(patient_name or "患者").strip() or "患者" try: self._policy = TrustedDocumentPolicy.from_url( location.url, @@ -213,10 +244,14 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._companion_ended = False self._released = False self._close_reason = "window-closed" + self._call_cycle_closed = False + self._start_requested = False self._legacy_grants: list[tuple[Any, Any]] = [] self._permission_grants: list[Any] = [] - self.setWindowTitle("视频面诊") + self.setWindowTitle( + f"与 {self.patient_name} IM 问诊" if self.open_im else "视频面诊" + ) self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True) self.resize(1120, 760) self.setMinimumSize(760, 520) @@ -248,6 +283,7 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._connect_permissions() self._start_completed.connect(self._on_lifecycle_started) + self._screenshot_completed.connect(self._on_screenshot_completed) self.web_view.loadFinished.connect(self._on_load_finished) self.web_view.setUrl(QUrl(self.location.url)) @@ -326,17 +362,24 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self.close() return - try: - start_future = self.lifecycle.start() - except Exception: - self.logger.error( - "video call record could not be queued", - extra={"video_call": self.request.safe_log_context()}, - ) - self._close_reason = "record-start-queue-failed" - self.close() - return - start_future.add_done_callback(self._notify_start_completed) + self._media_active = True + config = { + **self.request.to_web_config(), + "patientName": self.patient_name, + "mode": "chat" if self.open_im else "video", + } + config_json = json.dumps(config, ensure_ascii=True, separators=(",", ":")) + script = f""" + (() => {{ + if (!window.doctorConsultation + || typeof window.doctorConsultation.open !== 'function') {{ + return false; + }} + void window.doctorConsultation.open({config_json}).catch(() => undefined); + return true; + }})() + """ + self._page.runJavaScript(script, self._after_injection) def _notify_start_completed(self, future: Future[bool]) -> None: try: @@ -350,25 +393,16 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration if self._closing: return if not succeeded: - self._close_reason = "record-start-failed" - self.close() + self._start_requested = False + self._call_cycle_closed = True + self._page.runJavaScript( + "window.doctorConsultation?.hostCallReady?.(false, " + '"通话记录创建失败,请稍后重试。");' + ) return - self._media_active = True - config_json = json.dumps( - self.request.to_web_config(), - ensure_ascii=True, - separators=(",", ":"), + self._page.runJavaScript( + "window.doctorConsultation?.hostCallReady?.(true, '');" ) - script = f""" - (() => {{ - if (!window.doctorCall || typeof window.doctorCall.start !== 'function') {{ - return false; - }} - void window.doctorCall.start({config_json}).catch(() => undefined); - return true; - }})() - """ - self._page.runJavaScript(script, self._after_injection) def _after_injection(self, result: Any) -> None: self._injected = result is not False @@ -380,6 +414,18 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration if self._closing: return event = str(message.get("event", "")) + if event == "call-start-request": + self._start_call_cycle() + return + if event == "screenshot": + self._save_screenshot(str(message.get("dataUrl") or "")) + return + if event == "screenshot-invalid": + self._on_screenshot_completed( + False, + str(message.get("message") or "截屏图片无效。")[:200], + ) + return room_id = message.get("roomId", message.get("room_id")) if room_id not in (None, ""): self.lifecycle.bind_room(room_id) @@ -388,16 +434,80 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration if event == "status": status = str(message.get("status", "unknown"))[:80] self.status_changed.emit(status) - if status == "idle": + if status == "idle" and not self.open_im: self._close_from_companion("remote-idle") elif event == "hangup": status = str(message.get("status", "ended"))[:80] self.call_ended.emit(status) - self._close_from_companion("companion-hangup") + self.lifecycle.end(f"companion-{status}") + self._call_cycle_closed = True + self._start_requested = False + if not self.open_im: + self._close_from_companion("companion-hangup") elif event == "error": message_text = str(message.get("message", "视频通话错误"))[:400] self.call_error.emit(message_text) - self._close_from_companion("companion-error") + if self._start_requested: + self.lifecycle.end("companion-error") + self._call_cycle_closed = True + self._start_requested = False + if not self.open_im: + self._close_from_companion("companion-error") + + def _start_call_cycle(self) -> None: + if self._closing or self._start_requested: + return + if self._call_cycle_closed: + self.lifecycle = self._lifecycle_factory() + self._lifecycles.append(self.lifecycle) + self._call_cycle_closed = False + self._start_requested = True + try: + future = self.lifecycle.start() + except Exception: + self._start_requested = False + self._on_lifecycle_started(False) + return + future.add_done_callback(self._notify_start_completed) + + def _save_screenshot(self, data_url: str) -> None: + prefix = "data:image/jpeg;base64," + if not data_url.startswith(prefix): + self._on_screenshot_completed(False, "截屏图片格式不正确。") + return + try: + content = base64.b64decode(data_url[len(prefix) :], validate=True) + except (ValueError, binascii.Error): + self._on_screenshot_completed(False, "截屏图片解析失败。") + return + try: + future = self.lifecycle.save_screenshot( + content, + f"callshot-{self.request.diagnosis_id}.jpg", + ) + except Exception as error: + self._on_screenshot_completed(False, str(error)[:200]) + return + future.add_done_callback(self._notify_screenshot_completed) + + def _notify_screenshot_completed(self, future: Future[str]) -> None: + try: + future.result() + except Exception as error: + succeeded = False + message = str(error)[:200] or "截屏保存失败。" + else: + succeeded = True + message = "截屏已保存到患者信息。" + with suppress(RuntimeError): + self._screenshot_completed.emit(succeeded, message) + + def _on_screenshot_completed(self, succeeded: bool, message: str) -> None: + payload = json.dumps(str(message)[:200], ensure_ascii=True) + state = "true" if succeeded else "false" + self._page.runJavaScript( + f"window.doctorConsultation?.screenshotResult?.({state}, {payload});" + ) def _close_from_companion(self, reason: str) -> None: self._companion_ended = True @@ -415,11 +525,15 @@ if WEBENGINE_AVAILABLE: # pragma: no cover - GUI behavior needs an integration self._media_active = False if self._injected and not self._companion_ended and not self._released: self._page.runJavaScript( - "void window.doctorCall?.hangup?.().catch(() => undefined)" + "void window.doctorConsultation?.close?.().catch(() => undefined)" ) - self.lifecycle.end(self._close_reason) + if self._start_requested and not self._call_cycle_closed: + self.lifecycle.end(self._close_reason) self._release_webengine() + def wait_for_lifecycles(self, timeout: float) -> bool: + return all(lifecycle.wait(timeout) for lifecycle in self._lifecycles) + def _release_webengine(self) -> None: if self._released: return @@ -486,6 +600,8 @@ class VideoCallWindow: remote_url: str | None = None, logger: logging.Logger | None = None, browser_opener: Callable[[str], bool] | None = None, + open_im: bool = False, + patient_name: str = "患者", ) -> None: del browser_opener # Reserved for a future authenticated handoff implementation. try: @@ -500,14 +616,23 @@ class VideoCallWindow: raise VideoWindowError("embedded video requires an active QApplication") self.request = request + self.repository = repository + self.open_im = bool(open_im) + self.patient_name = str(patient_name or "患者").strip() or "患者" self.logger = logger or _LOGGER self.location = resolve_companion_location( local_dist=local_dist, remote_url=remote_url, ) self.lifecycle = OrderedCallLifecycle(request, repository, self.logger) + self._lifecycles = [self.lifecycle] self._session: Any = None + def _new_lifecycle(self) -> OrderedCallLifecycle: + lifecycle = OrderedCallLifecycle(self.request, self.repository, self.logger) + self._lifecycles.append(lifecycle) + return lifecycle + @property def qt_window(self) -> Any: return self._session @@ -519,6 +644,9 @@ class VideoCallWindow: self.location, self.lifecycle, logger=self.logger, + lifecycle_factory=self._new_lifecycle, + open_im=self.open_im, + patient_name=self.patient_name, ) except Exception: self.lifecycle.end("window-open-failed") @@ -545,7 +673,9 @@ class VideoCallWindow: def wait_for_lifecycle(self, timeout: float = 0.25) -> bool: """Wait briefly for ordered backend writes; timeout is capped at five seconds.""" - return self.lifecycle.wait(timeout) + if self._session is not None: + return self._session.wait_for_lifecycles(timeout) + return all(lifecycle.wait(timeout) for lifecycle in self._lifecycles) wait = wait_for_lifecycle @@ -558,6 +688,8 @@ def open_video_call( remote_url: str | None = None, logger: logging.Logger | None = None, browser_opener: Callable[[str], bool] | None = None, + open_im: bool = False, + patient_name: str = "患者", ) -> VideoCallWindow: """Create and immediately open a trusted embedded video window.""" @@ -570,6 +702,8 @@ def open_video_call( remote_url=remote_url, logger=logger, browser_opener=browser_opener, + open_im=open_im, + patient_name=patient_name, ).open() diff --git a/app/tests/test_api_client.py b/app/tests/test_api_client.py index c8d1601a5..5f3dc4a9b 100644 --- a/app/tests/test_api_client.py +++ b/app/tests/test_api_client.py @@ -215,21 +215,43 @@ def test_invalid_envelope_raises_protocol_error() -> None: client.get("broken") -def test_token_store_file_fallback_never_persists_password(tmp_path: Path) -> None: - """The fallback contains only an access token and an optional account name.""" +def test_token_store_file_fallback_never_persists_plaintext_password(tmp_path: Path) -> None: + """The fallback may contain a Windows DPAPI blob, but never plaintext.""" path = tmp_path / "credentials.json" store = TokenStore(path, keyring_backend=None) store.save_token("token-value", account="doctor") + password_saved = store.save_password( + "must-not-reach-disk", + account="doctor", + scope="https://example.test/adminapi", + ) assert store.load_token() == "token-value" assert store.load_account() == "doctor" + restored = store.load_password(account="doctor", scope="https://example.test/adminapi") + if password_saved: + assert restored == "must-not-reach-disk" + else: + assert restored is None payload = json.loads(path.read_text(encoding="utf-8")) - assert payload == {"token": "token-value", "account": "doctor"} + assert payload["token"] == "token-value" + assert payload["account"] == "doctor" assert "password" not in path.read_text(encoding="utf-8").lower() + assert "must-not-reach-disk" not in path.read_text(encoding="utf-8") store.clear_token() assert store.load_token() is None assert store.load_account() == "doctor" + after_logout = store.load_password( + account="doctor", + scope="https://example.test/adminapi", + ) + if password_saved: + assert after_logout == "must-not-reach-disk" + else: + assert after_logout is None + store.clear_account() + assert store.load_password(account="doctor", scope="https://example.test/adminapi") is None class _MemoryKeyring: @@ -267,6 +289,33 @@ def test_token_store_prefers_available_keyring(tmp_path: Path) -> None: assert json.loads(path.read_text(encoding="utf-8")) == {"account": "doctor"} +def test_token_store_keeps_login_password_in_scoped_keyring_only(tmp_path: Path) -> None: + backend = _MemoryKeyring() + path = tmp_path / "credentials.json" + store = TokenStore(path, keyring_backend=backend) + scope = "https://example.test/adminapi/" + + assert store.save_password("secret-value", account="doctor", scope=scope) + assert ( + store.load_password(account="doctor", scope="https://example.test/adminapi") + == "secret-value" + ) + assert store.load_password(account="doctor", scope="https://other.test/adminapi") is None + assert "secret-value" not in path.read_text(encoding="utf-8") + assert json.loads(path.read_text(encoding="utf-8")) == { + "account": "doctor", + "scope": "https://example.test/adminapi", + } + + next_scope = "https://next.test/adminapi" + assert store.save_password("next-secret", account="doctor", scope=next_scope) + assert store.load_password(account="doctor", scope=scope) is None + assert store.load_password(account="doctor", scope=next_scope) == "next-secret" + + store.clear_password(account="doctor", scope=next_scope) + assert store.load_password(account="doctor", scope=next_scope) is None + + def test_token_store_scopes_automatic_restore_and_forgets_account(tmp_path: Path) -> None: """Automatic restore never returns a token issued for another API base.""" diff --git a/app/tests/test_reception_parity_ui.py b/app/tests/test_reception_parity_ui.py index c751d8efa..d98dd9fa8 100644 --- a/app/tests/test_reception_parity_ui.py +++ b/app/tests/test_reception_parity_ui.py @@ -10,13 +10,20 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") import httpx import pytest -from PySide6.QtWidgets import QApplication +from PySide6.QtWidgets import QApplication, QPushButton from doctor_workstation.core import PermissionSet from doctor_workstation.services.api_client import ApiClient +from doctor_workstation.services.mock_repository import DemoDoctorRepository from doctor_workstation.services.repository import RemoteDoctorRepository from doctor_workstation.ui.pages import reception as reception_module -from doctor_workstation.ui.pages.reception import NOTE_LIMIT, ReceptionPage +from doctor_workstation.ui.pages.reception import ( + NOTE_LIMIT, + QueueRow, + ReceptionPage, + _is_image_attachment, +) +from doctor_workstation.ui.widgets import StatusBadge @pytest.fixture(scope="module") @@ -50,6 +57,71 @@ def immediate_async(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(reception_module, "run_async", run_immediately) +@pytest.mark.parametrize( + ("path", "expected"), + [ + ("https://cdn.test/tongue.JPG?token=1", True), + ("https://cdn.test/report.webp", True), + ("https://cdn.test/report.pdf", False), + ], +) +def test_note_attachment_preview_type_is_extension_aware(path: str, expected: bool) -> None: + assert _is_image_attachment(path) is expected + + +def test_note_attachments_offer_image_preview_and_file_open( + application: QApplication, +) -> None: + page = ReceptionPage(DemoDoctorRepository(), PermissionSet([])) + page._render_notes( + [ + { + "id": 1, + "note_date": "2026-08-12", + "tongue_images": ["https://cdn.test/tongue.jpg"], + "report_files": [ + "https://cdn.test/check.png", + "https://cdn.test/check.pdf", + ], + } + ] + ) + + labels = [button.text() for button in page.notes_container.findChildren(QPushButton)] + assert labels.count("预览") == 2 + assert labels.count("打开") == 1 + page.close() + application.processEvents() + + +def test_queue_status_badge_is_not_clipped_in_narrow_panel( + application: QApplication, +) -> None: + row = QueueRow( + { + "patient_name": "张蒙", + "status": 1, + "status_desc": "待接诊", + "appointment_time": "12:45:00", + "gender": 1, + "age": 36, + "assistant_name": "苏亚梅", + } + ) + row.setFixedWidth(280) + row.show() + application.processEvents() + + badge = row.findChild(StatusBadge) + assert badge is not None + assert badge.height() >= 24 + assert badge.width() >= 54 + assert badge.geometry().right() < row.width() + + row.close() + application.processEvents() + + def _detail( appointment_id: int, *, @@ -361,6 +433,7 @@ def test_video_payload_keeps_three_identifiers_distinct( "patient_id": 141, "diagnosis_id": 241, "patient_name": "视频患者", + "mode": "im", "record": detail["appointment"], } ] diff --git a/app/tests/test_ui_contract.py b/app/tests/test_ui_contract.py index 2277c4bb4..3913f3886 100644 --- a/app/tests/test_ui_contract.py +++ b/app/tests/test_ui_contract.py @@ -4,7 +4,7 @@ from types import SimpleNamespace from typing import Any from PySide6.QtCore import QSettings -from PySide6.QtWidgets import QApplication +from PySide6.QtWidgets import QApplication, QDialogButtonBox, QMessageBox from doctor_workstation import app as app_module from doctor_workstation.app import ApplicationController @@ -232,11 +232,28 @@ def test_real_demo_login_reaches_success_without_widget_adapter( application.processEvents() -def test_remembered_account_survives_a_new_login_window(tmp_path: Any) -> None: +def test_remembered_password_survives_a_new_login_window(tmp_path: Any) -> None: application = QApplication.instance() or QApplication([]) - settings_path = tmp_path / "remember-account.ini" + settings_path = tmp_path / "remember-password.ini" + secrets: dict[tuple[str, str], str] = {} + + def load_password(*, account: str, scope: str) -> str | None: + return secrets.get((account, scope.rstrip("/"))) + + def save_password(password: str, *, account: str, scope: str) -> bool: + secrets[(account, scope.rstrip("/"))] = password + return True + + def clear_password(*, account: str, scope: str) -> None: + secrets.pop((account, scope.rstrip("/")), None) + + credentials = SimpleNamespace( + load_password=load_password, + save_password=save_password, + clear_password=clear_password, + ) config = SimpleNamespace( - api_base_url="", + api_base_url="https://example.test/adminapi", request_timeout=30, verify_ssl=True, demo_mode=False, @@ -246,8 +263,9 @@ def test_remembered_account_survives_a_new_login_window(tmp_path: Any) -> None: object(), config=config, settings=QSettings(str(settings_path), QSettings.Format.IniFormat), + credential_store=credentials, ) - first._on_login_success({}, "admin", True) + first._on_login_success({}, "admin", True, "secret-value") first.close() application.processEvents() @@ -255,12 +273,28 @@ def test_remembered_account_survives_a_new_login_window(tmp_path: Any) -> None: object(), config=config, settings=QSettings(str(settings_path), QSettings.Format.IniFormat), + credential_store=credentials, ) assert restored.account_edit.text() == "admin" + assert restored.password_edit.text() == "secret-value" + assert restored.remember_check.text() == "记住密码" assert restored.remember_check.isChecked() + + restored._on_login_success({}, "admin", False, "secret-value") restored.close() application.processEvents() + forgotten = LoginWindow( + object(), + config=config, + settings=QSettings(str(settings_path), QSettings.Format.IniFormat), + credential_store=credentials, + ) + assert forgotten.password_edit.text() == "" + assert not forgotten.remember_check.isChecked() + forgotten.close() + application.processEvents() + def test_server_settings_panel_keeps_controls_separated_at_minimum_window( tmp_path: Any, @@ -386,6 +420,37 @@ def test_certificate_error_explains_self_signed_server_setting() -> None: assert "服务器设置" in message +def test_qt_standard_dialog_buttons_are_localized_to_chinese() -> None: + application = QApplication.instance() or QApplication([]) + app_module._install_chinese_translations(application) + + question = QMessageBox() + question.setStandardButtons( + QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.Cancel + ) + assert question.button(QMessageBox.StandardButton.Yes).text() == "是" + assert question.button(QMessageBox.StandardButton.Cancel).text() == "取消" + + buttons = QDialogButtonBox( + QDialogButtonBox.StandardButton.Ok + | QDialogButtonBox.StandardButton.Save + | QDialogButtonBox.StandardButton.Close + ) + assert buttons.button(QDialogButtonBox.StandardButton.Ok).text() == "确定" + assert buttons.button(QDialogButtonBox.StandardButton.Save).text() == "保存" + assert buttons.button(QDialogButtonBox.StandardButton.Close).text() == "关闭" + + +def test_friendly_error_hides_english_technical_messages() -> None: + message = friendly_error( + TypeError("invoke() takes 2 positional arguments but 3 were given") + ) + assert message == "程序执行失败,请重试;若问题持续出现,请联系管理员。" + assert friendly_error(RuntimeError("API response envelope must be an object")) == ( + "服务器返回的数据格式不正确,请联系管理员检查接口。" + ) + + def test_certificate_error_opens_server_settings(tmp_path: Any) -> None: application = QApplication.instance() or QApplication([]) settings = QSettings(str(tmp_path / "certificate-error.ini"), QSettings.Format.IniFormat) diff --git a/app/tests/test_video_contract.py b/app/tests/test_video_contract.py index 52336b95f..53241ccc1 100644 --- a/app/tests/test_video_contract.py +++ b/app/tests/test_video_contract.py @@ -274,6 +274,57 @@ def test_failed_start_prevents_bind_and_end_writes() -> None: assert events == ["start"] +def test_video_screenshot_is_uploaded_and_appended_to_patient_tongue_images() -> None: + events: list[tuple[object, ...]] = [] + + class Repository: + def start_call(self, diagnosis_id: int, *, call_type: int) -> None: + events.append(("start", diagnosis_id, call_type)) + + def upload_material_bytes( + self, + content: bytes, + filename: str, + material_type: str, + cid: int = 0, + ) -> str: + events.append(("upload", content, filename, material_type, cid)) + return "/uploads/image/callshot-123.jpg" + + def add_doctor_note( + self, + diagnosis_id: int, + content: str, + tongue_images: list[str], + ) -> None: + events.append(("note", diagnosis_id, content, tongue_images)) + + def end_call(self, diagnosis_id: int) -> None: + events.append(("end", diagnosis_id)) + + request = VideoCallRequest( + sdk_app_id=1400123456, + user_id="doctor_42", + user_sig="short-lived-ticket", + target_user_id="patient_8", + diagnosis_id=123, + ) + lifecycle = OrderedCallLifecycle(request, Repository(), logging.getLogger(__name__)) + + lifecycle.start() + screenshot = lifecycle.save_screenshot(b"jpeg-frame", "callshot-123.jpg") + lifecycle.end("test") + + assert screenshot.result(timeout=2) == "/uploads/image/callshot-123.jpg" + assert lifecycle.wait(1) is True + assert events == [ + ("start", 123, 2), + ("upload", b"jpeg-frame", "callshot-123.jpg", "image", 0), + ("note", 123, "", ["/uploads/image/callshot-123.jpg"]), + ("end", 123), + ] + + def test_https_document_policy_is_exact_and_origin_scoped() -> None: policy = TrustedDocumentPolicy.from_url( "https://RTC.Example.com/doctor-call/index.html?tenant=a#boot", diff --git a/app/video_companion/dist/assets/index-BuO_uDya.css b/app/video_companion/dist/assets/index-BuO_uDya.css deleted file mode 100644 index 9f3778393..000000000 --- a/app/video_companion/dist/assets/index-BuO_uDya.css +++ /dev/null @@ -1 +0,0 @@ -:root{font-family:Inter,PingFang SC,Microsoft YaHei,system-ui,sans-serif;color:#f7f8fa;background:#0b0f14;font-synthesis:none;text-rendering:optimizeLegibility}*{box-sizing:border-box}html,body,#app{width:100%;height:100%;margin:0;overflow:hidden}button,input{font:inherit}.call-stage{position:relative;width:100%;height:100%;min-height:420px;overflow:hidden;background:radial-gradient(circle at 50% 35%,rgba(39,74,83,.22),transparent 38%),#0b0f14}.call-kit,.call-stage :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 rgba(255,255,255,.09);border-radius:20px;background:#131920e6;box-shadow:0 24px 70px #00000052;backdrop-filter:blur(18px)}.eyebrow{margin:0 0 12px;color:#8f9ba8;font-size:12px;font-weight:700;letter-spacing:.16em;text-transform:uppercase}.status-card h1{margin:0;font-size:clamp(22px,3.2vw,34px);font-weight:600;line-height:1.25}.status-hint{margin:14px 0 0;color:#9aa5b1;font-size:14px}.status-dot{width:10px;height:10px;margin-top:5px;border-radius:50%;background:#77818c;box-shadow:0 0 0 5px #77818c1f}.status-dot--starting,.status-dot--live{background:#52c99a;box-shadow:0 0 0 5px #52c99a24}.status-dot--error{background:#f26d6d;box-shadow:0 0 0 5px #f26d6d24}.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 rgba(255,255,255,.1);border-radius:999px;background:#0b0f14c2;color:#e8edf2;font-size:13px;backdrop-filter:blur(14px)}.live-status .status-dot{width:7px;height:7px;margin:0;box-shadow:none} diff --git a/app/video_companion/dist/assets/index-DwSVWep6.js b/app/video_companion/dist/assets/index-DwSVWep6.js new file mode 100644 index 000000000..0836105c4 --- /dev/null +++ b/app/video_companion/dist/assets/index-DwSVWep6.js @@ -0,0 +1,632 @@ +(function(){const i=document.createElement("link").relList;if(i&&i.supports&&i.supports("modulepreload"))return;for(const u of document.querySelectorAll('link[rel="modulepreload"]'))l(u);new MutationObserver(u=>{for(const p of u)if(p.type==="childList")for(const y of p.addedNodes)y.tagName==="LINK"&&y.rel==="modulepreload"&&l(y)}).observe(document,{childList:!0,subtree:!0});function r(u){const p={};return u.integrity&&(p.integrity=u.integrity),u.referrerPolicy&&(p.referrerPolicy=u.referrerPolicy),u.crossOrigin==="use-credentials"?p.credentials="include":u.crossOrigin==="anonymous"?p.credentials="omit":p.credentials="same-origin",p}function l(u){if(u.ep)return;u.ep=!0;const p=r(u);fetch(u.href,p)}})();var pg=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function B3(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ZL(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 u=Object.getOwnPropertyDescriptor(t,l);Object.defineProperty(r,l,u.get?u:{enumerable:!0,get:function(){return t[l]}})}),r}var l1={exports:{}},RiA=l1.exports,z5;function wiA(){return z5||(z5=1,function(t,i){(function(r,l){t.exports=l()})(RiA,function(){const r=s=>s===void 0,l=s=>typeof s=="string",u=s=>{var n;return(n=Object.prototype.toString.call(s).match(/^\[object (.*)\]$/))===null||n===void 0?void 0:n[1].toLowerCase()},p=s=>typeof Array.isArray=="function"?Array.isArray(s):u(s)==="array",y=s=>s!==null&&typeof s=="object",w=s=>p(s)||y(s),_=s=>{if(typeof s!="string")return!1;const n=s[0];return!/[^a-zA-Z0-9]/.test(n)},k=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 F(s=99999999){return Math.round(Math.random()*s)}const j=(s,n,g,I)=>{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",to=It&&typeof wx.miniapp=="object",uo=typeof uni<"u",Ys=ft&&typeof tt.enterChat=="function",ki=It||qe||ft||Vt||gi||_o||Fi,os=typeof window>"u"&&!ki&&typeof pg<"u"&&pg.NativeScriptGlobals!==void 0,Ko=typeof pg<"u"&&(pg.nativeModuleProxy!==void 0||pg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,jt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!Ko,io=qe?qq:ft?tt:Vt?swan:gi?my:It?wx:_o?uni:Fi?jd:{},bi=jt&&window&&window.navigator&&window.navigator.userAgent||"",Ms=/(micromessenger|webbrowser)/i.test(bi),qA=function(){let s="WEB";return Ms?s="WEB":qe?s="QQ_MP":ft?s="TT_MP":Vt?s="BAIDU_MP":gi?s="ALI_MP":It?s=to?"DONUT_NATIVE_APP":"WX_MP":_o?s="UNI_NATIVE_APP":os?s="NS_NATIVE_APP":Ko&&(s="RN_NATIVE_APP"),aA[s]}(),ce=/iPad/i.test(bi),Pe=/iPhone/i.test(bi)&&!ce,kt=/iPod/i.test(bi),it=Pe||ce||kt,gt=function(){const s=bi.match(/OS (\d+)_/i);return s&&s[1]?s[1]:null}(),Xt=/Android/i.test(bi),$t=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}(),Ge=/Firefox/i.test(bi),je=/Edge/i.test(bi),Mt=!je&&/Chrome/i.test(bi),Rt=/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}(),Qo=/Safari/i.test(bi)&&!Mt&&!Xt&&!je,To=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),No=jt&&typeof Worker<"u"&&!Rt,$s=Xt||it,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:s}=window.navigator;return!(!it||s||Qo)}();function us(){let s="unknown";if(oo&&(s="mac"),To&&(s="windows"),it&&(s="ios"),Xt&&(s="android"),ki)try{const{platform:n}=io.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 yo(s,n){var g={};for(var I in s)Object.prototype.hasOwnProperty.call(s,I)&&n.indexOf(I)<0&&(g[I]=s[I]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function"){var E=0;for(I=Object.getOwnPropertySymbols(s);E{io.request({url:g,data:I,method:n,timeout:E,header:{"content-type":jr},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":${Br}}`))},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",jr),M.send(I||null)})})}function vs(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(k(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 ir(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(ir(M,g),ir(D,g))}),m}if(s instanceof Set){const m=new Set;return g.set(s,m),s.forEach(D=>{m.add(ir(D,g))}),m}if(Array.isArray(s)){const m=[];return g.set(s,m),s.forEach(D=>{m.push(ir(D,g))}),m}const I=Object.getPrototypeOf(s),E=Object.create(I);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]=ir(s[m],g))}),E}function An(s,n,g){const I=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(I.has(D))return"[Circular]";I.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,I)=>{s=g,n=I}),resolve:s,reject:n}}var Jt,fg=Object.freeze({__proto__:null,ANDROID_VERSION:$t,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Vt,IN_BROWSER:jt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:Ys,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:os,IN_QQ_MINI_APP:qe,IN_RN_APP:Ko,IN_TT_MINI_APP:ft,IN_TT_MINI_GAME:si,IN_UNI_APP:uo,IN_UNI_NATIVE_APP:_o,IN_WX_MINI_APP:It,IN_WX_MINI_APP_DESK:qt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:gt,IS_ANDROID:Xt,IS_CHROME:Mt,IS_EDGE:je,IS_FIREFOX:Ge,IS_IE:Rt,IS_IOS:it,IS_IPAD:ce,IS_IPHONE:Pe,IS_IPOD:kt,IS_MAC:oo,IS_SAFARI:Qo,IS_WECHAT:Ms,IS_WIN:To,IS_WORKER_AVAILABLE:No,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:ir,deepMerge:j,generatePromise:wn,getPlatformType:us,getType:u,httpRequest:Pi,isArray:p,isArrayOrObject:w,isEmpty:vs,isH5:$s,isIOSWebView:rn,isNumber:s=>s!==null&&(typeof s=="number"&&!Number.isNaN(s-0)||typeof s=="object"&&s.constructor===Number),isObject:y,isPlainObject:k,isString:l,isUndefined:r,isUniIOSApp:function(){return _o&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:qA,randomInt:F,randomString:function(){const s="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let n="";for(let g=32;g>0;--g)n+=s[Math.floor(62*Math.random())];return n},safeStringify:An});class On{constructor(){this.listeners={}}on(n,g,I){this.listeners[n]||(this.listeners[n]=[]),this.listeners[n].push({fn:g,context:I})}off(n,g,I){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=!I||m.context===I;return!(D&&M)}))}emit(n,...g){const I=this.listeners[n];I&&I.forEach(E=>{const{fn:m,context:D}=E;try{m.apply(D,g)}catch(M){console.warn(`Error in event handler for ${n} error: ${An(M)}`)}})}once(n,g,I){const E=(...m)=>{g.apply(I,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"})(Jt||(Jt={}));const Gn=[16,17];function Vs(s){var n;const g=[];return(n=s?.GroupTips)===null||n===void 0||n.forEach(I=>{var E;I.GroupInfo.MillionGroupFlag===2?g.push(Jt.TOPIC_TIPS_NOTIFICATION):Gn.includes((E=I?.MsgBody)===null||E===void 0?void 0:E.OpType)?g.push(Jt.GROUP_MESSAGE_PINNED):g.push(Jt.GROUP_TIPS_NOTIFICATION)}),g}const Qr=[{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 n;const g=[];return(n=s?.C2cNotifyMsgArray)===null||n===void 0||n.forEach(I=>{I.WithdrawC2cMsgNotify&&g.push(Jt.C2C_REVOKED_MESSAGE),I.C2cReadedReceipt&&g.push(Jt.C2C_MESSAGE_PEER_READ),I.ReadC2cMsgNotify&&g.push(Jt.C2C_MESSAGE_READ_SYNC),I.MuteNotificationsSync&&g.push(Jt.C2C_REMIND_TYPE_SYNC)}),g}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Vs},{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(I=>{Array.isArray(I.MsgBody.GroupWithdrawInfoArray)?g.push(Jt.GROUP_MESSAGE_REVOKED):Array.isArray(I.MsgBody.GroupMsgReceiptList)?g.push(Jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(I.MsgBody.GroupReadInfoArray)?I.MsgBody.GroupReadInfoArray[0].TopicId?g.push(Jt.TOPIC_MESSAGE_READ_SYNC):g.push(Jt.GROUP_MESSAGE_READ_SYNC):I.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:Vs},{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(I=>{const{GroupAtTips:{TopicId:E}}=I;E?g.push(Jt.TOPIC_AT_TIPS):g.push(Jt.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(I=>{switch(I.PushType){case Ke.CONV_MARK_UPDATED:g.push(Jt.CONVERSATION_MARK_UPDATED);break;case Ke.CONV_GROUP_ADDED:g.push(Jt.CONVERSATION_GROUP_ADD);break;case Ke.CONV_GROUP_DELETED:g.push(Jt.CONVERSATION_GROUP_DELETED);break;case Ke.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 Pn;function pr(s){var n;const g=Array.isArray((n=s?.body)===null||n===void 0?void 0:n.EventArray)?s.body.EventArray:[],I=[];return g.forEach(E=>{E.Flag=s.body.Flag;const m=Qr.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=>{I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${M}`,data:E})}):I.push({type:`${Pn.SERVER_PUSH_MESSAGE}:${D}`,data:E})}),I}(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 po={[Pn.SERVER_PUSH_MESSAGE]:pr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:pr,[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=Jt}subscribeInnerEvent(s,n,g,I,E){var m;let D,M,T,P;["string","number"].includes(typeof n)?(T=`${s}:${n}`,P=g,M=I,D=E):(T=s,P=n,M=g,D=typeof I=="function"?I: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,I;if((g=this._innerEventEmitter)===null||g===void 0||g.emit(s,n),Object.keys(po).includes(s)){const E=(I=po[s])===null||I===void 0?void 0:I.call(po,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 I;(I=this._outerEventEmitter)===null||I===void 0||I.on(s,n,g)}unSubscribeOuterEvent(s,n,g){var I;(I=this._outerEventEmitter)===null||I===void 0||I.off(s,n,g)}unSubscribeInnerEvent(s,n,g,I){if(["string","number"].includes(typeof n)){const E=g,m=`${s}:${n}`;this._unsubscribeEvent(m,E,I)}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,I){var E;const m=D=>{I.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:I,context:g}),(E=this._innerEventEmitter)===null||E===void 0||E.on(s,m,g)}_unsubscribeEvent(s,n,g){var I,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(I=this._innerEventEmitter)===null||I===void 0||I.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 fl{constructor(){this._socket=null}connectSocket(n){return this._socket=new WebSocket(n),this._socket}send(n){var g,I;try{(g=this._socket)===null||g===void 0||g.send(n)}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.binaryType="arraybuffer",this._socket.onopen=g,this._socket.onmessage=I,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=io.connectSocket({url:n,header:{"content-type":"application/json"},complete:()=>{},fail:I=>g._onError(I)}),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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(I),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 mr="CONNECT",ks="SEND",Yc="DISCONNECT",ps="OPEN",rs="MESSAGE",Bu="CLOSE",ja="ERROR",ds="SEND_FAIL";class og{constructor(){this._worker=null,this._blobUrl=null}connectSocket(n){const g=new Blob([` + let _socket = null; + + self.onmessage = (event) => { + const { type, url, data } = event.data; + + switch (type) { + case 'CONNECT': + connectSocket(url); + break; + case 'SEND': + send(data); + break; + case 'DISCONNECT': + disconnect(); + break; + } + }; + + function connectSocket(url) { + _socket = new WebSocket(url); + _socket.binaryType = 'arraybuffer'; + bindSocketHandlers(); + return _socket; + } + + function send(packet) { + try { + _socket?.send(packet); + } catch (error) { + self.postMessage({ + type: 'SEND_FAIL', + error: { + message: error.message, + name: error.name, + }, + }); + } + } + + function bindSocketHandlers() { + if (_socket) { + _socket.onopen = (event) => { + self.postMessage({ + type: 'OPEN', + data: { + type: event.type, + timeStamp: event.timeStamp, + }, + }); + }; + + _socket.onmessage = (event) => { + self.postMessage({ + type: 'MESSAGE', + data: event.data, + }); + }; + + _socket.onclose = (event) => { + self.postMessage({ + type: 'CLOSE', + data: { + code: event.code, + reason: event.reason, + timeStamp: event.timeStamp, + }, + }); + }; + + _socket.onerror = (error) => { + self.postMessage({ + type: 'ERROR', + data: { + message: error.message, + name: error.name + }, + }); + }; + } + } + + function unbindSocketHandlers() { + if (_socket) { + _socket.onopen = null; + _socket.onmessage = null; + _socket.onclose = null; + _socket.onerror = null; + } + } + + function disconnect() { + if (_socket) { + _socket.close(); + _socket = null; + } + } +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(g)),this._worker.postMessage({type:mr,url:n})}send(n){var g,I;try{(g=this._worker)===null||g===void 0||g.postMessage({type:ks,data:n})}catch(E){(I=this._onSendFail)===null||I===void 0||I.call(this,E)}}bindSocketHandlers(n){const{onOpen:g,onMessage:I,onClose:E,onError:m,onSendFail:D}=n;if(this._worker){const M={[ps]:g,[rs]:I,[Bu]:E,[ja]:m,[ds]: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:Yc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class LI{}var Xo,Zi=new class{constructor(){this._store=new Map}get(s){return this._store.get(s)}getStorage(s){return ki?gi?my.getStorageSync({key:s}).data:io.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?gi?my.setStorageSync({key:s,data:JSON.stringify(n)}):io.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 Qc{connectSocket(n){return this._socket=io.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:I,onClose:E,onError:m,onSendFail:D}=n;this._socket&&(this._socket.onClose(E),this._socket.onOpen(g),this._socket.onMessage(M=>I(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"})(Xo||(Xo={}));class sg{constructor(n){this._url="",this._readyState=Xo.DISCONNECTED,this._url=n,this._id=F(),this._emitter=new On,gi?this._socket=new Qc:It||_o||ft||qe||Fi||Vt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new LI:this._canUseWebWorker()?this._socket=new og:this._socket=new fl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this._readyState=Xo.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(n){this._readyState!==Xo.CONNECTED?this.reconnect():this._socket.send(n)}reconnect(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(n,g,I){this._emitter.on(n,g,I)}off(n,g,I){this._emitter.off(n,g,I)}isConnected(){return this._readyState===Xo.CONNECTED}disconnect(){this._readyState=Xo.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(n){this._readyState===Xo.CONNECTING&&(this._readyState=Xo.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:n}))}_onMessage(n){this._emitter.emit("message",n)}_onClose(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:n})}_onError(n){this._readyState=Xo.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:n})}_onSendFail(n){this._readyState=Xo.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=Zi.get("cloudConfig")||{};return(r(n.isWorkerEnabled)||n.isWorkerEnabled==="1")&&No}}const yg={[ct.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ct.KOREA]:[[3e7,4e7],[173e7,174e7]],[ct.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ct.IND]:[[5e7,6e7],[175e7,176e7]],[ct.JPN]:[[6e7,7e7],[176e7,177e7]],[ct.USA]:[[7e7,8e7],[177e7,178e7]],[ct.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ct.KSA]:[[9e7,1e8],[179e7,18e8]]};function la(s){var n;if(!((n=Zi.get("instance"))===null||n===void 0)&&n.oversea)return ct.OVERSEA;for(const g of Object.keys(yg))for(const[I,E]of yg[g])if(s>=I&&s`${oA}=${W[oA]}`).join("&"));var W;return g?`${s}/binfo?${P}&compress=gzip`:`${s}/info?${P}`}function Js(s){const n=Zi.get("instance"),{sdkAppId:g,testEnv:I,proxyServer:E}=n,m=la(g);if(I)return Hn(mt.TEST[m].DEFAULT,{isBinary:s});if(!vs(E))return Hn(E,{isBinary:s});const D=mt.PRODUCTION[m],M=jt&&D.ANYCAST,T=jt,P=!!D.BACKUP_CN;return Hn({[Go.INITIAL]:()=>(wo=Go.DEFAULT,D.DEFAULT),[Go.DEFAULT]:()=>(wo=Go.IPV6,D.IPV6),[Go.IPV6]:()=>(wo=Go.BACKUP,D.BACKUP),[Go.BACKUP]:()=>T?(wo=Go.BACKUP_WEB_ONLY,function(W){const oA=Math.floor(10001*Math.random())+1e4;return W.replace("*",String(oA))}(D.BACKUP_WEB_ONLY)):P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_WEB_ONLY]:()=>P?(wo=Go.BACKUP_CN,D.BACKUP_CN):M?(wo=Go.ANYCAST,D.ANYCAST):D.DEFAULT,[Go.BACKUP_CN]:()=>(wo=M?Go.ANYCAST:Go.DEFAULT,D[wo]),[Go.ANYCAST]:()=>(wo=Go.DEFAULT,D.ANYCAST="",D.DEFAULT)}[wo](),{isBinary:s})}var Dg=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(),I=g-s;this._timeOffsetWithServer=n+I-g}};const pc=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:I,isOnce:E=!1,intervalMs:m=pc}=s,D=Math.max(m,pc);return{id:n,nextExecuteTime:Date.now()+D,intervalMs:m,callback:g,context:I,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 Na(s){const n=[];for(let g=0;g=55296&&I<=56319){const E=s.charCodeAt(++g)-56320+(I-55296<<10)+65536;n.push(240|E>>18,128|E>>12&63,128|E>>6&63,128|63&E)}else I<=127?n.push(I):I<=2047?n.push(192|I>>6,128|63&I):n.push(224|I>>12,128|I>>6&63,128|63&I)}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 ms(s,n){if(mA.includes(s))return 0;const g=Na(JSON.stringify(n));let I=4294967295;const{length:E}=g;for(let m=0;m>>=1:I=I>>>1^3988292384}return(4294967295^I)>>>0}function Ia(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}}function yn(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}}let Ga=F();function ya(){return Ga=Ga<2415919103?Ga+1:F(),Ga}function $(){var s;const n=Zi.get("login")||{},g=Zi.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=Zi.get("webPush"))===null||s===void 0?void 0:s.userId),platform:qA,instance_id:g.instanceId,trace_id:new Date().getTime()}}var K,RA=Object.freeze({__proto__:null,calcBodyCRC:ms,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(s){const{servcmd:n,data:g}=s,I=function(m){const D=Zi.get("login")||{},M=Zi.get("instance")||{};return{servcmd:m,ver:"v4",platform:qA,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:ya(),cs:0}}(n),E=In(g);return I.cs=ms(n,E),{head:I,body:E}},generateProtocolData:Ia,generateSSOLogProtocolData:yn,generateSequence:ya,getCommonHead:$,getHostSite:la,taskScheduler:fn,timeManager:Dg});(function(s){s[s.info=4]="info",s[s.warning=5]="warning",s[s.error=6]="error"})(K||(K={}));const KA={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=Dg.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:I=0,message:E="",costTime:m=0,error:D,uiPlatform:M,moreMessage:T="",code:P=0,startTime:W=0}=n||{};this.eventType=I,this.method=g,this.message=E,this.costTime=m,this.moreMessage=`${T} startTime:${W}`,this.code=P,D&&this.setError(D),vs(M)||(this.uiPlatform=M)}setMoreMessage(n){this.moreMessage=`${this.moreMessage} ${n}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Dg.getTimeOffsetWithServer()}end(n=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Dg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),n&&this._ssoLogModule.uploadSSOLogData())}setError(n){var g;return n instanceof Error?this._canSendLog?(!((g=Zi.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(KA).includes(g)&&(this[g]=n[g])}),this}setSSOLogModule(n){this._ssoLogModule=n}_convertSSOLogDataKeyToServe(){const n={};return Object.keys(this).forEach(g=>{const I=g;KA[I]&&(n[KA[I]]=this[I])}),n}_getUiPlatform(){var n;const g=(n=Zi.get("instance"))===null||n===void 0?void 0:n.scene;if(typeof g=="string"){const I=Number(g);return isNaN(I)?void 0:I}}_getSDKEdition(){var n;return(n=Zi.get("instance"))===null||n===void 0?void 0:n.sdkEdition}}var pe;(function(s){s.RECONNECTED="reconnected",s.CLOUD_CONFIG_UPDATE="cloud_config_update",s.SOCKET_DISCONNECTED="socket_disconnected"})(pe||(pe={}));var Fe=pe;const Ue=20,ot=6e4,ut=[4,5,6],St="report-logger";var Ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:Ve,maxCount:Be},single:{throttleTime:ge,maxCount:de}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(s){const{evt_rpt_threshold:n=Ue,evt_rpt_waiting:g=ot,evt_rpt_level:I=ut,evt_rpt_sdkappid_bl:E="",evt_rpt_tinyid_wl:m="",evt_rpt_global_throttle_time:D=Ve,evt_rpt_global_throttle_count:M=Be,evt_rpt_single_throttle_time:T=ge,evt_rpt_single_throttle_count:P=de}=s||{};this._sdkAppIdBlackList=E.split(",").map(W=>Number(W)),this._waitingTime=Number(g),this._minThreshold=n,this._reportLevel=I,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};vs(g.Header.user_id)||(yield function(I){const E="imopenstat.tim_web_report_v2",m=yn({servcmd:E,data:I}),D=`${m.head.seq}${E}`;return fe.sendPacket(m,{requestId:D})}(g))}catch(n){this._requeueFailedLogs(s),this.debug("uploadSSOLogData",An(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(It){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:I,envVersion:E}=g;Zi.set("instance",{appId:I,envVersion:E})}}else jt&&Zi.set("instance",{href:window.location.href})}_filterLogs(s){const{tinyID:n}=Zi.get("login")||{},{sdkAppId:g}=Zi.get("instance")||{};return this._sdkAppIdBlackList.includes(g)&&!this._tinyIdWhiteList.includes(n)?[]:s.filter(I=>this._reportLevel.includes(I.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(PA[s])}_formatLog(s,n,g,I){const E=new Date,m=`${E.getHours()}:${E.getMinutes()}:${E.getSeconds()}:${E.getMilliseconds()}`,D=`<${IA[s]}>`;return Rt||ki?[`${tA} [${m}] ${D} [${n}] ${g}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",tA,"",`[${m}] ${D} [${n}] ${g} params: ${An(I)}`]}_log(s,n,g,I){if(this._shouldLog(s)){const E=this._formatLog(s,n,g,I);MA[s].apply(console,E)}if(this._shouldReport(s)){const E=this._getThrottleKey(n,g,I);this._checkThrottle(E)||this.createSSOLogData(Object.assign(Object.assign({message:g},I),{method:n})).end()}}_getThrottleKey(s,n,g){const I=`${s}${n}${An(Object.assign(Object.assign({},g),{costTime:""}))}`,E=Na(JSON.stringify(I));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(St),gn.unSubscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const li=15e3,nt="Channel",Ft="channel_schedule_task",Ji="channel_reconnect_task",qi="connected",Hs="connecting",Mi="disconnected",Wo=1e3,Sg="network_status_change",or="activity_status_change",fr="send_fail",xn="reconnect_failed",yl="socket_error",qs="socket_close";function tI(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function jg(s){return jg=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},jg(s)}function mc(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 Qu,Da={exports:{}},Dl=(Qu||(Qu=1,function(s){s.exports=function n(g,I,E){function m(T,P){if(!I[T]){if(!g[T]){if(!P&&mc)return mc(T);if(D)return D(T,!0);var W=new Error("Cannot find module '"+T+"'");throw W.code="MODULE_NOT_FOUND",W}var oA=I[T]={exports:{}};g[T][0].call(oA.exports,function(EA){return m(g[T][1][EA]||EA)},oA,oA.exports,n,g,I,E)}return I[T].exports}for(var D=mc,M=0;M>>6:(EA<65536?oA[YA++]=224|EA>>>12:(oA[YA++]=240|EA>>>18,oA[YA++]=128|EA>>>12&63),oA[YA++]=128|EA>>>6&63),oA[YA++]=128|63&EA);return oA},I.buf2binstring=function(W){return P(W,W.length)},I.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)},I.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(n,g,I){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(n,g,I){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,I){g.exports=function(E,m){var D,M,T,P,W,oA,EA,wA,kA,YA,LA,SA,OA,HA,se,oe,_i,Ti,bt,Ni,gs,De,Bt,UA,ii;D=E.state,M=E.next_in,UA=E.input,T=M+(E.avail_in-5),P=E.next_out,ii=E.output,W=P-(m-E.avail_out),oA=P+(E.avail_out-257),EA=D.dmax,wA=D.wsize,kA=D.whave,YA=D.wnext,LA=D.window,SA=D.hold,OA=D.bits,HA=D.lencode,se=D.distcode,oe=(1<>>=bt=Ti>>>24,OA-=bt,(bt=Ti>>>16&255)==0)ii[P++]=65535&Ti;else{if(!(16&bt)){if(!(64&bt)){Ti=HA[(65535&Ti)+(SA&(1<>>=bt,OA-=bt),OA<15&&(SA+=UA[M++]<>>=bt=Ti>>>24,OA-=bt,!(16&(bt=Ti>>>16&255))){if(!(64&bt)){Ti=se[(65535&Ti)+(SA&(1<>>=bt,OA-=bt,(bt=P-W)>3,SA&=(1<<(OA-=Ni<<3))-1,E.next_in=M,E.next_out=P,E.avail_in=M>>24&255)+(De>>>8&65280)+((65280&De)<<8)+((255&De)<<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(De){var Bt;return De&&De.state?(Bt=De.state,De.total_in=De.total_out=Bt.total=0,De.msg="",Bt.wrap&&(De.adler=1&Bt.wrap),Bt.mode=wA,Bt.last=0,Bt.havedict=0,Bt.dmax=32768,Bt.head=null,Bt.hold=0,Bt.bits=0,Bt.lencode=Bt.lendyn=new E.Buf32(kA),Bt.distcode=Bt.distdyn=new E.Buf32(YA),Bt.sane=1,Bt.back=-1,oA):EA}function HA(De){var Bt;return De&&De.state?((Bt=De.state).wsize=0,Bt.whave=0,Bt.wnext=0,OA(De)):EA}function se(De,Bt){var UA,ii;return De&&De.state?(ii=De.state,Bt<0?(UA=0,Bt=-Bt):(UA=1+(Bt>>4),Bt<48&&(Bt&=15)),Bt&&(Bt<8||15=Gi.wsize?(E.arraySet(Gi.window,Bt,UA-Gi.wsize,Gi.wsize,0),Gi.wnext=0,Gi.whave=Gi.wsize):(ii<(ws=Gi.wsize-Gi.wnext)&&(ws=ii),E.arraySet(Gi.window,Bt,UA-ii,ws,Gi.wnext),(ii-=ws)?(E.arraySet(Gi.window,Bt,UA-ii,ii,0),Gi.wnext=ii,Gi.whave=Gi.wsize):(Gi.wnext+=ws,Gi.wnext===Gi.wsize&&(Gi.wnext=0),Gi.whave>>8&255,UA.check=D(UA.check,Eg,2,0),_t=wt=0,UA.mode=2;break}if(UA.flags=0,UA.head&&(UA.head.done=!1),!(1&UA.wrap)||(((255&wt)<<8)+(wt>>8))%31){De.msg="incorrect header check",UA.mode=30;break}if((15&wt)!=8){De.msg="unknown compression method",UA.mode=30;break}if(_t-=4,Ya=8+(15&(wt>>>=4)),UA.wbits===0)UA.wbits=Ya;else if(Ya>UA.wbits){De.msg="invalid window size",UA.mode=30;break}UA.dmax=1<>8&1),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0,UA.mode=3;case 3:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.time=wt),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,Eg[2]=wt>>>16&255,Eg[3]=wt>>>24&255,UA.check=D(UA.check,Eg,4,0)),_t=wt=0,UA.mode=4;case 4:for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.head&&(UA.head.xflags=255&wt,UA.head.os=wt>>8),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0,UA.mode=5;case 5:if(1024&UA.flags){for(;_t<16;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}UA.length=wt,UA.head&&(UA.head.extra_len=wt),512&UA.flags&&(Eg[0]=255&wt,Eg[1]=wt>>>8&255,UA.check=D(UA.check,Eg,2,0)),_t=wt=0}else UA.head&&(UA.head.extra=null);UA.mode=6;case 6:if(1024&UA.flags&&(xi<(ho=UA.length)&&(ho=xi),ho&&(UA.head&&(Ya=UA.head.extra_len-UA.length,UA.head.extra||(UA.head.extra=new Array(UA.head.extra_len)),E.arraySet(UA.head.extra,ii,Gi,ho,Ya)),512&UA.flags&&(UA.check=D(UA.check,ii,ho,Gi)),xi-=ho,Gi+=ho,UA.length-=ho),UA.length))break A;UA.length=0,UA.mode=7;case 7:if(2048&UA.flags){if(xi===0)break A;for(ho=0;Ya=ii[Gi+ho++],UA.head&&Ya&&UA.length<65536&&(UA.head.name+=String.fromCharCode(Ya)),Ya&&ho>9&1,UA.head.done=!0),De.adler=UA.check=0,UA.mode=12;break;case 10:for(;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}De.adler=UA.check=LA(wt),_t=wt=0,UA.mode=11;case 11:if(UA.havedict===0)return De.next_out=Lr,De.avail_out=ar,De.next_in=Gi,De.avail_in=xi,UA.hold=wt,UA.bits=_t,2;De.adler=UA.check=1,UA.mode=12;case 12:if(Bt===5||Bt===6)break A;case 13:if(UA.last){wt>>>=7&_t,_t-=7&_t,UA.mode=27;break}for(;_t<3;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}switch(UA.last=1&wt,_t-=1,3&(wt>>>=1)){case 0:UA.mode=14;break;case 1:if(Ni(UA),UA.mode=20,Bt!==6)break;wt>>>=2,_t-=2;break A;case 2:UA.mode=17;break;case 3:De.msg="invalid block type",UA.mode=30}wt>>>=2,_t-=2;break;case 14:for(wt>>>=7&_t,_t-=7&_t;_t<32;){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if((65535&wt)!=(wt>>>16^65535)){De.msg="invalid stored block lengths",UA.mode=30;break}if(UA.length=65535&wt,_t=wt=0,UA.mode=15,Bt===6)break A;case 15:UA.mode=16;case 16:if(ho=UA.length){if(xi>>=5,_t-=5,UA.ndist=1+(31&wt),wt>>>=5,_t-=5,UA.ncode=4+(15&wt),wt>>>=4,_t-=4,286>>=3,_t-=3}for(;UA.have<19;)UA.lens[YD[UA.have++]]=0;if(UA.lencode=UA.lendyn,UA.lenbits=7,DI={bits:UA.lenbits},Ol=T(0,UA.lens,0,19,UA.lencode,0,UA.work,DI),UA.lenbits=DI.bits,Ol){De.msg="invalid code lengths set",UA.mode=30;break}UA.have=0,UA.mode=19;case 19:for(;UA.have>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(yI<16)wt>>>=Rr,_t-=Rr,UA.lens[UA.have++]=yI;else{if(yI===16){for(Ku=Rr+2;_t>>=Rr,_t-=Rr,UA.have===0){De.msg="invalid bit length repeat",UA.mode=30;break}Ya=UA.lens[UA.have-1],ho=3+(3&wt),wt>>>=2,_t-=2}else if(yI===17){for(Ku=Rr+3;_t>>=Rr)),wt>>>=3,_t-=3}else{for(Ku=Rr+7;_t>>=Rr)),wt>>>=7,_t-=7}if(UA.have+ho>UA.nlen+UA.ndist){De.msg="invalid bit length repeat",UA.mode=30;break}for(;ho--;)UA.lens[UA.have++]=Ya}}if(UA.mode===30)break;if(UA.lens[256]===0){De.msg="invalid code -- missing end-of-block",UA.mode=30;break}if(UA.lenbits=9,DI={bits:UA.lenbits},Ol=T(P,UA.lens,0,UA.nlen,UA.lencode,0,UA.work,DI),UA.lenbits=DI.bits,Ol){De.msg="invalid literal/lengths set",UA.mode=30;break}if(UA.distbits=6,UA.distcode=UA.distdyn,DI={bits:UA.distbits},Ol=T(W,UA.lens,UA.nlen,UA.ndist,UA.distcode,0,UA.work,DI),UA.distbits=DI.bits,Ol){De.msg="invalid distances set",UA.mode=30;break}if(UA.mode=20,Bt===6)break A;case 20:UA.mode=21;case 21:if(6<=xi&&258<=ar){De.next_out=Lr,De.avail_out=ar,De.next_in=Gi,De.avail_in=xi,UA.hold=wt,UA.bits=_t,M(De,ln),Lr=De.next_out,ws=De.output,ar=De.avail_out,Gi=De.next_in,ii=De.input,xi=De.avail_in,wt=UA.hold,_t=UA.bits,UA.mode===12&&(UA.back=-1);break}for(UA.back=0;Pg=(xg=UA.lencode[wt&(1<>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(Pg&&!(240&Pg)){for(rc=Rr,Wm=Pg,XQ=yI;Pg=(xg=UA.lencode[XQ+((wt&(1<>rc)])>>>16&255,yI=65535&xg,!(rc+(Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=rc,_t-=rc,UA.back+=rc}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,UA.length=yI,Pg===0){UA.mode=26;break}if(32&Pg){UA.back=-1,UA.mode=12;break}if(64&Pg){De.msg="invalid literal/length code",UA.mode=30;break}UA.extra=15&Pg,UA.mode=22;case 22:if(UA.extra){for(Ku=UA.extra;_t>>=UA.extra,_t-=UA.extra,UA.back+=UA.extra}UA.was=UA.length,UA.mode=23;case 23:for(;Pg=(xg=UA.distcode[wt&(1<>>16&255,yI=65535&xg,!((Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}if(!(240&Pg)){for(rc=Rr,Wm=Pg,XQ=yI;Pg=(xg=UA.distcode[XQ+((wt&(1<>rc)])>>>16&255,yI=65535&xg,!(rc+(Rr=xg>>>24)<=_t);){if(xi===0)break A;xi--,wt+=ii[Gi++]<<_t,_t+=8}wt>>>=rc,_t-=rc,UA.back+=rc}if(wt>>>=Rr,_t-=Rr,UA.back+=Rr,64&Pg){De.msg="invalid distance code",UA.mode=30;break}UA.offset=yI,UA.extra=15&Pg,UA.mode=24;case 24:if(UA.extra){for(Ku=UA.extra;_t>>=UA.extra,_t-=UA.extra,UA.back+=UA.extra}if(UA.offset>UA.dmax){De.msg="invalid distance too far back",UA.mode=30;break}UA.mode=25;case 25:if(ar===0)break A;if(ho=ln-ar,UA.offset>ho){if((ho=UA.offset-ho)>UA.whave&&UA.sane){De.msg="invalid distance too far back",UA.mode=30;break}ho>UA.wnext?(ho-=UA.wnext,cl=UA.wsize-ho):cl=UA.wnext-ho,ho>UA.length&&(ho=UA.length),QC=UA.window}else QC=ws,cl=Lr-UA.offset,ho=UA.length;for(ar_i?(bt=cl[QC+YA[Bt]],Ni=_t[qu+YA[Bt]]):(bt=96,Ni=0),SA=1<>Lr)+(OA-=SA)]=Ti<<24|bt<<16|Ni,OA!==0;);for(SA=1<>=1;if(SA!==0?(wt&=SA-1,wt+=SA):wt=0,Bt++,--ln[De]==0){if(De===ii)break;De=W[oA+YA[Bt]]}if(ws{const M=new Uint8Array(D).slice(4);let T;try{T=Dl.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 I;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?Na(E).buffer:E;(I=this._socketAdapter)===null||I===void 0||I.send(P)}else this._pendingRequests.delete(g)})}_onConnect(s){const{socketId:n,event:g={}}=s||{};this._connectionId=n,this._connectionEstablishedTime=Date.now();const I=Date.now()-this._connectionStartTime,E=`${nt}.onConnect cost:${I} ms. socketID:${n} res:${JSON.stringify(g)}`;if(this._ssoLog({method:"onConnect",message:E}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const m=`${nt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:m}),gn.emitInnerEvent(Fe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:qi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(s){const n=Ia({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=Ia({servcmd:"heartbeat.alive",data:{}});try{const g=`${n.head.seq}${n.head.servcmd}`;yield this.sendPacket(n,{requestId:g,timeout:3e3})}catch(g){const I=(s=Zi.get("netWorkMonitor"))===null||s===void 0?void 0:s.isNetworkOnline,E=`${nt}.sendHeartbeat failed. isNetWorkOnline:${I} error: ${An(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=_o?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(s){const n=`${nt}.networkStatusChange ${JSON.stringify(s)}`;this._ssoLog({method:"networkStatusChange",message:n});const{isNetworkOnline:g,networkType:I}=s;g&&I!=="none"?this._handleConnectStateChange({state:qi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg})}isPrivateNetWork(){const s=Zi.get("instance")||{};return s.proxyServer&&!s.fileDownloadProxy}_handleConnectStateChange(s){const{state:n,shouldAttemptReconnect:g,shouldEmitEvent:I,reason:E}=s,m=`${nt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${g} shouldEmitEvent: ${I} reason: ${E}`;this._currentConnectState!==n&&(this._ssoLog({method:"handleConnectStateChange",message:m}),I&&(Ot.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${n}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:n}}),this._currentConnectState=n,n===Mi&&gn.emitInnerEvent(Fe.SOCKET_DISCONNECTED)),g&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(s){var n,g;const I=(g=(n=this._socketAdapter)===null||n===void 0?void 0:n._ws)===null||g===void 0?void 0:g.readyState,E=`${nt}.activityStatusChange ${JSON.stringify(s)} readyState: ${I}`;Ot.debug("activityStatusChange",E),I===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:or})}_resetReconnectDelay(){var s;Ot.debug(`${nt}._resetReconnectDelay`),fn.removeTask(Ji);const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Wo:1e3}_scheduleReconnectWithBackoff(){var s;const n=(s=Zi.get("activityMonitor"))===null||s===void 0?void 0:s.isActive;this._intendedDelay=n?Math.min(5e3,Math.max(Wo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const g=new Date().toTimeString().slice(0,8),I=`${nt}.scheduleReconnectWithBackoff timeStr: ${g} intendedDelay: ${this._intendedDelay}`;Ot.debug(I),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(s){const{method:n,message:g}=s;Ot.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(I){Ot.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${I.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){Ot.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${g.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[s,n]of this._pendingRequests.entries()){const{reject:g,timestamp:I,timeout:E}=n;Date.now()-I>=E&&(this._pendingRequests.delete(s),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),g({errorCode:Br,errorInfo:"NETWORK_TIMEOUT",data:{requestId:s}}))}}_updateIsBinarySupported(){var s;if(!((s=Zi.get("instance"))===null||s===void 0)&&s.devMode)return void(this._isBinarySupported=!1);const n=us();if((gi||It&&n==="windows"||Ys)&&(this._isBinarySupported=!1),_o){const{uniRuntimeVersion:g=""}=io.getSystemInfoSync();(function(I){const E=I.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 me={init:function(s){Zi.set("instance",s),fe.init()},destroy:function(){fe.dispose(),Zi.clear(),fn.dispose()},notificationCenter:gn,channel:fe,store:Zi,ssoLog:Ot,utils:fg,common:RA,constants:Dt},Mg=s=>typeof s=="function";function ng(s,n,g){const I=g||[];if(!s||!n)return!1;const E=Object.keys(s).filter(D=>!I.includes(D)),m=Object.keys(n).filter(D=>!I.includes(D));return E.length===m.length&&E.every(D=>!!n.hasOwnProperty(D)&&(typeof s[D]=="object"&&s[D]!==null?ng(s[D],n[D],g):s[D]===n[D]))}var vg;(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"})(vg||(vg={}));var Dn,yr=vg;(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 Ii,so=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"})(Ii||(Ii={}));var Jc=Ii;const Wg=Object.assign({},{KICKED_OUT_MULT_ACCOUNT:"multipleAccount",KICKED_OUT_MULT_DEVICE:"multipleDevice",KICKED_OUT_USERSIG_EXPIRED:"userSigExpired",KICKED_OUT_REST_API:"REST_API_Kick"}),Rg={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 Or;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(Or||(Or={}));const fc={modify:so.MESSAGE_MODIFIED,delete:so.MESSAGE_DELETED,revoke:so.MESSAGE_REVOKED};var Hc;(function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"})(Hc||(Hc={}));const rg=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Rg),{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:Or,Direction:Hc}),pu={[fc.modify]:so.TOPIC_MESSAGE_MODIFIED,[fc.delete]:so.TOPIC_MESSAGE_DELETED,[fc.revoke]:so.TOPIC_MESSAGE_REVOKED},uE={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"},wg=Object.assign({},uE),ba={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},yc=Object.assign(Object.assign(Object.assign(Object.assign({},ba),{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"}),EE=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"}),ka={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},oa={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},_g={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},iI=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},ka),{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:oa,GROUP_TIPS_OPERATION_TYPE:_g}),Cs={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},ko=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Wg),rg),wg),yc),EE),iI),Cs),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ua={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},sr={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},Pt={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"},Ht={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"},Tg={[Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Ht.USER_STATUS_UPDATE},{stepId:Ht.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Ht.UNREAD_MESSAGE_SYNC,dependency:Ht.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Ht.CONVERSATION_RECOVER},{stepId:Ht.HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.BLACKLIST_RECOVER},{stepId:Ht.FRIEND_RECOVER},{stepId:Ht.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Ht.GROUP_REVOKED_NOTICE_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.GROUP_TIPS_RECOVER,dependency:Ht.HISTORY_MESSAGE_RECOVER},{stepId:Ht.TOPIC_REQUEST_INFO_RESET},{stepId:Ht.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_RECOVER]},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Ht.C2C_HISTORY_MESSAGE_RECOVER,dependency:Ht.CONVERSATION_RECOVER},{stepId:Ht.STREAM_MESSAGE_RECOVER}],[Pt.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Ht.COMMERCIAL_CONFIG_UPDATE},{stepId:Ht.CLOUD_CONFIG_SYNC},{stepId:Ht.USER_PROFILE_SYNC},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.FRIEND_AND_BLACKLIST_SYNC},{stepId:Ht.GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_LIST_SYNC},{stepId:Ht.SIGNALING_MESSAGE_RECOVER,dependency:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Ht.GROUP_LIST_SYNC,Ht.CONVERSATION_LIST_SYNC]},{stepId:Ht.CONVERSATION_GROUP_LIST_SYNC},{stepId:Ht.CONVERSATION_GROUP_UPDATE,dependency:[Ht.CONVERSATION_LIST_SYNC,Ht.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Ht.QUALITY_REPORT}],[Pt.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.UNREAD_MESSAGE_SYNC},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_C2C_NEW_MESSAGE},{stepId:Ht.EMIT_C2C_MESSAGE_EVENT,dependency:[Ht.HANDLE_C2C_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Ht.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Ht.UNREAD_MESSAGE_SYNC]}],[Pt.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_NEW_MESSAGE},{stepId:Ht.EMIT_GROUP_MESSAGE_EVENT,dependency:[Ht.HANDLE_GROUP_NEW_MESSAGE,Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[Pt.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Ht.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Ht.EMIT_GROUP_TIPS_EVENT,dependency:[Ht.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Ht.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},oI={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},nr={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},UI=["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 Wa=Object.freeze({__proto__:null,ERROR_CODE:ua,InnerEvent:so,NEED_LOG_API:UI,OuterConstant:ko,OuterEvent:yr,PUSH:Cs,QUALITY_METRICS:oI,SDK_EDITION:sr,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:nr,SignalingEvent:Jc,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Tg,WORKFLOW_NAME:Pt,WORKFLOW_STEP:Ht}),sa,un,Sn;(function(s){s[s.USER_INITIATED=0]="USER_INITIATED",s[s.KICKED_OUT=1]="KICKED_OUT"})(sa||(sa={})),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 mu={[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"},Ng="login_online_presence_task",{ERROR:La,DESTROY:qc,FORCE_OFFLINE:FI}=so,{KICKED_OUT_MULT_ACCOUNT:dE,KICKED_OUT_MULT_DEVICE:sI,KICKED_OUT_REST_API:fu,ACCOUNT_A2KEY_EXPIRED:Sl,MSG_A2KEY_EXPIRED:Dc}=ua;class yu{init(){const{notificationCenter:n}=me;n.subscribeInnerEvent(FI,this._handleForceOfflineFromServerPush,this),n.subscribeInnerEvent(La,Dc,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,Sl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),n.subscribeInnerEvent(La,dE,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,sI,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(La,fu,this._handleForceOfflineFromResponse,this),n.subscribeInnerEvent(qc,this._dispose,this)}_handleForceOfflineFromServerPush(n){var g;if(((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)===!0){const{EventArray:I=[]}=n?.body||{};this._extractKickedOutMessages(I).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,I)=>[...g,...I.C2cNotifyMsgArray||[]],[]).filter(g=>{var I;return this._isKickedOut((I=g?.KickoutMsgNotify)===null||I===void 0?void 0:I.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:I,utils:{safeStringify:E}}=me;try{this._logKickedOutEvent(n),this._shouldLogoutAfterKickedOut(g)?yield me.login.loginAction.logout(sa.KICKED_OUT):me.login.loginAction.handleLogoutCompleted()}catch(m){I.debug("_processKickedOutReasonInfo",` fail ${E(m)}`)}finally{me.notificationCenter.emitOuterEvent(yr.KICKED_OUT,{data:{type:mu[g]},name:yr.KICKED_OUT})}})}_logKickedOutEvent(n){const{kickedOutReasonCode:g,newInstanceInfo:I={}}=n,E=`type:${mu[g]} newInstanceInfo: ${JSON.stringify(I)}`;me.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:I}=me.store.get("login")||{};return g===!0&&n===I}_dispose(){const{notificationCenter:n}=me;n.unSubscribeInnerEvent(FI,this._handleForceOfflineFromServerPush,this),n.unSubscribeInnerEvent(La,Sl,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,Dc,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,dE,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,sI,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(La,fu,this._handleForceOfflineFromResponse,this),n.unSubscribeInnerEvent(qc,this._dispose,this)}}function Du(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.wslogin",g=me.common.generateProtocolData({servcmd:n,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{timeout:9e4,requestId:I});if(E){const{HelloInterval:m,InstId:D,TinyId:M,TimeStamp:T,CustomStatus:P,PurchaseBits:W,A2Key:oA,RichMsgAuthKey:EA,ErrorCode:wA,ErrorInfo:kA,ActionStatus:YA}=E;return{helloInterval:m,instanceID:D,tinyID:M,timeStamp:T,customStatus:P,purchaseBits:W,a2Key:oA,authKey:EA,errorCode:wA,errorInfo:kA,actionStatus:YA}}})}function Ml(){const{store:s}=me;return la(s.get("instance").sdkAppId)!==ct.CHINA}function ss(s){var n;try{const g=Zi.getStorage("errorMessage");if(!s||!g)return"";const I=((n=JSON.parse(g))===null||n===void 0?void 0:n.errorMessage)||{},{code:E,replacement1:m="",replacement2:D=""}=s;if(!E)return"";const M=Ml()?`${E}_en`:`${E}_cn`;let T=I[I[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 as extends Error{constructor(n={}){n.code=n.code||n.errorCode;let{functionName:g="Unknown",code:I,message:E="",data:m="",moreMessage:D="",errorMessage:M=""}=n;M=(I?ss(n):"")||M||E;let T=I?`${g} failed. error: {"message": ${M}, "code": ${I}}`:`${g} failed. error: {"message": ${M}}`;T=`${T} ${D}`,super(),this.code=I,this.errorCode=I,this.errorMessage=M,this.message=T,this.data=m}}function td(s,n){var g;if(s&&((g=me.store.get("login"))===null||g===void 0?void 0:g.isLoggedIn)!==!0)throw new as({code:ua.USER_NOT_LOGGED_IN,functionName:n})}function nI(s,n,g){if(Array.isArray(s))for(let I=0;I{return P===(W=I,Object.prototype.toString.call(W).match(/^\[object (.*)\]$/)[1].toLowerCase());var W})){for(let W=0;W{const{interceptor:E,context:m}=I;E.apply(m,[g])})}(s)}function Sc(s,n){CE.push({interceptor:s,context:n})}function Kc(s){const{params:n,auth:g}=s;n&&typeof n=="object"&&Object.assign(vl,n),g&&typeof g=="object"&&Object.assign(id,g)}function en(s){return me.store.get("commercialConfig").get(s)}class Rs{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(n,g)=>{const I=Date.now();g?(this._stepStartTimes.set(`${n}-${g}`,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} started at ${new Date(I).toISOString()}`)):(this._workflowStartTimes.set(n,I),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] started at ${new Date(I).toISOString()}`))},success:(n,g)=>{const I=Date.now();if(g){const E=this._stepStartTimes.get(`${n}-${g}`),m=E?I-E:0;this._stepStartTimes.delete(`${n}-${g}`),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] Step ${g} completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}else{const E=this._workflowStartTimes.get(n),m=E?I-E:0;this._workflowStartTimes.delete(n),me.ssoLog.debug("_executeWorkflowStep",`[Workflow ${n}] completed successfully at ${new Date(I).toISOString()} (${m}ms)`)}},error:(n,g,I)=>{const{ssoLog:E,utils:{safeStringify:m}}=me,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(I)}`,{error:I})}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(I)}`,{error:I})}}}}static getInstance(){return Rs._instance||(Rs._instance=new Rs),Rs._instance}static setInstance(n){Rs._instance=n}init(){this._initializeWorkflows()}registerWorkflowStep(n,g,I,E){if(!this._handlers.has(n))return void me.ssoLog.debug("registerWorkflowStep",`Workflow '${n}' not defined in core`);if(!Tg[n].find(D=>D.stepId===g))return void me.ssoLog.debug("registerWorkflowStep",`Step '${g}' not defined in workflow '${n}'`);const m=this._handlers.get(n);m.has(g)||m.set(g,E?I.bind(E):I)}executeWorkflow(n,g){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(n))return;me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Started execution at ${new Date().toISOString()}`);const I=Tg[n],E={},m={cancelled:!1};this._activeWorkflows.set(n,{cancelToken:m});try{const D=new Map;I.forEach(T=>{D.set(T.stepId,T)});const M={workflowName:n,pendingSteps:new Set(I.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(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:n}).filter(EA=>!M.runningSteps.has(EA)).length===0&&M.runningSteps.size===0&&(me.ssoLog.debug("executeWorkflow",`Workflow ${n} completed with some steps skipped due to dependency failures`),T())},onError:P,onStepComplete:W})})};W()}),me.ssoLog.debug("executeWorkflow",`[Workflow ${n}] Completed execution at ${new Date().toISOString()}`)}catch(D){me.ssoLog.error("executeWorkflow",`[Workflow ${n}] Failed execution at ${new Date().toISOString()}`,{error:D})}finally{this._activeWorkflows.delete(n)}})}_executeWorkflowStep(n,g,I){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 oA=this._handlers.get(E).get(n);if(oA){const EA=yield Promise.resolve(oA({data:T,result:W}));M[n]=EA,this._logWorkflowExecution(E,n,"success")}g.completedSteps.add(n)}catch(P){const W=`[Workflow].${E}.${n}`,{errorCode:oA,errorInfo:EA=`${W} failed`}=P||{},wA=new as({functionName:W,code:oA,message:EA});me.ssoLog.error(W,EA,{error:wA}),this._logWorkflowExecution(E,n,"error",P),I.onError(P)}finally{m.delete(n),g.pendingSteps.delete(n),I.onStepComplete(),I.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Tg).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:I}=g;I.cancelled=!0,this._activeWorkflows.delete(n)}_cancelAllWorkflows(){Object.keys(Tg).forEach(n=>{this._cancelWorkFlow(n)})}_validateWorkflow(n){return Tg[n]?!!this._handlers.get(n):!1}_getExecutableSteps(n){const{pendingSteps:g,completedSteps:I,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})?I.has(T):!P;if(p(T)){if(T.filter(W=>!this._isStepRegistered({workflowName:m,stepId:W})).length>0&&P)return!1;for(const W of T)if(!I.has(W))return!1;return!0}return!1})}_isStepRegistered(n){var g;const{workflowName:I,stepId:E}=n;return(g=this._handlers.get(I))===null||g===void 0?void 0:g.has(E)}_logWorkflowExecution(n,g,I,E){this._logHandlers[I](n,g)}}const Ea=new Map,zr=({type:s,groupID:n})=>s===ko.GRP_COMMUNITY||`${n}`.startsWith(oa.COMMUNITY)&&!`${n}`.includes(oa.TOPIC),jc=(s="")=>{const n=s.startsWith("GROUP")?s.replace("GROUP",""):s;return n.startsWith(oa.COMMUNITY)&&`${n}`.includes(oa.TOPIC)},od="openim",zg="million_group_open_http_svc";function ag(s){return pA(this,void 0,void 0,function*(){const{servcmd:n,data:g}=function(m){const{data:D}=m;return hE(D)||Zg(D)}(s)?function(m){let{servcmd:D,data:M}=m;return Zg(M)?function(T){const{servcmd:P,data:W}=T;let{GroupId:oA=""}=W;const EA=oA;return[oA]=EA.split(oa.TOPIC),{servcmd:qn(P),data:Object.assign(Object.assign({},W),{GroupId:oA,TopicId:EA})}}(m):(hE(M)&&(D=qn(D)),{servcmd:D,data:M})}(s):s,I=me.common.generateProtocolData({servcmd:n,data:g}),E=`${I.head.seq}${n}`;return me.channel.sendPacket(I,{requestId:E,timeout:s.timeout})})}function hE(s){const{Type:n,GroupId:g,GroupIdList:I=[]}=s,E=g||I[0]||"";return zr({type:n,groupID:E})}function Zg(s){const{GroupId:n=""}=s;return jc(n)}function qn(s){if(s.includes(od))return s;const n=s.split(".")[1];return`${zg}.${n}`}function Ar(){var s;return(s=me.store.get("login"))===null||s===void 0?void 0:s.userId}const Ua=s=>p(s)||y(s),sd=(s,n,g,I)=>{if(!Ua(s)||!Ua(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===ko.MSG_TEXT)return n.text||"";const g=OI[s];return g?Su(g):""},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}],PI="im_sdk_config_mgr.fetch_config",aI="im_sdk_config_mgr.push_configv2",Zc="cloud-config",Xc=2996,Sa=new class{init(s){this.core=s}};function Gg(s){return pA(this,void 0,void 0,function*(){const{sdkAppId:n}=Sa.core.store.get("instance")||{},g=Sa.core.helper.generateProtocolData({servcmd:PI,data:{uint32_sdkappid:n,uint64_version:s}}),I=`${g.head.seq}${PI}`;return Sa.core.channel.sendPacket(g,{requestId:I})})}var fs=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:I,constants:{WORKFLOW_NAME:E,WORKFLOW_STEP:m},channel:D}=s;n.subscribeInnerEvent(aI,this._handlePushedConfig,this),I.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),I.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(zc),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:I,methodCallCounter:E}=this._methodCallFrequencyMap.get(s);if(Date.now()-I>1e3*g)this._methodCallFrequencyMap.set(s,{startTime:Date.now(),methodCallCounter:1});else if(E+=1,this._methodCallFrequencyMap.set(s,{startTime:I,methodCallCounter:E}),E>n)throw new this._core.helper.ChatError({code:Xc,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 Gg(this._version);s.info("_fetchCloudConfigIfLogin",n(g)),yield this._updateCloudConfig(g)}this._core.helper.taskScheduler.addTask({id:Zc,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 Gg(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:I,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(I),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(I){console.warn(I)}})}_updateCmdFreqLimitMap(s){s.forEach(n=>{this._cmdFrequencyLimitMap.set(n.cmd,{interval:n.interval,count:n.count})})}_reset(){this._core.helper.taskScheduler.removeTask(Zc),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(zc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(aI,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 I=8-g.length;for(;I;)g=`0${g}`,I--}return n+g}}const Mc={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()},xI="CommercialConfig",YI="commercial-config";var BE=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:I,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(I.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 I,E=!0;for(let m=g-1,D=0;m>=0;m--,D++)if(n.charAt(m)==="1"&&(I=D<32?new Kn(0,2**D).toString():new Kn(2**(D-32),0).toString(),!this._featureMap.get(I))){E=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${xI}.isFeatureEnabled decimalNumber:${s} key:${I} 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:I}}=this._core;try{this._isFetching=!0;const E=yield I({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:YI,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:I,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",`${xI}._parseCommercialConfig failed. Invalid message format:`,s),this._expirationTime=Date.now()+36e5):(n.warn("_parseCommercialConfig",`${xI}._parseCommercialConfig errorCode:${g} errorMessage:${I}`),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 I=null;for(let E=s.length-1,m=0;E>=0;E--,m++)if(I=m<32?new Kn(0,2**m).toString():new Kn(2**(m-32),0).toString(),s[E]==="1"){this._featureMap.set(I,!0);const D=this._getKeyByValue(Mc,I);D&&this._methodKeyMap.set(D,!0)}else{this._featureMap.set(I,!1);const D=this._getKeyByValue(Mc,I);D&&this._methodKeyMap.set(D,!1)}}else n.warn("_parsePurchaseBits",`${xI}.parsePurchaseBits invalid purchases:${g(s)}`)}_getKeyByValue(s,n){const g=Object.entries(s).find(([I,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(YI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},zC=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,channel:I}=this._core;n.subscribeInnerEvent(g.OVERLOAD_PUSH,this._handleOverLoadPush,this),n.subscribeInnerEvent(g.LOGOUT,this._reset,this),n.subscribeInnerEvent(g.DESTROY,this._dispose,this),I.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)}},eC=new class{constructor(){this.name="ConfigCenter"}install(s){Sa.init(s),fs.install(s),BE.install(s),zC.install(s)}},ZC=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={},I=new RegExp(/'/g);for(let E=0;E{var HA,se,oe;const _i=function(Ti,bt){const{From_Account:Ni,From_AccountHeadurl:gs,From_AccountNick:De,IsNeedReadReceipt:Bt,MsgBody:UA,MsgClientTime:ii,MsgRandom:ws,MsgSeq:Gi,MsgTimeStamp:Lr,SendMsgControl:xi,SupportMessageExtension:ar,To_Account:wt,TinyId:_t,MsgCheckResult:qu,CloudCustomData:ln,IsPeerRead:ho,MsgFlagBits:cl,MsgVersion:QC,EventArray:Rr}=Ti;return{from:Ni,avatar:gs,nick:De,needReadReceipt:Bt===1,readReceiptSentByPeer:ho,clientTime:ii,messageFlagBits:cl,random:ws,sequence:Gi,time:Lr,messageControlInfo:xi,isSupportExtension:ar,to:wt,tinyID:_t,checkResult:qu,cloudCustomData:ln,messageVersion:QC,eventArray:Rr,elements:bt.message.messageHelper.parseServerPushMessageElement(UA)}}(OA,YA);if(!((oe=(se=(HA=OA?.EventArray)===null||HA===void 0?void 0:HA[0])===null||se===void 0?void 0:se.hasOwnProperty)===null||oe===void 0)&&oe.call(se,"C2cNotifyMsgArray"))SA.push(...function(Ti){var bt;const Ni=[];return(bt=Ti.EventArray)===null||bt===void 0||bt.forEach(gs=>{var De,Bt;const{C2cNotifyMsgArray:UA}=gs,ii=(Bt=(De=UA?.[0])===null||De===void 0?void 0:De.WithdrawC2cMsgNotify)===null||Bt===void 0?void 0:Bt.C2cWithdrawInfoArray;Array.isArray(ii)&&Ni.push(...ii)}),Ni}(OA));else{const Ti=YA.message.messageFactory.createMessage(Object.assign(Object.assign({},_i),{conversationType:"C2C",flow:"in"})),{elements:bt}=_i;Ti.setElement(bt),LA.push(Ti)}}),{unreadMessageList:LA,revokedMessageList:SA}}(T.MsgList,n);return{syncFlag:T?.SyncFlag,unreadMessageList:EA,revokedMessageList:wA,unreadCountList:P,overflowUnreadCountList:W,cookie:T?.Cookie,groupTipList:oA}}catch(T){console.warn(T)}})}var bg,no;(function(s){s[s.START_SYNC=0]="START_SYNC",s[s.SYNCING=1]="SYNCING",s[s.SYNC_COMPLETE=2]="SYNC_COMPLETE"})(bg||(bg={})),function(s){s[s.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",s[s.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(no||(no={}));var tC=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:I=!1}=s||{};let E=bg.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?no.NEW_MESSAGE_RECEIVED:no.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),n){const{messages:YA}=this._handleNewMessageList(W);T.push(...YA)}}return n?{conversationUpdateFieldList:m,revokedMessageList:M,unreadMessageMap:this._unreadDBMessageMap,groupTipList:D,messages:T,isUnreadC2CMessage:!0}:{conversationUpdateFieldList:m,isInstantMessage:!I,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:I}=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=I.find(({conversationID:W})=>W===`${E}${M}`);P?P.unreadCount=T:I.push({conversationID:`${E}${M}`,unreadCount:T,type:E})}}),g?.forEach(D=>{const{From_Account:M,LastMsgTime:T}=D;M!==m&&(I.find(({conversationID:P})=>P===`${E}${M}`)||I.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||{},I=(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!==I){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,I=[];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)||I.push(E);else if(this._shouldStoreUnreadMessage(E)){if(n.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})}n.isMessageSentByCurrentInstance(E)&&!m||I.push(E)}}),{messages:I,conversationOptions:g}}_shouldStoreUnreadMessage(s){var n;const{conversationID:g}=s,{message:I,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!I.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 $c(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(I){console.log(I)}})}_canContinueSync({cookie:s,syncFlag:n}){var g;return n===bg.START_SYNC||n===bg.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),I=g[g.length-1];return I?.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()}},QE=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()}},pE=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,I,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})})):((I=m?.onAppShow)===null||I===void 0||I.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()}},nd=new class{init(s){const{IN_MINI_APP:n,IN_WX_MINI_PLUGIN:g}=s.helper;g||(n?pE.init(s):QE.init(s))}};const mE="none",Al="online";var gI=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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,networkType:E})}_onOnline(){this._onNetworkStatusChange({isConnected:!0,networkType:Al})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:mE})}_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()}},Mu=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:I,networkType:E}=s;(n=this._core)===null||n===void 0||n.store.set("netWorkMonitor",{isNetworkOnline:I,networkType:E}),(g=this._core)===null||g===void 0||g.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:I,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()}},vu=new class{init(s){const{IN_MINI_APP:n}=s.utils;n?Mu.init(s):gI.init(s)}},iC=new class{constructor(){this.name="SystemStateMonitor"}install(s){nd.init(s),vu.init(s)}};const Mr=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.*"]),gg="tui_room_svr.*";var vc=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=Mr}install(s){this._core=s;const{notificationCenter:n,InnerEvent:g,helper:I}=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),I.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),I.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(s){return pA(this,void 0,void 0,function*(){const n="transferBusinessCommand";try{const{serviceCommand:g=gg}=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=gg,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: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:I}=s||{},{ROOM_CUSTOM_DATA_RECEIVED:E}=n;g.emitOuterEvent(E,{name:E,data:I})}_reset(){this._transferredCommands=Mr}_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 Ru=1,Rl=2,rd=3,Zr=4,cI=5,_n="TIMCustomElem",oC="C2C",el="GROUP",ad="invite",lI="accept",Fa="cancel",sC="reject",Oa="modifyInvitation",Ir="signaling",gd=8010,wu="signaling-timeout";function ur(s){return s.filter(n=>{if(n.type===_n){const{cloudCustomData:g="",payload:{data:I=""}={}}=n,E=g.match(/"type":"tsignaling"/),m=I.match(/inviteID/),D=I.match(/actionType/);return E||m&&D}return!1})}function Rc(s){const{data:n}=s.payload;try{return JSON.parse(n)}catch(g){return console.error(g),null}}function tl(s,n){return s.toString(16).padStart(n,"0")}function kg(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=`${Ir}.updateSignaling`,{inviteID:g,inviter:I,inviteeList:E,groupID:m}=s;if(console.log(`${n} inviteID:${g} inviter:${I} 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()}},Xg=new class{init(s){this._core=s}createInviteSignaling(s){const n=this._generateInviteID(),g=this._createInviteSignalingData(Object.assign(Object.assign({},s),{inviteID:n})),{groupID:I,inviteeList:E}=g,m=I||E[0];return{signaling:this._createSignaling(g,m),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createAcceptSignaling(s){const n=this._createAcceptSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createCancelSignaling(s){const n=this._createCancelSignalingData(s),{groupID:g,inviteeList:I}=n,E=g||I[0];return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createRejectSignaling(s){const n=this._createRejectSignalingData(s),{groupID:g,inviter:I}=n,E=g||I;return{signaling:this._createSignaling(n,E),signalingData:n,signalingExtensionOptions:this._createSignalingExtensionOptions(s)}}createTimeoutSignaling(s){const{isInviter:n=!1}=s,g=this._createTimeoutSignalingData(s),{groupID:I,inviteeList:E,inviter:m}=g,D=I||(n?E[0]:m);return{signaling:this._createSignaling(g,D),signalingData:g,signalingExtensionOptions:this._createSignalingExtensionOptions(g)}}_createSignalingExtensionOptions(s){var n,g;const{data:I="",onlineUserOnly:E,inviteID:m="",offlinePushInfo:D,actionType:M}=s,T=((g=(n=Fo.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(I,M)}}_createMessageControlInfo(s,n){const g=n===cI&&!!s.match(/excludeTimeoutSignalingFromHistoryMessage/),I=!!s.match(/excludeFromHistoryMessage/)||!!s.match(/excludeOriginalSignalingFromHistoryMessage/);return{excludedFromContentModeration:!0,excludedFromUnreadCount:g||I,excludedFromLastMessage:g||I}}_createInviteSignalingData(s){const n=`${Ir}._createInviteSignalingData`,{userID:g,timeout:I=0,groupID:E="",inviteeList:m=[]}=s,D=this._core.common.getCurrentUserID(),M=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Ru,inviter:D,inviteeList:E?m:[g],timeout:I});return console.log(`${n} signalingData:`,M),M}_createAcceptSignalingData(s){const n=`${Ir}._createAcceptSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:rd,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createCancelSignalingData(s){const n=`${Ir}._createCancelSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviteeList:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Rl,groupID:m,inviter:I,inviteeList:E});return console.log(`${n} signalingData:`,D),D}_createRejectSignalingData(s){const n=`${Ir}._createRejectSignalingData`,{inviteID:g}=s,I=this._core.common.getCurrentUserID(),{inviter:E,groupID:m}=Fo.getSignaling(g),D=Object.assign(Object.assign({},this._generateBaseSignalData(s)),{actionType:Zr,groupID:m,inviter:E,inviteeList:[I]});return console.log(`${n} signalingData:`,D),D}_createTimeoutSignalingData(s){const n=`${Ir}._createTimeoutSignalingData`,{isInviter:g=!1,inviteID:I}=s,{inviteeList:E,inviter:m}=Fo.getSignaling(I),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,I,E;const{groupID:m=""}=s,D={to:n,conversationType:m?el:oC,priority:"High",payload:{data:JSON.stringify(s)}};return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageFactory)===null||E===void 0?void 0:E.createCustomMessage(D)}_generateInviteID(){return[tl(kg(32),8),tl(kg(16),4),tl(16384|kg(12),4),tl(32768|kg(14),4),tl(kg(48),12)].join("-")}_generateBaseSignalData(s){const{data:n="",inviteID:g="",groupID:I=""}=s;return{businessID:1,timeout:0,data:n,inviteID:g,groupID:I}}},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:I,signalingExtensionOptions:E}=Xg.createInviteSignaling(s),m=yield this._sendSignaling(g,E);if(m?.code===0){const{inviteID:D,timeout:M}=I;return Fo.saveSignaling(D,Object.assign(Object.assign({},I),{signaling:g})),M>0&&((n=this._core)===null||n===void 0||n.helper.taskScheduler.addOnceTask({id:`${wu}-${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:I,signalingExtensionOptions:E}=Xg.createAcceptSignaling(s),m=yield this._sendSignaling(g,E);return m?.code===0?(Fo.updateSignaling(I),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:I}=Xg.createCancelSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.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:I}=Xg.createRejectSignaling(s),E=yield this._sendSignaling(g,I);return E?.code===0?(Fo.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:I,data:E}=s;let m="";try{this._validateBeforeModifyInvitation(I);const D=Fo.getSignaling(I),{signaling:M}=D,T=yo(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 Fo.hasSignaling(I)&&Fo.saveSignaling(I,Object.assign(Object.assign({},T),{signaling:M})),P}catch(D){if(m){const{signaling:M}=Fo.getSignaling(I);M.payload.data=m}throw D}})}getSignalingInfo(s){const{ssoLog:n,utils:{safeStringify:g}}=this._core;if(ur([s]).length===0)return;const I=Rc(s),E={businessID:I.businessID||1,inviteID:I.inviteID,groupID:I.groupID||"",inviter:I.inviter||"",inviteeList:I.inviteeList||[],data:I.data||"",actionType:I.actionType||Ru,timeout:I.timeout||0};return n.debug(`${Ir} getSignalingInfo ${g(E)}`),E}addSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!0),(E=this._core)===null||E===void 0||E.notificationCenter.subscribeOuterEvent(s,n,g)}removeSignalingListener(s,n,g){var I,E;s===((I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED)&&Fo.setSignalingListenStatus(!1),(E=this._core)===null||E===void 0||E.notificationCenter.unSubscribeOuterEvent(s,n,g)}handleInvitationExpiryTimer(s){const n=Fo.getOnlineSignalingMap(),g=this._core.common.getCurrentUserID();if(!n.has(s))return;const I=n.get(s).inviter===g;this._sendTimeoutNotice({inviteID:s,isInviter:I})}_sendSignaling(s,n){return pA(this,void 0,void 0,function*(){var g,I,E;return(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.messageSender)===null||E===void 0?void 0:E.sendMessage(s,n)})}_sendTimeoutNotice(s){return pA(this,void 0,void 0,function*(){var n,g,I;this._core.ssoLog.debug("_sendTimeoutNotice",`${Ir}._sendTimeoutNotice params:${JSON.stringify(s)}`);const{isInviter:E,inviteID:m}=s,{signaling:D,signalingData:M,signalingExtensionOptions:T}=Xg.createTimeoutSignaling(s),P=yield this._sendSignaling(D,T);if(P?.code===0){const{data:W,groupID:oA,inviteeList:EA,inviter:wA}=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:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.INVITATION_TIMEOUT,data:{data:W,groupID:oA,inviteID:m,inviteeList:EA,inviter:wA,isSelfTimeout:!0,message:D}}),E?Fo.removeSignaling(m):Fo.updateSignaling(M)}})}_validateInviteId(s,n){if(!Fo.hasSignaling(n))throw new this._core.helper.ChatError({functionName:s,code:gd})}_validateProcessStatus(s){if(this._isProcessingSignaling)throw new this._core.helper.ChatError({functionName:s,message:"processing other signaling operations"})}_validateBeforeInvite(s){const n=ad,{userID:g}=s,I=this._core.common.getCurrentUserID();if(g===I)throw new this._core.helper.ChatError({functionName:n,message:`cannot invite yourself, currentUserId:${I}, inviteeId:${g}`})}_validateBeforeAccept(s){const n=lI;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:I}=Fo.getSignaling(s);if(!I.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=Fa;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviter:I}=Fo.getSignaling(s);if(I!==g){const E=`unmatched inviter:${I} and my userID:${g}`;throw new this._core.helper.ChatError({functionName:n,message:E})}}_validateBeforeReject(s){const n=sC;this._validateInviteId(n,s),this._validateProcessStatus(n);const g=this._core.common.getCurrentUserID(),{inviteeList:I}=Fo.getSignaling(s);if(!I.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=Oa;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}},wl=new class{constructor(){this._actionProcessor=new Map([[Ru,this._onNewInvitationReceived.bind(this)],[Zr,this._onInviteeRejected.bind(this)],[rd,this._onInviteeAccepted.bind(this)],[Rl,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=Rc(n);if(g){const I=this._actionProcessor.get(g.actionType);I?.(g,n)}})}_handleMessageReceived(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length!==0&&this.handleActionSignaling(n)}_handleMessageModified(s){if(!Fo.getSignalingListenStatus())return;const n=ur(s.data);n.length>0&&n.forEach(g=>{const I=Rc(g);I&&this._onInvitationModified(I,g)})}_onNewInvitationReceived(s,n){var g,I;const E=`${Ir}._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 oA=Fo.getSignaling(m);oA!==s&&(oA||Fo.saveSignaling(m,Object.assign(Object.assign({},s),{signaling:n})),P>0&&((g=this._core)===null||g===void 0||g.helper.taskScheduler.addOnceTask({id:`${wu}-${m}`,intervalMs:1e3*P,callback:za.handleInvitationExpiryTimer.bind(za,m)})),this._emitEvent({name:(I=this._core)===null||I===void 0?void 0:I.SignalingEvent.NEW_INVITATION_RECEIVED,data:Object.assign(Object.assign({},this._generateBaseEmitData(s)),{inviteeList:D})}))}_onInviteeRejected(s){var n;const g=`${Ir}._onInviteeRejected`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeRejected",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInviteeAccepted`,{inviteID:I,inviter:E,groupID:m,inviteeList:D}=s,M=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInviteeAccepted",`${g} inviteID:${I} hasInviteID:${M} inviter:${E} groupID:${m}`),M&&(Fo.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=`${Ir}._onInvitationCancelled`,{inviteID:I,inviter:E,groupID:m}=s,D=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationCancelled",`${g} inviteID:${I} hasInviteID:${D} inviter:${E} groupID:${m}`),D&&(Fo.removeSignaling(I),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=`${Ir}._onInvitationTimeout`,{inviteID:I,inviteeList:E}=s,m=Fo.hasSignaling(I);this._core.ssoLog.debug("_onInvitationTimeout",`${g} inviteID:${I} hasInviteID:${m} data:${s.data}`),m&&(Fo.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 I=`${Ir}._onInvitationModified`,{inviteID:E,data:m}=s,D=Fo.hasSignaling(E);this._core.ssoLog.debug("_onInvitationModified",`${I} inviteID:${E} data:${m}`),D&&(Fo.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:I,data:E}=s;return{inviteID:n,inviter:g,groupID:I,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)}},Xr=new class{constructor(){this._offlineSignalingMap=new Map}init(s){this._core=s;const{notificationCenter:n,helper:g,constants:{InnerEvent:I,WORKFLOW_STEP:E,WORKFLOW_NAME:m}}=s;n.subscribeInnerEvent(I.DESTROY,this._dispose,this),n.subscribeInnerEvent(I.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&&Fo.getSignalingListenStatus()))return;const g=ur([...n.values()]);if(g.length!==0&&(g.forEach(I=>{this._handleC2CActionType(I)}),this._offlineSignalingMap.size>0)){const I=this._sortOfflineSignalingByTime();wl.handleActionSignaling(I)}}_handleC2CActionType(s){const n=Rc(s);if(!n)return;const{actionType:g}=n;g===Ru?this._saveValidOfflineInvite(n,s):this._removeOfflineInvite(n)}_saveValidOfflineInvite(s,n){const{inviteID:g,inviteeList:I=[],timeout:E=0}=s,m=this._core.common.getCurrentUserID();if(!I.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 XC={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}}},Ks={invite:!0,cancel:!0,accept:!0,reject:!0,modifyInvitation:!0};var VI=new class{constructor(){this.name="Signaling"}install(s){za.init(s),wl.init(s),Xg.init(s),Fo.init(s),Xr.init(s),s.helper.registerValidateConfig({auth:Ks,params:XC})}};const Ls=new class{init(s){this.core=s}};function wc(s){let n;const{message:g}=Ls.core,{conversationID:I,messageID:E}=s;return n=g.messageDataHandler.getLocalMessageList(I).find(m=>m.ID===E),!n&&(n=g.messageDataHandler.getSparseMessageList(I).find(m=>m.ID===E)),n}function $g(s){return s.map(n=>{const{from:g,to:I,cloudCustomData:E,avatar:m,nick:D,ID:M,clientSequence:T,clientTime:P,messageRandom:W,messageSequence:oA,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:oA,MsgTimeStamp:EA,ReceiverId:I,SenderId:g,To_Account:I}})}function Er(s){var n;const{From_Account:g,From_AccountHeadurl:I,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:I,nick:E,clientTime:D,time:P,tinyID:W,random:oA,sequence:EA,to:T,groupID:m,clientSequence:M,_elements:(n=s.MsgBody)===null||n===void 0?void 0:n.map(wA=>{const{MsgType:kA}=wA;return Ls.core.message.messageFactory.getElementClass(kA).parseServerPushElement(wA)})}}var Pr,Za;(function(s){s.MSG_TEXT="TIMTextElem",s.MSG_CUSTOM="TIMCustomElem",s.MSG_LOCATION="TIMLocationElem",s.MSG_FACE="TIMFaceElem",s.MSG_STREAM="TIMStreamElem"})(Pr||(Pr={})),function(s){s[s.FORWARD=0]="FORWARD",s[s.BACKWARD=1]="BACKWARD"}(Za||(Za={}));const fE="MSG_REACTION",nC="MSG_EXT",$C=0,ro=1,_c={ZH_CN:"zh (cmn-Hans-CN)",EN_US:"en-US",YUE_HK:"yue-Hant-HK",JA_JP:"ja-JP",ZH_PY:"zh-PY"},_l="16k_zh",rC="16k_en",aC="16k_yue",Tl="16k_ja",JI="16k_zh-PY",II={[_c.ZH_CN]:_l,[_c.EN_US]:rC,[_c.YUE_HK]:aC,[_c.JA_JP]:Tl,[_c.ZH_PY]:JI},uI=/\.(wav|pcm|ogg-opus|speex|silk|mp3|m4a|aac|amr)/,yE={READ:0,UNREAD:1},Nl=1,Gl=2,Lg=3;var Ac;(function(s){s.IN="in",s.OUT="out"})(Ac||(Ac={}));const cd=16,DE=17;var Tc;(function(s){s[s.DATA=0]="DATA",s[s.REVOKED=1]="REVOKED"})(Tc||(Tc={}));var HI;(function(s){s[s.NORMAL=0]="NORMAL",s[s.TIMEOUT=1]="TIMEOUT"})(HI||(HI={}));const co="StreamMsg.PushStreamHttp";var SE=new class{constructor(){this._reactionsMap=new Map}init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:I},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(I,E,this._handleReactionUpdated,this),g.subscribeInnerEvent(I,m,this._handleReactionSync,this)}addMessageReaction(s,n){return pA(this,void 0,void 0,function*(){const{OuterConstant:g,ssoLog:I,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:${n}`;try{return this._recordMessageReactedByMe(D,n),M===g.CONV_C2C?yield function(YA,LA){return pA(this,void 0,void 0,function*(){var SA;const{from:OA,to:HA,clientSequence:se,random:oe,time:_i,reactionID:Ti}=YA,bt={From_Account:OA,To_Account:HA,MsgKey:`${se}_${oe}_${_i}`,Reaction:Ti,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_add",data:bt})})}({from:T,to:P,clientSequence:W,random:oA,time:EA,reactionID:n},this._core):M===g.CONV_GROUP&&(yield function(YA,LA){return pA(this,void 0,void 0,function*(){var SA;const{to:OA,reactionID:HA,sequence:se}=YA,oe={GroupId:OA,MsgSeq:se,Reaction:HA,Add_Account:[(SA=LA.store.get("login"))===null||SA===void 0?void 0:SA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_add",data:oe})})}({to:P,reactionID:n,sequence:wA},this._core)),{code:0,successLog:{message:kA}}}catch(YA){this._removeMyReactionRecord(D,n);const{errorCode:LA}=YA||{};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:I}=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:${n}`;try{return this._removeMyReactionRecord(m,n),D===g.CONV_C2C?yield function(kA,YA){return pA(this,void 0,void 0,function*(){var LA;const{from:SA,to:OA,clientSequence:HA,random:se,time:oe,reactionID:_i}=kA,Ti={From_Account:SA,To_Account:OA,MsgKey:`${HA}_${se}_${oe}`,Reaction:_i,Del_Account:[(LA=YA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_del",data:Ti})})}({from:M,to:T,clientSequence:P,random:W,time:oA,reactionID:n},this._core):D===g.CONV_GROUP&&(yield function(kA,YA){return pA(this,void 0,void 0,function*(){var LA;const{to:SA,reactionID:OA,sequence:HA}=kA,se={GroupId:SA,MsgSeq:HA,Reaction:OA,Del_Account:[(LA=YA.store.get("login"))===null||LA===void 0?void 0:LA.userId]};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_del",data:se},YA)})}({to:T,reactionID:n,sequence:EA},this._core)),{code:0,successLog:{message:wA}}}catch(kA){const{errorCode:YA}=kA||{};throw new I.ChatError({functionName:"removeMessageReaction",code:YA,moreMessage:wA})}})}getAllUserListOfMessageReaction(s){return pA(this,void 0,void 0,function*(){this._validateMessageReactionBusinessCapability();const{message:n,reactionID:g,nextSeq:I=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:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{from:YA,to:LA,clientSequence:SA,random:OA,time:HA}=oA,se={Reaction:wA,NextSeq:EA,Count:kA,From_Account:YA,To_Account:LA,MsgKey:`${SA}_${OA}_${HA}`};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_iterate",data:se})})}({message:n,reactionID:g,nextSeq:I,count:E}):yield function(W){return pA(this,void 0,void 0,function*(){const{message:oA,nextSeq:EA,reactionID:wA,count:kA}=W,{sequence:YA,to:LA}=oA,SA={Reaction:wA,NextSeq:EA,GroupId:LA,Count:kA,MsgSeq:YA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_iterate",data:SA})})}({message:n,reactionID:g,nextSeq:I,count:E}),P){const{Reaction_Account:W,NextSeq:oA}=P,EA=yield this._getUserProfileList(W);return{code:0,data:{nextSeq:oA,isCompleted:I===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:I=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:YA,to:LA,messageKeyList:SA,maxUserCountPerReaction:OA}=kA,HA={From_Account:YA,To_Account:LA,MsgKeyList:SA,Count:OA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.reaction_multi_stat",data:HA})})}({from:M,to:T,messageKeyList:W,maxUserCountPerReaction:I}):P===n.OuterConstant.CONV_GROUP&&(m=yield function(kA){return pA(this,void 0,void 0,function*(){const{groupId:YA,messageSequenceList:LA,maxUserCountPerReaction:SA}=kA,OA={GroupId:YA,MsgSeqList:LA,Count:SA};return Ls.core.common.buildAndSendPacket({servcmd:"openim_msg_ext_http_svc.group_reaction_multi_stat",data:OA})})}({groupId:T,messageSequenceList:W,maxUserCountPerReaction:I}));const{Results:oA=[]}=m||{},EA=this._extractUserIDsFromReactionResults(oA),wA=yield this._getUserProfileMap(EA);return{code:0,data:{resultList:oA.map(kA=>{const{ReactionList:YA,MsgSeq:LA,MsgKey:SA}=kA;return{messageID:this._generateMessageID({messageSequence:LA,messageKey:SA,messageIDMap:D}),reactionList:YA.map(OA=>{const{Reaction:HA,Count:se,Reaction_Account:oe,ReactedByMe:_i}=OA;return{reactionID:HA,totalUserCount:se,partialUserList:this._generatePartialUserInfo({userIDList:oe,userProfileMap:wA}),reactedByMyself:_i===1}})}})}}})}dispose(){this._reactionsMap.clear()}_extractUserIDsFromReactionResults(s){const n=[];return s?.forEach(g=>{const{ReactionList:I=[]}=g;I.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:I,avatar:E,userID:m}=g;n.set(m,{nick:I,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:I}=s,E=`${n}-${g}`,m=this._reactionsMap.get(E)||{};this._reactionsMap.set(E,Object.assign(Object.assign({},m),I))}_validateMessageReactionBusinessCapability(){const{helper:s,constants:n}=this._core;if(!s.checkBusinessCapabilityBits(fE))throw new s.ChatError({functionName:"addMessageReaction",code:n.ERROR_CODE.NO_USE,replacement1:"addMessageReaction"})}_handleReactionUpdated(s){const{MsgReactionNotifyList:n}=s,{notificationCenter:g,constants:I}=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),oA=`${T}-${P}-${W}`,EA=this._extractUserIDsFromReactionResults([{ReactionList:M}]),wA=yield this._getUserProfileMap(EA),kA=M.map(YA=>{var LA;const{Reaction:SA,Reaction_Account:OA}=YA,HA=this._generatePartialUserInfo({userIDList:OA,userProfileMap:wA}),se=OA?YA.Count:0,oe=((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:se,partialUserList:HA}}),{reactionID:SA,totalUserCount:se,partialUserList:HA,reactedByMyself:oe}});g.emitOuterEvent(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:kA}})}))}_handleReactionSync(s){var n;const{notificationCenter:g,constants:I}=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),(n=this._reactionsMap.get(EA))===null||n===void 0?void 0:n.reactionID){const wA=this._reactionsMap.get(EA);wA.reactedByMyself=M===1,g.emitOuterEvent(I.OuterEvent.MESSAGE_REACTIONS_UPDATED,{name:I.OuterEvent.MESSAGE_REACTIONS_UPDATED,data:{messageID:oA,reactionList:[wA]}})}}_generatePartialUserInfo({userIDList:s,userProfileMap:n}){const g=[];return s?.forEach(I=>{n.has(I)&&g.push(n.get(I))}),g}_generateMessageID(s){const{messageSequence:n,messageKey:g,messageIDMap:I}=s;return g?I.get(g):I.get(n)}_generateMessageKeyList(s,n){const{constants:g}=this._core,I=s[0],{conversationType:E}=I;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 n.set(oA,W),oA}):E===g.OuterConstant.CONV_GROUP&&(m=s.map(D=>{const{ID:M,sequence:T}=D;return n.set(T,M),T})),m}},Xa=new class{init(s){this._core=s;const{helper:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_MESSAGE_READ_RECEIPT:I,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,I,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:I}=this._core,E=this._filterValidMessageSendByOther(s);if(E.length===0)throw new g.ChatError({code:I.ERROR_CODE.READ_RECEIPT_MSG_LIST_EMPTY});try{const{conversationType:m}=E[0];return m===I.OuterConstant.CONV_C2C?yield function(D){return pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Ls.core,P=D[0].conversationID.replace(T.OuterConstant.CONV_C2C,""),W=D.map(EA=>{const{from:wA,to:kA,sequence:YA,random:LA,time:SA,clientTime:OA}=EA;return{From_Account:wA,To_Account:kA,MsgSeq:YA,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 pA(this,void 0,void 0,function*(){const{common:M,constants:T}=Ls.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:I}=s[0];if(I===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}=Ls.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(I){const{errorCode:E,errorInfo:m}=I;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:I,filter:E=yE.READ,cursor:m=""}=s,{conversationID:D,sequence:M,ID:T}=I,P=D.replace(n.OuterConstant.CONV_GROUP,""),W=s.count>=100?100:s.count;try{const oA=yield function(EA){return pA(this,void 0,void 0,function*(){const{sequence:wA,groupID:kA,filter:YA,cursor:LA,count:SA}=EA,OA={MsgSeq:wA,GroupId:kA,Filter:YA,Cursor:LA,Num:SA};return Ls.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:YA}=oA,LA={cursor:EA,isCompleted:wA===1,messageID:T,unreadUserIDList:[],readUserIDList:[]};return E===yE.READ?LA.readUserIDList=YA.map(SA=>SA.Read_Account):E===yE.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 n=[],{constants:g,helper:I}=this._core,{C2cMsgInfo:E,PeerReadTime:m,Peer_Account:D}=s;if(I.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=wc({conversationID:M,messageID:EA});wA&&!wA.readReceiptInfo.isPeerRead&&(wA.readReceiptInfo.isPeerRead=!0,wA.readReceiptInfo.timestamp=m,n.push({userID:D,messageID:EA,isPeerRead:!0,timestamp:m}))}),this._emitReadReceiptEventIfNeed(n)}_updateGroupMessagesReadReceiptInfo(s){const{messageList:n,readReceiptList:g}=s,I=new Map;n.forEach(E=>{I.set(E.sequence,E)}),g?.forEach(E=>{if(E.Code===0){const{MsgSeq:m,ReadNum:D,UnreadNum:M}=E,T=I.get(m);T&&(T.readReceiptInfo.readCount=D,T.readReceiptInfo.unreadCount=M)}})}_handleGroupMessageReadReceipt(s){const n=[],{constants:g}=this._core,{GroupTips:I}=s;I.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}`,YA=wc({conversationID:M,messageID:kA}),LA={groupID:D,messageID:kA,readCount:0,unreadCount:0};YA&&(typeof EA=="number"&&(YA.readReceiptInfo.readCount=EA,LA.readCount=EA),typeof wA=="number"&&(YA.readReceiptInfo.unreadCount=wA,LA.unreadCount=wA),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:I,status:E}=g;return I===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:I}=this._core;I.unSubscribeInnerEvent(s,n,this._handleC2CMessageReadReceipt,this),I.unSubscribeInnerEvent(s,g,this._handleGroupMessageReadReceipt,this)}};function qI(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Ls.core,{from:E,to:m,clientSequence:D,random:M,time:T}=s;return I({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 _u(s,n,g){return pA(this,void 0,void 0,function*(){const{common:{buildAndSendPacket:I}}=Ls.core,{to:E,sequence:m}=s;return I({servcmd:"openim_msg_ext_http_svc.group_set_key_values",data:{GroupId:E,MsgSeq:m,OperateType:g,ExtensionList:n}})})}var Nc=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:I,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(I,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:I}=this._core,{ID:E,conversationID:m,sequence:D,time:M,conversationType:T}=s;let P=n;n.length>20&&(P=n.slice(0,20),I.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 qI(s,W,Nl):T===g.CONV_GROUP&&(EA=yield _u(s,W,Nl)),EA){const{resultList:wA,successCount:kA,failureCount:YA}=this._handleModifyMessageExtensions(s,EA);return{code:0,data:{extensions:wA},successLog:{message:`${oA} successCount:${kA} failCount:${YA}`}}}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 pA(this,void 0,void 0,function*(){const{utils:{isUndefined:n}}=this._core;this._validateMessageExtensionBusinessCapability("getMessageExtensions");const{conversationID:g,ID:I,sequence:E,time:m}=s,D=`convID:${g} messageID:${I} sequence:${E} time:${m}`;try{let M;this._completedFetchExtensions.has(I)&&(M=this._extensionsLatestSequenceMap.get(I));const T=yield this._fetchMessageExtensions(s,M);return n(M)&&T.length>1&&this._completedFetchExtensions.add(I),{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:I}}=this._core,{conversationType:E,conversationID:m,sequence:D,ID:M,time:T}=s;let P=Lg;const W=[];g(n)||(P=Gl,n?.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===I.CONV_C2C?wA=yield qI(s,EA,P):E===I.CONV_GROUP&&(wA=yield _u(s,EA,P)),wA){const{resultList:kA,successCount:YA,failureCount:LA}=this._handleModifyMessageExtensions(s,wA);return{code:0,data:{extensions:kA},successLog:{message:`${oA}successCount:${YA} 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:n,LOGOUT:g},InnerEventSubType:{MESSAGE_EXTENSIONS_UPDATED:I}}=this._core;s.unSubscribeInnerEvent(n,I,this._handleMessageExtensionsNotify,this),s.subscribeInnerEvent(g,this.reset,this)}_handleModifyMessageExtensions(s,n){const{ID:g}=s,{Seq:I}=n,E=n.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,I),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(I=>{const{key:E,seq:m,value:D=""}=I;g?.set(E,{value:D,seq:m})})}_fetchMessageExtensions(s,n){return pA(this,void 0,void 0,function*(){const{constants:{OuterConstant:g},utils:{isEmpty:I}}=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}}=Ls.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,n):m===g.CONV_GROUP&&(E=yield function(M,T){const{common:{buildAndSendPacket:P}}=Ls.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,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 oA=[];if(this._messageExtensionsMap.has(D)){const EA=this._messageExtensionsMap.get(D);EA?.forEach((wA,kA)=>{const{value:YA}=wA;I(YA)||oA.push({key:kA,value:YA})})}return oA}}catch(E){throw E}})}_clearLocationExtensions(s,n){if(!(n<=0)&&this._messageExtensionsMap.has(s)){const g=this._messageExtensionsMap.get(s);g?.forEach((I,E)=>{I.seq<=n&&g.delete(E)})}}_generateServerExtensions(s,n){const{ID:g}=s;if(this._messageExtensionsMap.has(g)){const I=this._messageExtensionsMap.get(g);return n.map(E=>{var m;const{key:D,value:M}=E;let T=0;return I?.has(D)&&(T=(m=I.get(D))===null||m===void 0?void 0:m.seq),{Key:D,Value:M,Seq:T}})}return n.map(I=>({Key:I.key,Value:I.value,Seq:0}))}_validateMessageExtensionBusinessCapability(s){const{helper:n,constants:g}=this._core;if(!n.checkBusinessCapabilityBits(nC))throw new n.ChatError({functionName:s,code:g.ERROR_CODE.NO_USE,replacement1:s})}_handleMessageExtensionsNotify(s){const{SetKVInfo:n,DeleteKVInfo:g,ClearKVInfo:I,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===Nl?this._handleMessageExtensionsUpdated({messageID:EA,updateMessageExtensionsInfo:n}):E===Gl?this._handleMessageExtensionsDeleted({messageID:EA,deleteMessageExtensionsInfo:g}):E===Lg&&this._handleMessageExtensionsCleared({messageID:EA,clearMessageExtensionsInfo:I})}_handleMessageExtensionsUpdated(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_UPDATED,{name:g.MESSAGE_EXTENSIONS_UPDATED,data:{messageID:I,extensions:m}})}_handleMessageExtensionsDeleted(s){const{notificationCenter:n,OuterEvent:g}=this._core,{messageID:I,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(I,T)}),n.emitOuterEvent(g.MESSAGE_EXTENSIONS_DELETED,{name:g.MESSAGE_EXTENSIONS_DELETED,data:{messageID:I,keyList:m}})}_handleMessageExtensionsCleared(s){const{notificationCenter:n,OuterEvent:{MESSAGE_EXTENSIONS_DELETED:g},utils:{isEmpty:I}}=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&&!I(P.value)&&D.push(W)}),this._clearLocationExtensions(E,T)}),n.emitOuterEvent(g,{name:g,data:{messageID:E,keyList:D}})}};const EI={key:"message",required:!0,rules:["object"],allowEmpty:!1,customValidator:s=>{const{constants:{OuterConstant:n}}=Ls.core;return s.status!==n.MessageStatus.SUCCESS?"message is not success":s.isSupportExtension===!0||"message is not support extension"}},il={setMessageExtensions:[EI,{key:"extensions",required:!0,rules:["array"],allowEmpty:!1}],getMessageExtensions:[EI],deleteMessageExtensions:[EI]},ol=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 I;return typeof g?.text!="string"||typeof g.text=="string"&&((I=g?.text)===null||I===void 0?void 0:I.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}}=Ls.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}}}),il),{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}]}),Pa=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 ME{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={From_Account:this._core.common.getCurrentUserID(),To_Account:g,MsgKeyList:I};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:I,sequence:E,time:m,random:D}=n,M={MsgInfo:{From_Account:I,To_Account:g,MsgSeq:E,MsgRandom:D,MsgTimeStamp:m}};return this._core.common.buildAndSendPacket({servcmd:"openim.msgwithdraw",data:M})})}}class na{constructor(n){this._core=n}deleteMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,messageIdentifiers:I}=n,E={GroupId:g,Deleter_Account:this._core.common.getCurrentUserID(),Seqs:I};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:I}=n,E={GroupId:g,MsgSeqList:[{MsgSeq:I}]};return this._core.common.buildAndSendPacket({servcmd:"group_open_http_svc.group_msg_recall",data:E})})}}const Mn=2116;class Nr{constructor(n){this._core=n}generateRevokeMessage(n){const{conversationID:g,sequence:I,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:I,random:E,revoker:T}),P||(P={conversationID:g,sequence:I},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(I=>I.revoker);try{const I=yield this._fetchUserInfos(g);I&&n.forEach(E=>{const{revoker:m}=E;I[m]&&(E.revokerInfo.nick=I[m].nick||"",E.revokerInfo.avatar=I[m].avatar||"",E.revokerInfo.userID=m)})}catch(I){console.debug(I)}})}_fetchUserInfos(n){return pA(this,void 0,void 0,function*(){var g,I;const E=yield(g=this._core.user.userProfile)===null||g===void 0?void 0:g.getUserProfile({userIDList:n});return E?.data?(I=E.data)===null||I===void 0?void 0:I.reduce((m,{userID:D,nick:M,avatar:T})=>(m[D]={nick:M||"",avatar:T||""},m),{}):null})}}var sl=new class{constructor(){this._core=null,this._c2cMessageAction=null,this._groupMessageAction=null}init(s){this._core=s,this._groupMessageAction=new na(s),this._c2cMessageAction=new ME(s),this._messageHelper=new Nr(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:I,conversationType:E}=s[0],m=I.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===I&&T===E){if(!W){const kA=T==="C2C"?`${oA}_${EA}_${wA}`:String(oA);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:I,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(I)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=((n=W?.[0])===null||n===void 0?void 0:n.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,n){return pA(this,void 0,void 0,function*(){var g,I;return s.isResend=!0,s.status="unSend",(I=(g=this._core)===null||g===void 0?void 0:g.apiMap)===null||I===void 0?void 0:I.sendMessage(s,n)})}findMessage(s){return this._core.message.messageDataHandler.findMessage(s)}createQuoteMessage(s,n){const{ID:g,time:I,sequence:E}=n;return s.quoteInfo={msgID:g,messageTime:I,messageSequence:E},s}_handleDeleteMessageSuccess(s){if(s.length===0)return;const{message:{messageDataHandler:n},common:{isTopic:g},notificationCenter:I,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)?I.emitInnerEvent(E.TOPIC_MESSAGE_DELETED,m):I.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:I,sequence:E,random:m}=s;this._core.message.messageDataHandler.revokeMessage({conversationID:I,sequence:E,random:m,revoker:g}),yield this._messageHelper.updateRevokerInfo([s])})}};class bl{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Index:I,Data:E}=g;return new bl({index:I,data:E})}constructor(n){this.type=Pr.MSG_FACE;const{index:g,data:I}=n;this.content={index:g,data:I}}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||{},I=g?this.payload:this.content,{index:E,data:m}=I;return{MsgType:this.type,MsgContent:{Index:E,Data:m}}}}class Gc{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Desc:I,Longitude:E,Latitude:m}=g;return new Gc({description:I,longitude:E,latitude:m})}constructor(n){this.type=Pr.MSG_LOCATION;const{description:g,longitude:I,latitude:E}=n;this.content={description:g,longitude:I,latitude:E}}validateBeforeSend(){return{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{description:E,longitude:m,latitude:D}=I;return{MsgType:this.type,MsgContent:{Desc:E,Longitude:m,Latitude:D}}}}class vE{static parseServerPushElement(n){const{MsgContent:g={}}=n,{StreamMsgID:I,CompatibleText:E,Markdown:m,BinaryData:D,ErrorCode:M,ErrorMsg:T}=g;return new vE({streamMessageID:I,compatibleText:E,markdown:m,binaryData:D,errorCode:M,errorMessage:T})}constructor(n){this.type=Pr.MSG_STREAM,this.content={streamMessageID:"",compatibleText:"",errorCode:0,errorMessage:"",isStreamEnded:!1},this._chunks=[],this._latestIndex=0;const{streamMessageID:g,compatibleText:I,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=I,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),I=this._getMaxRevokedChunkIndex(g);I>=0&&(this._chunks=[],this._latestIndex=I,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||{},I=g?this.payload:this.content,{streamMessageID:E,chunks:m}=I,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 I=[];let E=g;for(const m of n){if(m.index>E)break;m.index===E&&(I.push(m),E++)}return I}_mergeAndSortChunks(n){const g=new Map;this._chunks.forEach(I=>{g.set(I.index,I)}),n.forEach(I=>{g.set(I.index,I)}),this._chunks=Array.from(g.values()).sort((I,E)=>I.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),I=new Uint8Array(g);let E=0;for(const m of n)I.set(m,E),E+=m.length;this.content.binaryData=I}}_getMaxRevokedChunkIndex(n){let g=-1;for(let I=0;Ig&&(g=E.index)}return g}_getValidChunks(n){const g=n.filter(I=>I.eventType===Tc.DATA&&I.index>this._latestIndex);return this._filterContinuousChunks(g,this._latestIndex+1)}}var bc=new class{init(s){this._core=s,s.message.messageFactory.registerElementClass(Pr.MSG_FACE,bl),s.message.messageFactory.registerElementClass(Pr.MSG_LOCATION,Gc),s.message.messageFactory.registerElementClass(Pr.MSG_STREAM,vE),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||{},I=new bl({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(I),m}createTextAtMessage(s){const{atUserList:n}=s?.payload||{},g=this._core.apiMap.createTextMessage(s),{OuterConstant:I}=this._core;if(!g)return null;if(Array.isArray(n)){const E=[],m=[];n.forEach(D=>{D!==I.MSG_AT_ALL?(E.push({GroupAtAllFlag:$C,GroupAt_Account:D}),m.push(D)):(E.push({GroupAtAllFlag:ro}),m.push(I.MSG_AT_ALL))}),g._groupAtInfoList=E,g.atUserList=m}return g}createForwardMessage(s){const{helper:n,OuterConstant:g}=this._core,{to:I,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 oA=this._core.common.getCurrentUserID(),EA=this._core.message.messageFactory.createMessage({to:I,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:n,longitude:g,latitude:I}=s?.payload||{},E=new Gc({description:n,longitude:g,latitude:I}),m=this._core.common.getCurrentUserID(),D=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:m}));return D.setElement(E),D}};let Tu=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{C2C_REVOKED_MESSAGE:I},helper:{registerWorkflowStep:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(g,I,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:I,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,YA=this._messageHelper.generateRevokeMessage({conversationID:wA,sequence:T,random:M,revoker:oA,revokeReason:kA});n.push(YA)}),n.length>0&&(yield this._messageHelper.updateRevokerInfo(n),g.emitOuterEvent(I.MESSAGE_REVOKED,{name:I.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)}},gC=class{init(s){this._messageHelper=new Nr(s),this._core=s;const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g},InnerEventSubType:{GROUP_MESSAGE_REVOKED:I}}=s;n.subscribeInnerEvent(g,I,this._handleGroupNotifyMessage,this)}_handleGroupNotifyMessage(s){const{GroupTips:n}=s;n?.forEach(g=>{var I;Array.isArray((I=g?.MsgBody)===null||I===void 0?void 0:I.GroupWithdrawInfoArray)&&this._handleGroupRevokeMessage(g)})}_handleGroupRevokeMessage(s){return pA(this,void 0,void 0,function*(){try{const{RevokerInfo:n,MsgBody:{GroupWithdrawInfoArray:g},GroupInfo:I}=s,E=[],m=[],{notificationCenter:D,OuterEvent:M,utils:{isEmpty:T},common:{isCommunity:P}}=this._core;let W=!1;I&&(W=P({groupID:I.GroupId})||!T(I.TopicId)),g.forEach(oA=>{const{Random:EA,MsgSeq:wA,GroupId:kA,MsgClientTime:YA,TinyId:LA,TopicId:SA,RevokerInfo:{Revoker_Account:OA=n?.Revoker_Account||"",Reason:HA=n?.Reason||""}}=oA,se=SA?`GROUP${SA}`:`GROUP${kA}`,oe=this._messageHelper.generateRevokeMessage({conversationID:se,sequence:wA,random:EA,tinyID:LA,clientTime:YA,revoker:OA,revokeReason:HA});W?(oe.revokerInfo.nick=I.From_AccountNick,oe.revokerInfo.avatar=I.From_AccountHeadurl,E.push(oe)):m.push(oe)}),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 KI=new class{constructor(){this._c2cMessageReceiver=new Tu,this._groupMessageReceiver=new gC}init(s){this._c2cMessageReceiver.init(s),this._groupMessageReceiver.init(s)}dispose(){this._c2cMessageReceiver.dispose(),this._groupMessageReceiver.dispose()}},Ah=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:I}=s,E=yield function(m,D){return pA(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},YA=yield wA.buildAndSendPacket({servcmd:"im_open_translate.ws_batch_trans_text",data:kA});if(YA){const{CmdErrorCode:LA,TargetText:SA}=YA;return{cmdErrorCode:LA,translatedTextList:SA}}})}({sourceLanguage:n,sourceTextList:g,targetLanguage:I},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:I}=n||{};throw new this._core.helper.ChatError({functionName:"translateText",code:g,message:I})}})}},Nu=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:I=_c.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=uI.exec(E))===null||n===void 0?void 0:n[1])||"mp3",M=II[I]||JI;try{const T=yield function(P){var W;const{store:oA,common:EA}=Ls.core,{url:wA,format:kA,serverLanguageType:YA}=P,LA={BytesUrl:wA,BytesEngServiceType:YA,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(!uI.test(s))throw new this._core.common.ChatError({code:2119})}};class dI{constructor(n){const{constants:g,common:I,utils:E}=Ls.core,{CONV_C2C:m,CONV_GROUP:D}=g.OuterConstant,{ID:M,tinyID:T,from:P,to:W,clientTime:oA=I.timeManager.getServerTimeSeconds()||0,random:EA,sequence:wA,cloudCustomData:kA="",nick:YA="",avatar:LA="",clientSequence:SA,conversationType:OA,groupID:HA,_elements:se,time:oe}=n;this.ID=M||`${T}-${oA}-${EA}`,this.messageRandom=EA,this.from=P,this.messageSender=P,this.time=oe,this.messageSequence=wA,this.clientSequence=SA||wA,this.clientTime=oA,this.cloudCustomData=kA,this.messageReceiver=W,this.avatar=LA,this.nick=YA;const _i=E.deepCopyWithMethods(se);_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):HA?(this.receiverGroupID=HA,this.messageReceiver=HA):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 nl{static parseServerPushElement(n){const{MsgContent:g}=n,{MsgList:I=[],CompatibleText:E,AbstractList:m,Title:D,PbMsgKey:M,JsonMsgKey:T}=g||{},P=I.map(W=>Er(W));return new nl({messageList:P,title:D,abstractList:m,compatibleText:E,pbDownloadKey:M,downloadKey:T})}constructor(n){this.type=Ls.core.constants.OuterConstant.MSG_MERGER;const{messageList:g,title:I,abstractList:E,compatibleText:m,pbDownloadKey:D="",downloadKey:M="",version:T=0,layersOverLimit:P=!1}=n,W=[];g.forEach(oA=>{if(oA){const EA=new dI(oA);W.push(EA)}}),this.content={messageList:W,title:I,abstractList:E,compatibleText:m,version:T,downloadKey:M,pbDownloadKey:D,layersOverLimit:P}}validateBeforeSend(){const{isEmpty:n}=Ls.core.helper;return n(this.content.messageList)?{isValid:!1,error:{message:"content is invalid"}}:{isValid:!0}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{abstractList:E,compatibleText:m,downloadKey:D,layersOverLimit:M,pbDownloadKey:T,title:P,version:W,messageList:oA}=I;return{MsgType:this.type,MsgContent:{AbstractList:E,CompatibleText:m,JsonMsgKey:D,LayersOverLimit:M,PbMsgKey:T,Title:P,Version:W,MsgList:$g(oA)}}}}var cC=new class{init(s){this._core=s;const{message:n,helper:g,constants:{OuterConstant:I}}=s;n.messageFactory.registerElementClass(I.MSG_MERGER,nl),g.registerApi({apiName:"createMergerMessage",context:this}),g.registerApi({apiName:"sendMessage",context:this,matcher:E=>E[0].type===I.MSG_MERGER}),g.registerApi({apiName:"downloadMergerMessage",context:this})}createMergerMessage(s){const{common:n}=this._core;if(!s)return null;const g=new nl(s.payload),I=n.getCurrentUserID(),E=this._core.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:I}));return E.setRelayFlag(!0),E.setElement(g),E}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,I,E;try{const m=function(P){let W="utf-8";Ls.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 pA(this,void 0,void 0,function*(){const{payload:{messageList:wA}}=EA,kA={MsgList:$g(wA)};return Ls.core.common.buildAndSendPacket({servcmd:"im_long_msg.save_relay_json_msg",data:kA})})}(D),{payload:oA}=D;M=new nl(Object.assign(Object.assign({},oA),{messageList:[],downloadKey:P,pbDownloadKey:W})),D.setElement(M)}catch(P){console.error(P)}}const{data:{message:T}}=yield(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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:I,pbDownload:E,type:m,messageList:D}=g,M=yo(g,["downloadKey","pbDownload","type","messageList"]);try{const T=yield function(oA){return pA(this,void 0,void 0,function*(){return Ls.core.common.buildAndSendPacket({servcmd:"im_long_msg.get_relay_json_msg",data:{JsonMsgKey:oA}})})}(I),{MsgList:P}=T||{},W=P?.map(oA=>{const EA=Er(oA);return new dI(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:${I}`),s}catch(T){const{errorCode:P}=T;throw new this._core.helper.ChatError({functionName:"downloadMergerMessage",code:P,moreMessage:I})}})}},ra=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:I},utils:{isArray:E}}=this._core,{GroupId:m,To_Account:D}=s;s.From_Account=s.From_Account||I();let M=null;if(m){M=this._generateGroupMessage(Object.assign(Object.assign({},s),{ToGroupId:m}));const T=n.userStore.getUserProfile(I());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,I=g,E=n.messageHelper.parseServerPushMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,flow:Ac.OUT})),{elements:D}=E;return m.setElement(D),m}_generateGroupMessage(s){const{message:n,OuterConstant:{CONV_GROUP:g}}=this._core,I=g,E=n.messageHelper.parseServerGroupMessage(s),m=n.messageFactory.createMessage(Object.assign(Object.assign({},E),{conversationType:I,flow:Ac.OUT})),{elements:D}=E;return m.setElement(D),m}},ec=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:{MESSAGE_PUSH:I},InnerEventSubType:{GROUP_MESSAGE_PINNED:E}}=s;g.subscribeInnerEvent(I,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:I},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:oA}}=Ls.core,{groupID:EA,sequence:wA,isPinned:kA}=P,YA=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=YA:SA.UnPinner_Account=YA,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 pA(this,void 0,void 0,function*(){let n=[];try{const g=yield function(I){return pA(this,void 0,void 0,function*(){const{groupID:E}=I,{common:{buildAndSendPacket:m}}=Ls.core;return m({servcmd:"group_open_http_svc.get_pinned_messages",data:{GroupId:E}})})}({groupID:s});if(g){const{PinnedMsgList:I=[]}=g;n=yield this._updatePinnedMessageInfo({serverPinnedMessageList:I,groupID:s})}return{code:0,data:{messageList:n}}}catch(g){throw g}})}_handleGroupMessagePinned(s){const{message:{messageHelper:n,messageFactory:g},notificationCenter:I,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 YA=null,LA=!1;if(P===cd){LA=!0;const SA=n.parseServerGroupMessage(T);YA=g.createMessage(Object.assign(Object.assign({},SA),{conversationType:m.CONV_GROUP,flow:"in"})),YA.setElement(SA.elements),YA.pinnerInfo={userID:EA,nick:wA,avatar:kA}}else if(P===DE){const{ClientTime:SA,Random:OA,SenderTinyId:HA,ServerTime:se,MsgSeq:oe}=oA;YA={ID:`${HA}-${SA}-${OA}`,sequence:oe,random:OA,time:se,clientTime:SA}}YA&&I.emitOuterEvent(E.PINNED_GROUP_MESSAGE_UPDATED,{name:E.PINNED_GROUP_MESSAGE_UPDATED,data:{groupID:M,message:YA,isPinned:LA,operatorInfo:{userID:EA,nick:wA,avatar:kA}}})})}_findMessageBySequence(s,n){const{message:{messageDataHandler:g}}=this._core;return[...g.getLocalMessageList(s),...g.getSparseMessageList(s)].find(I=>I.sequence===n)}_updatePinnedMessageInfo(s){return pA(this,arguments,void 0,function*({serverPinnedMessageList:n,groupID:g}){const{OuterConstant:{CONV_GROUP:I},utils:{isEmpty:E}}=this._core,m=[],D=[],M=[],T=new Map,P=`${I}${g}`;for(let oA=0;oA{const{sequence:kA}=wA,YA=T.get(kA),LA=oA[YA]||{userID:YA,nick:"",avatar:""};wA.pinnerInfo=LA}),m.sort((wA,kA)=>wA.sequence-kA.sequence),m}return[]})}_fetchPinnedMessageInfo(s){return pA(this,void 0,void 0,function*(){var n,g;const{message:{messageHistory:I},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(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 pA(this,void 0,void 0,function*(){const{utils:{isEmpty:n},message:{messageHistory:g}}=this._core,{conversationID:I,messageSequenceList:E}=s;return n(E)?[]:g.getGroupRoamingMessagesByAnchor({conversationID:I,messageSequenceList:E,getType:3})})}};class cg{constructor(n){this.eventType=Tc.DATA,this.index=0,this.markdown="",this.isLast=!1,this.binaryData=null;const{EventType:g,Index:I,Markdown:E,IsLast:m,BinaryData:D}=n;this.eventType=g,this.index=I,this.markdown=E,this.isLast=m,this.binaryData=D}}var CI=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:I},common:{workflowManager:E},constants:{WORKFLOW_NAME:m,WORKFLOW_STEP:D}}=s;n.subscribeInnerEvent(co,this._handleStreamMessageChunkPush,this),n.subscribeOuterEvent(g,this._handleMessageReceived,this),n.subscribeInnerEvent(I,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:I}=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){I.error("processHistoryMessage.error",g(E))}}_handleMessageReceived(s){const n=s.data;n?.forEach(g=>{var I,E;if(this._isValidStreamMessage(g)){const{streamMessageID:m}=((E=(I=g?._elements)===null||I===void 0?void 0:I[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:I}}=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===Pr.MSG_STREAM&&!I(E)}_fetchStreamMessageChunks(s){return pA(this,void 0,void 0,function*(){var n,g;const{constants:{ERROR_CODE:I},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 oA=yield function(EA){return pA(this,void 0,void 0,function*(){const{from:wA,to:kA,streamMessageID:YA,index:LA}=EA,SA={From_Account:wA,To_Account:kA,StreamMsgID:YA,AckIndex:LA};return Ls.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===I.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:I}=this._core;g.content.isStreamEnded=!0,g.stopReason=n,this._messageMap.delete(s),I.debug("_onStreamEnded",`streamMessage end, StopReason: ${n}`)}_handleStreamMessageChunkPush(s){var n;const{ssoLog:g}=this._core,{StopReason:I,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 cg(P));M.updateChunks(T)}this._emitMessageModify(D),function(T,P){pA(this,void 0,void 0,function*(){const{common:{generateProtocolData:W},utils:{safeStringify:oA},ssoLog:EA,channel:wA}=Ls.core,kA={StreamMsgID:T,AckIndex:P};try{const YA=W({servcmd:"StreamMsg.AckHttp",data:kA});wA.sendPacket(YA)}catch(YA){EA.debug("sendStreamChunkAck",oA(YA))}})}(m,M.getLatestIndex()),M.content.isStreamEnded&&this._onStreamEnded(m,I,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 I=!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 I=Math.max(0,g.length-300);I{const LA=this._getResponseBody(kA,E,oA&&EA),SA=this._buildResponse(kA,LA);if(kA.status===200)n(null,SA);else{if(EA&&!wA.includes(EA))return s.url=this._domainName2IP(wA,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,oA&&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,HA=Math.min(Math.floor(100*OA/SA),100);s.onProgress({total:SA,loaded:OA,percent:HA/100})}),kA.send(P),kA})}_buildResponse(s,n){const g={};return s.getAllResponseHeaders().trim().split(` +`).forEach(I=>{if(I){const[E,m]=I.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 I;const{isEmpty:E,isPlainObject:m}=(I=this._core)===null||I===void 0?void 0:I.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 bu=["unknown","image","video","audio","log"];var hI=new class{init(s){this._core=s}request(s,n){var g;const{MINI_APP_NAMESPACE:I,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||"",YA={key:s.fileKey||kA,success_action_status:200,"Content-Type":""},LA={};if(m()){const[OA,HA]=T.split("?sign=");HA&&(W=`${OA}?sign=${encodeURIComponent(HA)}`,LA.sign=decodeURIComponent(HA),LA.signature=decodeURIComponent(HA))}let SA={url:W,header:M,name:"file",filePath:D,formData:Object.assign(Object.assign({},YA),LA),timeout:s.timeout||3e5};if(E){const{name:OA}=SA,HA=yo(SA,["name"]);SA=Object.assign(Object.assign({},HA),{fileName:"file",fileType:s.fileType?bu[s.fileType]:"image"})}return oA=I.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})}})),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:n,response:g,callback:I}=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?I(null,{statusCode:m,headers:E,data:Object.assign(Object.assign({},g.data),{location:n})}):I({code:m,message:JSON.stringify(g.data)},{statusCode:m,headers:E,data:void 0})}};function rl(s){return function(n){return Object.prototype.toString.call(n).match(/^\[object (.*)\]$/)[1].toLowerCase()}(s)==="file"}function Gr(s){const n=s||99999999;return Math.round(Math.random()*n)}function br(s,n=!0,g=!0){const I=Date.now();return n?g?I-s+" ms":`${Math.round((I-s)/1e3)} s`:g?I-s:Math.round((I-s)/1e3)}function lg(s){return`${Array.from({length:8},()=>Math.floor(65536*(1+Math.random())).toString(16).substring(1)).join("")}-${s}`}function rr(s,n){return Math.round(Number(s)*10**n)/10**n}function vr(s){return s<=1048576?`${rr(s/1024,1)}KB/s`:`${rr(s/1048576,1)}MB/s`}const tc="TIMImageElem",Ug="TIMSoundElem",xa="TIMFileElem",kl="TIMVideoFileElem",da="RichMediaMessagePlugin",BI=["rich.my-imcloud.com","imrich.qcloud.com"],jI=1,Ca=2,al=3,wE=255;var WI;(function(s){s.UNSENT="unSend",s.SUCCESS="success",s.FAIL="fail"})(WI||(WI={}));const _E={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\/)/},xr=Symbol("isCustomUpload");var zI,Ut=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[I,E]=n.split("?");if(!E)return I;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?`${I}?${D}`:I}(s,"authKey")}_isMiniProgramTempFile(s){return!!this.getPlatformFlags().IN_MINI_APP&&Object.values(_E).some(n=>n.test(s))}extractFileFromInput(s){const{utils:{isArray:n}}=this._core;return rl(s)?s:function(g){if(typeof g!="object"||g===null)return!1;const I=Object.getPrototypeOf(g);if(I===null)return!0;let E=I;for(;Object.getPrototypeOf(E)!==null;)E=Object.getPrototypeOf(E);return I===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:I}=((n=this._core)===null||n===void 0?void 0:n.utils)||{};return this._shouldSkipProbing()?{width:0,height:0}:I?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=BI;const g=((s=this._core)===null||s===void 0?void 0:s.store.get("cloudConfig"))||{},{file_dn_list:I}=g;if(I===void 0)return n;try{JSON.parse(I).forEach(E=>{n.includes(E)||n.push(E)})}catch(E){console.warn(E),n=BI}return n}getPlatform(){var s;return(s=this._core)===null||s===void 0?void 0:s.utils.platform}generateUUID(s,n){var g;let I=`${this.getSDKAppID()}-${this.getCurrentUserID()}-${(g=this._core)===null||g===void 0?void 0:g.utils.randomString()}`;if(n)return`${I}.${n}`;const E=s.name||s.value||s.url||s.tempFilePath,m=E&&E.slice(E.lastIndexOf(".")+1);return m&&(I=`${I}.${m}`),I}processResourceUrl(s){if(!s)return"";let n=s;const g=this.getFileDownloadProxy(),I=this.getAuthKey(),E=this.getFileDNList();return g&&(s.startsWith("http://")?n=s.replace(/^http:\/\/[^/]+/,g):s.startsWith("https://")&&(n=s.replace(/^https:\/\/[^/]+/,g))),I&&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 oA=0;oA-1?`${n}&authKey=${I}`:`${n}?authKey=${I}`),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:I,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:I,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(I=>{g.getImageInfo({src:s,success:E=>I({width:E.width,height:E.height}),fail:()=>I({width:0,height:0})})})}_shouldSkipProbing(){var s;const{IN_RN_APP:n,IS_IE:g,IE_VERSION:I,IN_WX_MINI_GAME:E}=((s=this._core)===null||s===void 0?void 0:s.utils)||{};return n||g&&I===9||E}_probeImageDimensionsWeb(s){return new Promise(n=>{const g=new Image,I=()=>{g.onload=null,g.onerror=null,g.src=""};g.onload=()=>{n({width:g.width,height:g.height}),I()},g.onerror=()=>{n({width:0,height:0}),I()},g.src=s})}},ku={exports:{}},Lu=(zI||(zI=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 I(LA,SA){var OA=LA[0],HA=LA[1],se=LA[2],oe=LA[3];HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[0]-680876936|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[1]-389564586|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[2]+606105819|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[3]-1044525330|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[4]-176418897|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[5]+1200080426|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[6]-1473231341|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[7]-45705983|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[8]+1770035416|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[9]-1958414417|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[10]-42063|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[11]-1990404162|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&se|~HA&oe)+SA[12]+1804603682|0)<<7|OA>>>25)+HA|0)&HA|~OA&se)+SA[13]-40341101|0)<<12|oe>>>20)+OA|0)&OA|~oe&HA)+SA[14]-1502002290|0)<<17|se>>>15)+oe|0)&oe|~se&OA)+SA[15]+1236535329|0)<<22|HA>>>10)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[1]-165796510|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[6]-1069501632|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[11]+643717713|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[0]-373897302|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[5]-701558691|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[10]+38016083|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[15]-660478335|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[4]-405537848|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[9]+568446438|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[14]-1019803690|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[3]-187363961|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[8]+1163531501|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA&oe|se&~oe)+SA[13]-1444681467|0)<<5|OA>>>27)+HA|0)&se|HA&~se)+SA[2]-51403784|0)<<9|oe>>>23)+OA|0)&HA|OA&~HA)+SA[7]+1735328473|0)<<14|se>>>18)+oe|0)&OA|oe&~OA)+SA[12]-1926607734|0)<<20|HA>>>12)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[5]-378558|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[8]-2022574463|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[11]+1839030562|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[14]-35309556|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[1]-1530992060|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[4]+1272893353|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[7]-155497632|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[10]-1094730640|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[13]+681279174|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[0]-358537222|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[3]-722521979|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[6]+76029189|0)<<23|HA>>>9)+se|0,HA=((HA+=((se=((se+=((oe=((oe+=((OA=((OA+=(HA^se^oe)+SA[9]-640364487|0)<<4|OA>>>28)+HA|0)^HA^se)+SA[12]-421815835|0)<<11|oe>>>21)+OA|0)^OA^HA)+SA[15]+530742520|0)<<16|se>>>16)+oe|0)^oe^OA)+SA[2]-995338651|0)<<23|HA>>>9)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[0]-198630844|0)<<6|OA>>>26)+HA|0)|~se))+SA[7]+1126891415|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[14]-1416354905|0)<<15|se>>>17)+oe|0)|~OA))+SA[5]-57434055|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[12]+1700485571|0)<<6|OA>>>26)+HA|0)|~se))+SA[3]-1894986606|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[10]-1051523|0)<<15|se>>>17)+oe|0)|~OA))+SA[1]-2054922799|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[8]+1873313359|0)<<6|OA>>>26)+HA|0)|~se))+SA[15]-30611744|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[6]-1560198380|0)<<15|se>>>17)+oe|0)|~OA))+SA[13]+1309151649|0)<<21|HA>>>11)+se|0,HA=((HA+=((oe=((oe+=(HA^((OA=((OA+=(se^(HA|~oe))+SA[4]-145523070|0)<<6|OA>>>26)+HA|0)|~se))+SA[11]-1120210379|0)<<10|oe>>>22)+OA|0)^((se=((se+=(OA^(oe|~HA))+SA[2]+718787259|0)<<15|se>>>17)+oe|0)|~OA))+SA[9]-343485551|0)<<21|HA>>>11)+se|0,LA[0]=OA+LA[0]|0,LA[1]=HA+LA[1]|0,LA[2]=se+LA[2]|0,LA[3]=oe+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,HA,se,oe,_i,Ti=LA.length,bt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(bt,E(LA.substring(SA-64,SA)));for(OA=(LA=LA.substring(SA-64)).length,HA=[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(HA[SA>>2]|=128<<(SA%4<<3),SA>55)for(I(bt,HA),SA=0;SA<16;SA+=1)HA[SA]=0;return se=(se=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),oe=parseInt(se[2],16),_i=parseInt(se[1],16)||0,HA[14]=oe,HA[15]=_i,I(bt,HA),bt}function M(LA){var SA,OA,HA,se,oe,_i,Ti=LA.length,bt=[1732584193,-271733879,-1732584194,271733878];for(SA=64;SA<=Ti;SA+=64)I(bt,m(LA.subarray(SA-64,SA)));for(OA=(LA=SA-64>2]|=LA[SA]<<(SA%4<<3);if(HA[SA>>2]|=128<<(SA%4<<3),SA>55)for(I(bt,HA),SA=0;SA<16;SA+=1)HA[SA]=0;return se=(se=8*Ti).toString(16).match(/(.*?)(.{0,8})$/),oe=parseInt(se[2],16),_i=parseInt(se[1],16)||0,HA[14]=oe,HA[15]=_i,I(bt,HA),bt}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 HA,se,oe,_i,Ti=this.byteLength,bt=LA(SA,Ti),Ni=Ti;return OA!==n&&(Ni=LA(OA,Ti)),bt>Ni?new ArrayBuffer(0):(HA=Ni-bt,se=new ArrayBuffer(HA),oe=new Uint8Array(se),_i=new Uint8Array(this,bt,HA),oe.set(_i),se)}}(),YA.prototype.append=function(LA){return this.appendBinary(W(LA)),this},YA.prototype.appendBinary=function(LA){this._buff+=LA,this._length+=LA.length;var SA,OA=this._buff.length;for(SA=64;SA<=OA;SA+=64)I(this._hash,E(this._buff.substring(SA-64,SA)));return this._buff=this._buff.substring(SA-64),this},YA.prototype.end=function(LA){var SA,OA,HA=this._buff,se=HA.length,oe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(SA=0;SA>2]|=HA.charCodeAt(SA)<<(SA%4<<3);return this._finish(oe,se),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},YA.prototype.reset=function(){return this._buff="",this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},YA.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}},YA.prototype.setState=function(LA){return this._buff=LA.buff,this._length=LA.length,this._hash=LA.hash,this},YA.prototype.destroy=function(){delete this._hash,delete this._buff,delete this._length},YA.prototype._finish=function(LA,SA){var OA,HA,se,oe=SA;if(LA[oe>>2]|=128<<(oe%4<<3),oe>55)for(I(this._hash,LA),oe=0;oe<16;oe+=1)LA[oe]=0;OA=(OA=8*this._length).toString(16).match(/(.*?)(.{0,8})$/),HA=parseInt(OA[2],16),se=parseInt(OA[1],16)||0,LA[14]=HA,LA[15]=se,I(this._hash,LA)},YA.hash=function(LA,SA){return YA.hashBinary(W(LA),SA)},YA.hashBinary=function(LA,SA){var OA=P(D(LA));return SA?kA(OA):OA},YA.ArrayBuffer=function(){this.reset()},YA.ArrayBuffer.prototype.append=function(LA){var SA,OA=wA(this._buff.buffer,LA),HA=OA.length;for(this._length+=LA.byteLength,SA=64;SA<=HA;SA+=64)I(this._hash,m(OA.subarray(SA-64,SA)));return this._buff=SA-64>2]|=HA[SA]<<(SA%4<<3);return this._finish(oe,se),OA=P(this._hash),LA&&(OA=kA(OA)),this.reset(),OA},YA.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._hash=[1732584193,-271733879,-1732584194,271733878],this},YA.ArrayBuffer.prototype.getState=function(){var LA=YA.prototype.getState.call(this);return LA.buff=EA(LA.buff),LA},YA.ArrayBuffer.prototype.setState=function(LA){return LA.buff=oA(LA.buff,!0),YA.prototype.setState.call(this,LA)},YA.ArrayBuffer.prototype.destroy=YA.prototype.destroy,YA.ArrayBuffer.prototype._finish=YA.prototype._finish,YA.ArrayBuffer.hash=function(LA,SA){var OA=P(M(new Uint8Array(LA)));return SA?kA(OA):OA},YA}()}(ku)),ku.exports),lC=tI(Lu),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?hI:Gu,(n=this.httpRequest)===null||n===void 0||n.init(s)}uploadToCOS(s){return pA(this,void 0,void 0,function*(){const n=`${da} uploadToCOS`,{ssoLog:g,utils:{safeStringify:I}}=this._core,{file:E}=s;this.uploadFileType=s.uploadFileType,g.debug("uploadToCOS",`${n} options:${I(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:${vr(1e3*E.size/P)}`;return g.debug("uploadToCOS",`${n} ok. name:${E.name} ${oA}`),{uploadOptions:D,response:T}}catch(m){throw g.warn("uploadToCOS",`${n} failed, error:${I(m)}`),m}})}_handleUploadError(s,n){var g,I;const{ChatError:E}=(g=this._core)===null||g===void 0?void 0:g.helper;if(s.statusCode===403)throw n.url,!((I=s?.data)===null||I===void 0)&&I.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:br(Date.now(),!1),uploadSpeed:vr(1e3*s.size/br(Date.now(),!1))}}_createCosOptions(s){return pA(this,void 0,void 0,function*(){const{fileName:n,resources:g,uploadMethod:I}=yield this._prepareUploadParams(s),E=this._isC2CConversation(s.message.conversationID)?1:2;try{const m=yield this._fetchCosSignatureUrl({fileType:this.uploadFileType,fileName:n,uploadMethod:I,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=!Ut.isPrivateNetWork()&&m.uploadIP;return{url:this._getRawOrUploadProxyUrl(D),fileType:this.uploadFileType,fileName:n,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 pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g,isEmpty:I}}=this._core;n.debug("_prepareUploadParams",` prepareUploadParams:${g(s)}`);const{file:E}=s,{IN_MINI_APP:m,IN_RN_APP:D}=Ut.getPlatformFlags(),M=m||D,T=M&&s.message.type!==xa,{name:P}=E,W=P.slice(P.lastIndexOf(".")),oA=`${Gr(999999)}${W}`,EA=T?E.name:oA,wA=yield this._generateHashFileName(E);return{fileName:I(wA)?lg(EA):`${wA}${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:I,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]),I||(M=yield this._generateFileNameInMiniProgram(s)),I&&(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 I="";try{I=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 lC.ArrayBuffer,oA=new FileReader,EA=setTimeout(()=>{oA.abort(),n.warn("_generateHashFileNameInWeb","File hash generation timeout"),E("")},2e3);function wA(){const kA=P*M,YA=kA+M>=s.size?s.size:kA+M;oA.readAsArrayBuffer(D.call(s,kA,YA))}oA.onload=kA=>{n.debug("_generateHashFileNameInWeb",`read chunk nr ${P+1} of ${T}`),W.append(kA.target.result),P++,P{clearTimeout(EA),m(kA)},wA()})}catch(E){n.warn("_generateHashFileNameInWeb",g(E))}return I})}_generateFileNameInMiniProgram(s){return pA(this,void 0,void 0,function*(){const{utils:{MINI_APP_NAMESPACE:n,safeStringify:g,isEmpty:I},ssoLog:E}=this._core;let m="";if(I(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:I},ssoLog:E}=this._core;let m="";if(I(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,I=Ut.isSimpleCos(),E=this._prepareCosRequestData(s),m=I?"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: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 n.debug("_fetchCosSignatureUrl",` ok. isSimpleCos:${I} 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=Ut.isSimpleCos(),I=g?(n=s?.rpt_pre_sig)===null||n===void 0?void 0:n[0]:s;if(!I)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:YA,str_snapshot_url:LA,str_file_key:SA}=I;return{uploadIP:W,preSig:oA,fileID:EA,existFlag:wA,downloadUrl:kA,uploadUrl:YA,requestSnapshotUrl:LA,fileKey:SA}}const{upload_url:E,download_url:m,snapshot_url:D,thumb_url:M,large_url:T,file_key:P}=I;return{uploadUrl:E,downloadUrl:m,requestSnapshotUrl:D,thumbUrl:M,largeUrl:T,fileKey:P}}_prepareCosRequestData(s){return Ut.isSimpleCos()?{uint32_upload_method:s.uploadMethod,uint32_platform:Ut.getPlatform(),uint32_sdkappid:Ut.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,(I,E)=>{I&&this.uploadFileTryCount=3e4}_syncSystemClock(s){var n,g,I;const E=((n=s.headers)===null||n===void 0?void 0:n.date)||((g=s.headers)===null||g===void 0?void 0:g.Date)||((I=s.error)===null||I===void 0?void 0:I.ServerTime);if(E){const m=Date.now(),D=Date.parse(E);this.systemClockOffset=D-m}}_getRawOrUploadProxyUrl(s){const n=Ut.getFileUploadProxy();let g=s;return n&&(g=s.replace(/^https:\/\/[^/]+/,n)),g}_isC2CConversation(s){return s.slice(0,3)==="C2C"}};const L=2108,sA=2251,G=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,XA=2;class Qe{constructor(n,g){this.instanceID=Gr(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=Ut.addAuthToUrl(n.imageUrl||n.url||""),this.url=Ut.addAuthToUrl(n.url||g)}setSizeType(n){this.sizeType=n}setType(n){this.type=n}setImageUrl(n){n&&(this.imageUrl=Ut.addAuthToUrl(n))}getImageUrl(){return this.imageUrl}}function Q(s){const{originUrl:n,originWidth:g,originHeight:I,min:E=198}=s,m=parseInt(g)||0,D=parseInt(I)||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 yo(M,["url"])}return M}class h{constructor(n){this._imageMemoryURL="",this._percent=0,this.type=tc;const{uuid:g,file:I,imageFormat:E,imageInfoArray:m=[],isCustomUpload:D=!1}=n;this._imageMemoryURL=this.createImageDataAsURL(I),this.content={imageFormat:E,uuid:g,imageInfoArray:[]},this[xr]=D,this.initImageInfoArray(m),this.autoFixUrl()}static parseServerPushElement(n){const{MsgContent:g}=n,{ImageFormat:I,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 h({imageFormat:I,imageInfoArray:D,uuid:m})}createImageDataAsURL(n){let g="";const{IN_MINI_APP:I,IN_RN_APP:E,IN_BROWSER:m}=Ut.getPlatformFlags();return n&&((I||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 I=0;I<3;I++){const E=n[I]||Object.assign({},g),m=new Qe(E,this._imageMemoryURL);m.setSizeType(I+1),m.setType(I),this.addImageInfo(m)}this.updateAccessSideImageInfoArray()}autoFixUrl(){const n=["http","https"];this.content.imageInfoArray.forEach(g=>{if(!g.url||g.imageUrl==="")return;const[I,...E]=g.imageUrl.split("://"),m=E.join("://");n.includes(I)||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 I;for(let E=0;E({InstanceId:g.instanceID,Type:g.sizeType,MsgType:g.type,Size:g.size,Width:g.width,Height:g.height,URL:Ut.removeAuthToUrl(g.imageUrl)}))}}const v=new class{init(s){this.core=s}},N={[jI]:"i",[al]:"a",[Ca]:"v",[wE]:"f"};let O=null,z=null;function X(s){var n;const{store:g,utils:{isNumber:I,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(I(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:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createImageMessage",context:this}),I.registerExperimentalAPI("createImageMessage",this,"createCustomUploadImageMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(tc,h),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createImageMessage(s){var n,g,I;try{const E=(n=this._core.store.get("login"))===null||n===void 0?void 0:n.userId,m=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:E})),D=this._processImage(s);s.payload.file=D;const M={imageFormat:uA.UNKNOWN,uuid:Ut.generateUUID(D),file:D,imageInfoArray:[]},T=new h(M);return m.setElement(T),this._messageOptionsMap.set(m.clientSequence,s),m}catch(E){throw E}}createCustomUploadImageMessage(s){var n,g,I,E;const{store:m,utils:{isEmpty:D}}=this._core,M=(n=m.get("login"))===null||n===void 0?void 0:n.userId,T=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:M})),{largeImageUuid:P,largeFileSize:W,largeImageWidth:oA,largeImageHeight:EA,largeImageUrl:wA,originImageUuid:kA,originFileSize:YA,originImageWidth:LA,originImageHeight:SA,originImageUrl:OA,thumbImageUuid:HA,thumbFileSize:se,thumbImageWidth:oe,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 bt=new h({imageFormat:uA.UNKNOWN,uuid:kA,imageInfoArray:[{instanceID:kA,size:YA,width:LA,height:SA,imageUrl:OA,url:OA},{instanceID:P,size:W,width:oA,height:EA,imageUrl:wA,url:wA},{instanceID:HA,size:se,width:oe,height:_i,imageUrl:Ti,url:Ti}],isCustomUpload:!0});return T.setElement(bt),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 I=yield this._performImageUpload(n,s,g),E=this._generateImageInfo(I);return n.updateImageFormat(I?.fileType),n.updateImageInfoArray(E),this._updateImageType(n.content.imageInfoArray),s})}_performImageUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:jI,file:g,to:I,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:I,height:E,smallImageUrl:m,smallImageWidth:D,smallImageHeight:M,largeImageUrl:T,largeImageWidth:P,largeImageHeight:W,imageInfoArray:oA}=s,EA=Ut.addAuthToUrl(n),wA={size:g,url:EA,width:I,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,I,E,720),this._generateThumbInfo(EA,I,E,198)]}_generateThumbInfo(s,n,g,I){return Q({originUrl:s,originWidth:n,originHeight:g,min:I})}_processImageInfoArray(s,n){let g,I,E;for(const m of s)m.type===1?(I=m,I.size=n):m.type===2?(E=m,E.size=n):(g=m,g.size=n);return[Object.assign({},g),Object.assign({},E),Object.assign({},I)]}_parseResponse(s,n){return pA(this,void 0,void 0,function*(){try{const{thumbUrl:g,largeUrl:I,downloadUrl:E}=s;if(g&&I&&(yield this._getImageInfoByUrl(g,n,"thumb"),yield this._getImageInfoByUrl(I,n,"large")),Ut.isSimpleCos()&&!Ut.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 I;try{const E=Ut.addAuthToUrl(s),{width:m=0,height:D=0}=yield Ut.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){(I=this._core)===null||I===void 0||I.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:sA});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:I}=s.payload;return I=g?this._processMiniAppImageFile(I):this._processWebImageFile(I),I}catch(g){throw g}}_processMiniAppImageFile(s){rl(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,I=Ut.extractFileFromInput(s);if(!I)throw new g({message:"Invalid file. Pass either `e.target` (from file input) or a File object"});return I}_getDownloadIP(s,n){return pA(this,void 0,void 0,function*(){const g=`${da} getDownloadIP domainName: ${s}`;try{const I=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},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(!I||!I.str_final_ip)return;console.log(`${g} ok. downloadIP:${I}`);const E=n.location.split("/");E[0]=I.str_final_ip,n.location=E.join("/")}catch(I){console.warn(I)}})}_getImageInfoArray(s,n){return pA(this,void 0,void 0,function*(){try{const g=yield function(I,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:I},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 I="";if(n.IN_MINI_APP&&(I=s.url.slice(s.url.lastIndexOf(".")+1)),n.IN_BROWSER&&(I=s.name.slice(s.name.lastIndexOf(".")+1)),iA.indexOf(I.toLowerCase())<0)throw new g.ChatError({code:G})}_checkImageSize(s){const{utils:n,helper:g,store:I}=this._core;let E=0;if(E=(n.IN_MINI_APP,s.size),E===0)throw new g.ChatError({code:L});if(E>=(X(jI)||20971520))throw new g.ChatError({code:x})}_updateImageType(s){s[1].type=XA,s[2].type=_A}_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,JA=2402,ee="2.5.0",ue="1.18.0";function He(s,n){const g=s.split("."),I=n.split("."),E=Math.max(g.length,I.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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,fileUrl:D,fileName:M,fileSize:T}=I;return{MsgType:this.type,MsgContent:{Download_Flag:m,Url:Ut.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:I}=n;return I?(g&&this._processNativeAppFile(I),{size:I.size,name:I.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=`${Gr(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)}}At=xr;var Gt=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createFileMessage",context:this}),I.registerExperimentalAPI("createFileMessage",this,"createCustomUploadFileMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(xa,st),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createFileMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={uuid:Ut.generateUUID(E),file:E},T=new st(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadFileMessage(s){var n,g,I;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:oA=""}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{};if(D(T))throw new Error("url is required");const EA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:M})),wA=new st({url:T,uuid:P,file:{size:W,name:oA},isCustomUpload:!0});return EA.setElement(wA),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],I=yield this._performFileUpload(g,s,n),E=Ut.addAuthToUrl(I?.location);return g.updateFileUrl(E),s})}_validateBeforeUploadFile(s){const{helper:{ChatError:n}}=this._core;if(!s)throw new n({code:GA});const g=X(wE)||104857600;if(s.size>g)throw new n({code:JA});if(s.size===0)throw new n({code:DA})}_performFileUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:wE,file:g,to:I,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:I,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(I||M){const P=Ut.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:I,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(I){if(!(E||m||D))throw new M({message:"Unsupported mini app environment"});const T=g.getSystemInfoSync().SDKVersion;if(E&&He(T,ee)<0)throw new M({message:`WXChooseMessageFile requires SDK version ${ee} or higher`});if(m&&He(T,ue)<0)throw new M({message:`QQChooseMessageFile requires SDK version ${ue} or higher`})}}_reset(){this._messageOptionsMap.clear()}_dispose(){this._reset();const{notificationCenter:s,InnerEvent:n}=this._core;s.unSubscribeInnerEvent(n.DESTROY,this._dispose,this)}};const xt=2108,Ui=2351,ao=2352,zi=["mp4","quicktime","mov","video"];var ui;class Oo{constructor(n){this.type=kl,this.uploadProgress=0,this[ui]=!1;const g=typeof n?.videoSecond=="number"?n?.videoSecond:0;this[xr]=n.isCustomUpload||!1,this.content={remoteVideoUrl:Ut.addAuthToUrl(n.remoteVideoUrl||n.videoUrl||""),videoFormat:n.videoFormat,videoSecond:parseInt(g?.toString(),10),videoSize:n.videoSize,videoUrl:Ut.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:Ut.addAuthToUrl(n.thumbUrl),snapshotUrl:Ut.addAuthToUrl(n.thumbUrl)}}static parseServerPushElement(n){const{MsgContent:g}=n,{VideoUrl:I,VideoFormat:E,VideoSecond:m,VideoSize:D,VideoDownloadFlag:M,VideoUUID:T,ThumbUUID:P,ThumbFormat:W,ThumbWidth:oA,SnapshotWidth:EA,ThumbHeight:wA,SnapshotHeight:kA,ThumbSize:YA,SnapshotSize:LA,ThumbDownloadFlag:SA,ThumbUrl:OA,SnapshotUrl:HA}=g;return new Oo({videoUrl:I,videoFormat:E,videoSecond:m,videoSize:D,videoDownloadFlag:M,videoUUID:T,thumbUUID:P,thumbFormat:W,thumbWidth:oA,snapshotWidth:EA,thumbHeight:wA,snapshotHeight:kA,thumbSize:YA,snapshotSize:LA,thumbDownloadFlag:SA,thumbUrl:OA,snapshotUrl:HA})}updatePercent(n){this.uploadProgress=Math.min(n,1)}updateVideoUrl(n){n&&(this.content.remoteVideoUrl=n)}updateSnapshotInfo(n){const{snapshotUrl:g,snapshotWidth:I,snapshotHeight:E}=n;Ut.isEmpty(g)||(this.content.thumbUrl=this.content.snapshotUrl=g),Ut.isEmpty(I)||(this.content.thumbWidth=this.content.snapshotWidth=Number(I)),Ut.isEmpty(E)||(this.content.thumbHeight=this.content.snapshotHeight=Number(E))}validateBeforeSend(){if(this[xr])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||{},I=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:YA,thumbSize:LA,snapshotSize:SA,thumbDownloadFlag:OA,thumbUrl:HA,snapshotUrl:se}=I;return{MsgType:this.type,MsgContent:{VideoUrl:Ut.removeAuthToUrl(E),VideoFormat:m,VideoSecond:D,VideoSize:M,VideoDownloadFlag:T,VideoUUID:P,ThumbUUID:W,ThumbFormat:oA,ThumbWidth:EA,SnapshotWidth:wA,ThumbHeight:kA,SnapshotHeight:YA,ThumbSize:LA,SnapshotSize:SA,ThumbDownloadFlag:OA,ThumbUrl:Ut.removeAuthToUrl(HA),SnapshotUrl:Ut.removeAuthToUrl(se)}}}}ui=xr;var $o,Qi=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createVideoMessage",context:this}),I.registerExperimentalAPI("createVideoMessage",this,"createCustomUploadVideoMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(kl,Oo),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createVideoMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:m})),M={videoFormat:E.videoFile.type,videoSecond:rr(E.videoFile.second,0),videoSize:E.videoFile.size,remoteVideoUrl:"",videoUrl:E.videoFile.url,videoUUID:Ut.generateUUID(E.videoFile),thumbUUID:Ut.generateUUID(E.videoFile,"jpg"),thumbWidth:E.width||200,thumbHeight:E.height||200,thumbUrl:E.thumbUrl,thumbSize:E.thumbSize,thumbFormat:"jpg"},T=new Oo(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadVideoMessage(s){var n,g,I;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:oA,videoFileSize:EA,videoType:wA,snapshotWidth:kA,snapshotHeight:YA,snapshotFileSize:LA,snapshotType:SA="jpg"}=((g=s?.payload)===null||g===void 0?void 0:g.file)||{},OA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:D})),HA=new Oo({videoFormat:wA,videoSecond:P||0,videoSize:EA,remoteVideoUrl:M,videoUrl:M,videoUUID:T,thumbUUID:oA,thumbWidth:kA||200,thumbHeight:YA||200,thumbUrl:W,thumbSize:LA,thumbFormat:SA,isCustomUpload:!0});return OA.setElement(HA),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 I=yield this._performVideoUpload(n,s,g),{location:E,snapshotInfo:m}=I,D=Ut.addAuthToUrl(E);return n.updateVideoUrl(D),Ut.isEmpty(m)||n.updateSnapshotInfo(m),s})}_validateBeforeUploadVideo(s){const{helper:{ChatError:n}}=this._core,g=X(Ca)||104857600;if(s.videoFile.size>g)throw new n({code:Ui});if(s.videoFile.size===0)throw new n({code:xt});if(zi.indexOf(s.videoFile.type)===-1)throw new n({code:ao})}_validateCustomUploadVideoMessage(s){var n;const{utils:{isEmpty:g,isNumber:I}}=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)||!I(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:I}=n,E={uploadFileType:Ca,file:g,to:I,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:I}=(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=Ut.extractFileFromInput(D);if(!T)throw new I({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(I){throw console.warn(`${da} _processFile error:`,I),I}}_processMiniVideoFile(s){const{utils:{IN_UNI_NATIVE_APP:n},helper:{ChatError:g}}=this._core;if(rl(s))throw new g({message:"FileUnsupportedInMiniApp"});Array.isArray(s.tempFiles)&&(s=s.tempFiles[0]);let I=s.tempFilePath.slice(s.tempFilePath.lastIndexOf(".")+1).toLowerCase();return n&&(I=s.fileType||I),{url:s.tempFilePath,name:s.tempFilePath.slice(s.tempFilePath.lastIndexOf("/")+1),size:s.size||1,second:s.duration||0,type:I}}_processWebVideoFile(s){const{name:n,size:g=1,duration:I=0,type:E}=s,m=E.split("/")[1];return{url:window.URL.createObjectURL(s),name:n,size:g,second:I,type:m}}_getSnapshotInfoByUrl(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core;try{n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl url:${s}`);const g={version:1,platform:Ut.getPlatform(),cover_name:lg(Gr(99999)),snapshot_url:s},I=yield function(T,P){return pA(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}=I||{};if(n.debug("_getSnapshotInfoByUrl",`${da} _getSnapshotInfoByUrl OK snapshotUrl:${E}`),Ut.isEmpty(E))return{};const m=Ut.addAuthToUrl(E),{width:D=0,height:M=0}=yield Ut.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 Ki{constructor(n){this.uploadProgress=0,this.type=Ug,this[$o]=!1,this[xr]=n.isCustomUpload||!1,this.content={downloadFlag:2,second:n.second,size:n.size,url:Ut.generateURL(n.url,{needAddAuthToUrl:!this[xr]}),remoteAudioUrl:Ut.addAuthToUrl(n.url||""),uuid:n.uuid}}static parseServerPushElement(n){const{MsgContent:g}=n,{Url:I,Download_Flag:E,Second:m,Size:D,UUID:M}=g;return new Ki({url:I,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[xr])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||{},I=g?this.payload:this.content,{uuid:E,downloadFlag:m,remoteAudioUrl:D,size:M,second:T}=I;return{MsgType:this.type,MsgContent:{Url:Ut.removeAuthToUrl(D),Download_Flag:m,Second:T,Size:M,UUID:E}}}}$o=xr;const js=2108,we=2300,vt=2301;var FA=new class{constructor(){this._messageOptionsMap=new Map}init(s){var n;this._core=s;const{notificationCenter:g,helper:I,InnerEvent:E,message:m}=s;I.registerApi({apiName:"createAudioMessage",context:this}),I.registerExperimentalAPI("createAudioMessage",this,"createCustomUploadAudioMessage"),(n=m?.messageFactory)===null||n===void 0||n.registerElementClass(Ug,Ki),g.subscribeInnerEvent(E.DESTROY,this._dispose,this)}createAudioMessage(s){var n,g,I;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=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageFactory)===null||I===void 0?void 0:I.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:Ut.generateUUID(E)},T=new Ki(M);return D.setElement(T),this._messageOptionsMap.set(D.clientSequence,s),D}catch(E){throw E}}createCustomUploadAudioMessage(s){var n,g,I;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)||{},oA=(I=m.messageFactory)===null||I===void 0?void 0:I.createMessage(Object.assign(Object.assign({},s),{from:D})),EA=new Ki({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 pA(this,void 0,void 0,function*(){const{ssoLog:n,utils:{safeStringify:g}}=this._core;n.debug("upload",`${da} uploadAudio message:${g(s)}`);const{file:I}=this._messageOptionsMap.get(s.clientSequence).payload;this._validateBeforeUploadAudio(I);const E=s.getElements()[0],m=yield this._performAudioUpload(E,s,I),D=Ut.addAuthToUrl(m?.location);return E.updateAudioUrl(D),s})}_validateBeforeUploadAudio(s){const{helper:{ChatError:n},store:g}=this._core;if(!s)throw new n({code:we});const I=X(al)||20971520;if(s.size>I)throw new n({code:vt});if(s.size===0)throw new n({code:js})}_performAudioUpload(s,n,g){return pA(this,void 0,void 0,function*(){const{to:I}=n,E={uploadFileType:al,file:g,to:I,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:I}=(n=this._core)===null||n===void 0?void 0:n.utils;return g?this._processMiniFile(s):I?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:I,uuid:E,duration:m}=((n=s?.payload)===null||n===void 0?void 0:n.file)||{};if(g(I)||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 Wt={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:Wt,createAudioMessage:Wt,createVideoMessage:Wt,createFileMessage:Wt},Zt={createImageMessage:!0,createAudioMessage:!0,createVideoMessage:!0,createFileMessage:!0},Is={[tc]:rA,[xa]:Gt,[kl]:Qi,[Ug]: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:I,MSG_VIDEO:E}}}=s;v.init(s),rA.init(s),Gt.init(s),Qi.init(s),FA.init(s),q.init(s),Ut.init(s),s.helper.registerApi({apiName:"sendMessage",context:this,matcher:m=>[n,g,I,E].includes(m[0].type)}),s.helper.registerValidateConfig({auth:Zt,params:En})}sendMessage(s,n){return pA(this,void 0,void 0,function*(){var g,I,E;try{return this._isCustomUpload(s)||(yield this._upload(s)),yield(E=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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 I=Is[s.type];I&&(yield I.upload(s),n.info("_upload",` type:${s.type}`))}catch(I){throw s.status=WI.FAIL,I instanceof Error&&(I.data={message:s}),this._core.message.messageDataHandler.storeConversationMessage(s),I}})}_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[xr])===!0}};const Co=new class{init(s){this.core=s}};class Et{constructor(n){this.conversationID=n.conversationID||"",this.unreadCount=n.unreadCount||0,this.type=n.type||"",this.lastMessage=Co.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:I}}}=Co;I(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),I(this.groupProfile)&&(this.groupProfile={groupID:this.conversationID.replace(g.CONV_GROUP,""),selfInfo:{},lastMessage:{},type:this.subType}))}updateUnreadCount(n){var g;const{core:{OuterConstant:I,utils:{isUndefined:E},store:m}}=Co,{nextUnreadCount:D,isFromGetConversations:M,isUnreadC2CMessage:T}=n;if(E(D))return;if(this.subType===I.GRP_AVCHATROOM)return void(this.unreadCount=0);if(M&&this.type===I.CONV_GROUP)return void(this.unreadCount=D);if(T&&this.type===I.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!==I.GRP_MEETING||P?this.unreadCount+=D:this.unreadCount=0}updateLastMessage(n){this.lastMessage=Co.core.common.buildLastMessage(n)}reduceUnreadCount(){return this.unreadCount>=1&&(this.unreadCount-=1,!0)}isLastMessageRevoked(n){const{core:{OuterConstant:g}}=Co,{sequence:I,time:E}=n;return this.type===g.CONV_C2C&&I===this.lastMessage.lastSequence&&E===this.lastMessage.lastTime||this.type===g.CONV_GROUP&&I===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}}}=Co;g(n,this.groupAtInfoList)}clearGroupAtInfoList(){this.groupAtInfoList.length=0}getProfileCompleted(){return this._isInfoCompleted}setProfileCompleted(){this._isInfoCompleted=!0}}const Ct=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,3)===n.CONV_C2C},Ig=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s.slice(0,5)===n.CONV_GROUP},bs=s=>{const{core:{OuterConstant:n,utils:{isString:g}}}=Co;return g(s)&&s===n.CONV_SYSTEM};function ji(s){const{OuterConstant:n}=Co.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 Yr(s){const{OuterConstant:n}=Co.core;let g;return s.startsWith(n.CONV_C2C)&&(g=s.replace(n.CONV_C2C,"")),g==="@TLS#ERROR"||g==="@TLS#NOT_FOUND"}function ic(s,n){const{helper:g}=Co.core,I=new g.ChatError({functionName:s,code:n?.errorCode||n?.code,message:n?.errorInfo||n?.message});throw console.error(`${s} fail:`,I),I}var es,aa;(function(s){s[s.OFF=0]="OFF",s[s.ON=1]="ON"})(es||(es={})),function(s){s[s.ONLY_CONVERSATIONID=1]="ONLY_CONVERSATIONID"}(aa||(aa={}));var ha;(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"})(ha||(ha={}));const $r=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:I=[]}=g||{};I.forEach(E=>{const{Peer_Account:m,MuteNotifications:D}=E,M=`${this._core.OuterConstant.CONV_C2C}${m}`,T=ji(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(I,E){return pA(this,void 0,void 0,function*(){const{groupIDList:m,responseFilter:D}=I,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(I=>{var E;const{GroupId:m,MemberList:D}=I,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:I},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:YA}}=s;this._conversationStore=I,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(oA,this._handleMessageModified,this),g.subscribeInnerEvent(EA,this._handleConversationUpdated,this),g.subscribeInnerEvent(M,YA,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:n}}=this._core,{conversationUpdateFieldList:g=[],groupTipList:I=[],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(I)}_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:I=!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:I,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:I,MsgBody:E,MsgRandom:m,ClientSeq:D}=g;let M={};I?M=this._convertGroupAtTipsKey(I):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:I,GroupAtType:E}=s;return{from:n,groupID:g,sequence:I,groupAtType:E}}_updateGroupAtInfoList(){if(this._groupAtTipsList.length===0)return;const{common:s,OuterConstant:n}=this._core,g=s.getCurrentUserID();let I=!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),I=!0)}}),I&&this.emitConversationListUpdate(),this._groupAtTipsList.length=0}_handleMessageDeleted(s){var n,g;console.log(`${this._name}._handleMessageDeleted, conversationID:`,s);const{message:{messageDataHandler:I},OuterConstant:E}=this._core,m=I?.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 I=null,E=!1;n.forEach(m=>{I=this.getLocalConversation(m.conversationID),I&&(g&&I.reduceUnreadCount()&&(E=!0),I.isLastMessageRevoked({sequence:m.sequence,time:m.time})&&(I.setLastMessageRevoked(!0),I.setLastMessageRevoker(m.revoker),E=!0))}),E&&this.emitConversationListUpdate()}_handleMessageModified(s){const{utils:{isEmpty:n},common:{getMessagePreviewText:g},ssoLog:I}=this._core;I.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:I,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)?I.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(I).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:I,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===I){const T=D.replace(I,"");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:I},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 oA=((T=I.getFriend(P))===null||T===void 0?void 0:T.remark)||"";W.remark=oA,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:I},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",I(M))}})}_handleMessageRead(s){const{OuterConstant:{CONV_C2C:n}}=this._core,{C2cNotifyMsgArray:g=[]}=s||{};g.forEach(I=>{const{To_Account:E,UinPairReadArray:m=[]}=I?.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:I}}=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===I()&&T.lastTime<=m&&!T.isPeerRead&&(T.isPeerRead=!0,n.conversationStore.updateConversation(E,{lastMessage:T}))}}_updateMessageListPeerRead(s){const{notificationCenter:n,OuterEvent:g,message:I}=this._core,{conversationID:E,peerReadTime:m}=s,D=I.messageDataHandler.getLocalMessageList(E),M=I.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:I,GRP_ROOM:E,GRP_LIVE:m},utils:{isUndefined:D}}=this._core,M=this.getLocalConversation(s);if(D(M))return!0;const T=M.type===I&&((n=M.groupProfile)===null||n===void 0?void 0:n.type)===E,P=M.type===I&&((g=M.groupProfile)===null||g===void 0?void 0:g.type)===m;return!(T||P)}updateUnreadCount(s,n=!0){var g,I;let E=!1;const m=this.getLocalConversation(s),D=(I=(g=this._core)===null||g===void 0?void 0:g.message.messageDataHandler)===null||I===void 0?void 0:I.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:I},conversation:E}=this._core,m=this.getLocalConversationList();this._emitEvent({name:I,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 I=0;return g.forEach(E=>{E.type!==s.CONV_SYSTEM&&(n(E.messageRemindType)||E.messageRemindType===s.MSG_REMIND_ACPT_AND_NOTE)&&(I+=E.unreadCount)}),I}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(I=>{const E=this.getLocalConversation(I);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:I=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=I&&T.time>I,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(I=>I[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:I,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(I,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:I}}=this._core;if(n(s))return NA.getLocalConversationList();if(g(s))return s.length===0?[]:NA.getLocalConversationList().filter(E=>s.includes(E.conversationID));if(I(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}},ve=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:I},appStore:{groupStore:E},utils:{isEmpty:m}}=this._core,D={code:0,data:{}};let M=NA.getLocalConversation(s);if(bs(s))return D.data.conversation=M,D;let T=!1;const P=Ct(s)?n:g;if(m(M)&&(T=!0,M=new Et({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!==I&&(yield yA.get([W]))}return D})}_handleC2CConversation(s,n){return pA(this,void 0,void 0,function*(){var g,I;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:ha.USER_OR_GRP_NOT_FOUND});s.userProfile=W?.data[0];const oA=(I=T.getFriend(n))===null||I===void 0?void 0:I.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,n){return pA(this,void 0,void 0,function*(){const{apiMap:{getGroupProfile:g},appStore:{conversationStore:I}}=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?I.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()}},Te=new class{constructor(){this._serverGroupConversationLastReadSeqMap=new Map,this._name="SetMessageRead"}init(s){this._core=s;const{helper:n,common:{isTopic:g},notificationCenter:I,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}),I.subscribeInnerEvent(E,m,this._handleAllMessageRead,this)}handleC2CMessageReadSync(s){const{helper:{isEmpty:n},OuterConstant:g}=this._core;s.forEach(I=>{const{ReadC2cMsgNotify:E}=I;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(I=>{const{GroupReadInfoArray:E}=I.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:I}=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===I.CONV_GROUP&&T&&this._deleteGroupAtTips(E),D.unreadCount===0)return m;const{helper:{ChatError:P}}=this._core;try{if(D.type===I.CONV_C2C){const W=this._getLocalMessageMaxTime(D);M+=`lastMessageTime:${W}`,yield this._setC2CMessageRead(E,W)}if(D.type===I.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===I.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 I=`scope:${s.scope}`;s.scope||(s.scope=n);const{scope:E}=s,m=this._generateSetAllMessageReadRequestData(E);if(m.allC2CMessageReadStatus===$r&&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 Co.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(),I+=`failureGroupInfoList:${g(P)}`}return{code:0,successLog:{message:I}}}catch(D){const{errorCode:M}=D;throw new this._core.helper.ChatError({functionName:"setAllMessageRead",code:M,moreMessage:I})}})}_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:I}=this._core,E=I.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:I},appStore:E}=this._core,m={allC2CMessageReadStatus:$r,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===$r){if(m.allC2CMessageReadStatus=H,s===I)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:n}}=this._core,g=[];return s?.forEach(I=>{const{GroupId:E,MsgSeq:m,RetCode:D,LastReadMsgSeq:M}=I;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:I,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:I(),MsgSeq:P.__sequence,MsgRandom:P.__random,GroupId:P.groupID}));yield function(P,W){return pA(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(I){console.error(`${this._name}._deleteGroupAtTips fail:`,I)}})}_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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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,I=this._core.message.messageDataHandler.getLocalMessageList(g),E=Math.max(...I.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,I){return pA(this,void 0,void 0,function*(){return I.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,I){return pA(this,void 0,void 0,function*(){const{groupID:E,lastMessageSequence:m}=g,D={GroupId:E,MsgReadedSeq:m};return I.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:I,READ_ALL_C2C_MSG:E,READ_ALL_GROUP_MSG:m}}=this._core,{type:D,scope:M,unreadCount:T}=s;return!(T<=0)&&(!(D!==n||![I,E].includes(M))||!(D!==g||![I,m].includes(M)))}},ne=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:I}=this._core;let E=!1;s.forEach(m=>{const{Type:D,Peer_Account:M,GroupId:T}=m;let P;D===1?P=NA.getLocalConversation(`${I.CONV_C2C}${M}`):D===2&&(P=NA.getLocalConversation(`${I.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:I}}=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(bs(E))return M&&(M.isPinned=m),NA.emitConversationListUpdate(!0),D;const T=`conversationID:${E} isPinned:${m}`;try{let P=null;if(Ct(E)?P={Type:1,To_Account:E.replace(n.CONV_C2C,"")}:Ig(E)&&(P={Type:2,GroupId:E.replace(n.CONV_GROUP,"")}),yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{fromAccount:wA,operationType:kA,itemList:YA}=oA,LA={From_Account:wA,OperationType:kA,RecentContactItem:YA};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 Et({conversationID:E,type:Ct(E)?n.CONV_C2C:n.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 I({functionName:"pinConversation",code:W,message:oA,moreMessage:T})}})}},Le=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,I=[];s.forEach(E=>{const{Type:m,Peer_Account:D,GroupId:M}=E;m===1&&I.push(`${g.CONV_C2C}${D}`),m===2&&I.push(`${g.CONV_GROUP}${M}`)}),console.log(`${this._name}.handleConversationDeleted conversationIDList:${I}`),this._deleteLocalConversationList(I)}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:aa.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:I=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:ha.CONV_NOT_FOUND});return{code:0,data:I===aa.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 I;if(!NA.hasLocalConversation(g))return!1;const E=(I=NA.getLocalConversation(g))===null||I===void 0?void 0:I.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:I}=this._core,E={fromAccount:I.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,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 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,I=s.replace(n,"");return!!g.getGroup(I)}_deleteConversationLocalMessage(s){console.log(`${this._name}._deleteConversationLocalMessage conversationID:${s}`),this._core.message.messageDataHandler.deleteConversationMessageList(s),this._core.message.messageHistory.completedHistoryConversations.delete(s)}},yt=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:ha.CONV_NOT_FOUND});const I=NA.getLocalConversation(n);return I?.setDraftText(g),NA.emitConversationListUpdate(),{code:0,data:{conversation:I}}})}},Kt=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:oA}=Co.core.OuterConstant;return{[P]:0,[W]:1,[oA]:2}}()[n],I=yield function(P,W){return pA(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=[]}=I||{},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,n),{code:0,data:{successUserIDList:D,failureUserIDList:m}}})}},ai=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:I},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),!I(s)){const m=`${E.CONV_GROUP}${s}`;NA.patchMessageRemindType([m],n)}return{code:0,data:{groupID:s,messageRemindType:n}}})}},Qt=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:I}=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=ji(M);I.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:I,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 ai.set(g,E);if(!D(I))return M.debug(`${this._name}.${n} userIDList:${I} messageRemindType:${E}`),yield Kt.set(I,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:${I} messageRemindType:${E}`})}})}},hi=new class{init(s){s.ssoLog.debug("ConversationAction.init"),this._core=s,zA.init(s),ve.init(s),le.init(s),Te.init(s),ne.init(s),Le.init(s),yt.init(s),Qt.init(s);const{notificationCenter:n,InnerEvent:{MESSAGE_PUSH:g,DESTROY:I}}=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(I,this._dispose,this)}_onConversationModified(s){const{constants:{ConvModifyPushType:n}}=this._core,{RecentContactMod:g=[]}=s;g.forEach(I=>{const{PushType:E}=I;if(E===n.CONV_DELETED){const{RecentContactList:m}=I.RecentContactDeleteItem;Le.handleConversationDeleted(m)}if(E===n.CONV_PINED){const{RecentContactList:m}=I.RecentContactTopItem;ne.handleConversationPinned(m,!0)}if(E===n.CONV_UNPINED){const{RecentContactList:m}=I.RecentContactTopItem;ne.handleConversationPinned(m,!1)}})}_onC2CMessageReadSync(s){const{C2cNotifyMsgArray:n=[]}=s;Te.handleC2CMessageReadSync(n)}_onC2CMessageRemindTypeSync(s){const{C2cNotifyMsgArray:n=[]}=s;Qt.handleC2CMessageRemindTypeSync(n)}_onGroupMessageReadSync(s){const{GroupTips:n=[]}=s;Te.handleGroupMessageReadSync(n)}_dispose(){const{notificationCenter:s,InnerEvent:{MESSAGE_PUSH:n,DESTROY:g}}=this._core,{InnerEventSubType:{CONV_MODIFIED:I,C2C_MESSAGE_READ_SYNC:E,GROUP_MESSAGE_READ_SYNC:m,C2C_REMIND_TYPE_SYNC:D}}=s;s.unSubscribeInnerEvent(n,I,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)}},Ao=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:I=!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}=Co.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:I?es.ON:es.OFF});return{code:0,data:{errorCode:D.ErrorCode,errorInfo:D.ErrorInfo}}}catch(n){ic("setAllReceiveMessageOpt",n)}})}_calcStartAndEndTime(s){const{startHour:n=0,startMinute:g=0,startSecond:I=0,duration:E=0,isRepeated:m=!0}=s,D=new Date,M=new Date(D.getFullYear(),D.getMonth(),D.getDate(),n,g,I),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]}},ls=new class{init(s){this._core=s;const{helper:n,notificationCenter:g,InnerEvent:I}=s;n.registerApi({apiName:"getAllReceiveMessageOpt",context:this}),g.subscribeInnerEvent(I.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:I}}=this._core;g.emitOuterEvent(I,{name:I,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}=Co.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){ic("getAllReceiveMessageOpt",s)}})}_handleResult(s){const{OuterConstant:n}=this._core,{MSG_REMIND_ACPT_AND_NOTE:g,MSG_REMIND_DISCARD:I,MSG_REMIND_ACPT_NOT_NOTE:E}=n,m={0:g,1:I,2:E},{Level:D,StartTime:M,EndTime:T,IsRepeated:P}=s;return{messageRemindType:m[D]||g,startTime:M,endTime:T,isRepeated:P===es.ON}}},Lo=new class{init(s){s.ssoLog.debug("ReceiveMessageOptions.init"),this._core=s,Kt.init(s),ai.init(s),BA.init(s),yA.init(s),Ao.init(s),ls.init(s)}};const ei=s=>!Ct(s)&&!Ig(s)&&!bs(s),kr={getConversationProfile:[{key:"conversationID",required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}],setMessageRead:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(s)||"conversationID is invalid."}},pinConversation:{conversationID:{required:!0,rules:["string"],allowEmpty:!1,customValidator:s=>!ei(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:I}}}=Co;if(!I(s)&&!g(s))return"options is String or Object.";if(I(s)&&ei(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(ei(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=>!(!Ct(s)&&!Ig(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){Co.init(s),hi.init(s),Lo.init(s),NA.init(s),s.helper.registerValidateConfig({auth:zo,params:kr})}};const Wn=new class{init(s){this.core=s}},Aa="AVChatRoom",Vr="AV_HISTORY_MSG",oc="GRP_COUNTER",Uu="Set",lm="Increase",Ri="Decrease",ti=0,fo=1,tn=2,ts=["Type","Name","Introduction","Notification","FaceUrl","Owner_Account","CreateTime","InfoSeq","LastInfoTime","LastMsgTime","MemberNum","MaxMemberNum","ApplyJoinOption","NextMsgSeq","ShutUpAllMember","InviteJoinOption","LastRecallTime"],ug=["Type","Name","Introduction","Notification","FaceUrl","CreateTime","Owner_Account","LastInfoTime","LastMsgTime","NextMsgSeq","MemberNum","MaxMemberNum","ApplyJoinOption","InviteJoinOption"],Ll=["Role","JoinTime","MsgFlag","MsgSeq"],ld=["Role","JoinTime","MsgSeq","MsgFlag","NameCard"],kc=0,Sr=1,QI="notStart",ZI="resolved",Fg="rejected",XI=10018,pI=11e3,Lc=2,Fu=["Owner","Admin","Member"],Im=["Role","JoinTime","NameCard","ShutUpUntil","OnlineStatus"],um=0,Em=1,dm=2,Hy=4,qy=1,Cv=2,Ky=3,jy=4,hv=5,Y_=1,Id=0,V_=4,Wy=6,J_=400,zy=300,H_={from:!0,groupID:!0,groupName:!0,to:!0},Bv={from:!0,groupID:!0,groupName:!0,to:!0,type:!0},q_=2,Qv=4,K_=5,j_=7,Zy=8,Xy=15,mQ=20,Cm=21,hm=2600,ud=2602,W_=2603,z_=2620,Bm=2621,$y=2623,eh=2660,Z_=2661,X_=2681,Qm=2683,pv=2684,AD=2685,pm=2687,mv=3122,$_=10018,AT={0:"DisableInvite",1:"NeedPermission",2:"FreeAccess"},fv=s=>s===Wn.core.OuterConstant.GRP_PUBLIC,Ed=s=>s===Wn.core.OuterConstant.GRP_AVCHATROOM,mm=(s,n)=>{const{isArray:g}=Wn.core.utils;if(!g(s)||!g(n))return!1;let I=!1;return n.forEach(({key:E,value:m})=>{const D=s.find(M=>M.key===E);D?D.value!==m&&(D.value=m,I=!0):(s.push({key:E,value:m}),I=!0)}),I},dd=s=>{const n=[];if(!s)return n;for(let g=0,I=s.length;g{const n=[];for(let g=0,I=s.length;g0&&M.members.forEach(T=>{T.userID===this.selfInfo.userID&&D(this.selfInfo,T,["sequence"])})}updateSelfInfo(n){const{nameCard:g,joinTime:I,role:E,messageRemindType:m,readedSequence:D,excludedUnreadSequenceList:M}=n,{common:{deepMerge:T}}=Wn.core;T(this.selfInfo,{nameCard:g,joinTime:I,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 Ou(E)),this._clearGroupLocalMessage(g))});const I=n();for(const[,E]of this._groupMap)E.selfInfo.userID=I,E.selfInfo.role==="Owner"&&(E.ownerID=I)}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:I}=g;return I!==s&&I!==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,I=`${g}${s}`,E=n.getConversation(I);if(E){const m=this.getLocalGroup(s);E.setProfileCompleted(),n.updateConversation(I,{groupProfile:m})}}reset(){this.clearLocalGroup()}_clearGroupLocalMessage(s){const{message:{messageHistory:n,messageDataHandler:g},OuterConstant:{CONV_GROUP:I},ssoLog:E}=this._core;E.debug("_clearGroupLocalMessage",`groupID:${s}`);const m=`${I}${s}`;n.completedHistoryConversations.delete(m),g.deleteConversationMessageList(m)}};function ym(s,n){return pA(this,void 0,void 0,function*(){const{type:g,limit:I,offset:E,supportTopic:m=0,memberAccount:D,responseFilter:M}=s,T={Type:g,Limit:I,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 yv=new class{constructor(){this._name="GetGroupList",this._pagingStatus=QI,this.PAGING_GRP_COUNT_LIMIT=200}init(s){this._core=s;const{helper:n,constants:{WORKFLOW_NAME:g,WORKFLOW_STEP:I}}=s;n.registerApi({apiName:"getGroupList",context:this}),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_LOGIN,I.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===Fg||this._pagingStatus===QI)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===QI&&Yi.clearLocalGroup();const s=this.PAGING_GRP_COUNT_LIMIT,n=[];try{yield this._pagingGetGroupList({limit:s,offset:0,groupList:n}),this._pagingStatus=ZI,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=Fg,g}})}_pagingGetGroupList(s){return pA(this,void 0,void 0,function*(){const{ssoLog:n}=this._core,{isCommunityRelay:g=!1,groupList:I}=s;let E,{limit:m,offset:D}=s;const M=[...ts];g&&(E=this._core.OuterConstant.GRP_COMMUNITY,M.push("AtInfoList"));try{const T=yield ym({type:E,limit:m,offset:D,memberAccount:this._core.store.get("login").userId,responseFilter:{GroupBaseInfoFilter:M,SelfInfoFilter:[...Ll]}},this._core),{GroupIdList:P=[],TotalCount:W=0}=T||{},oA=this._convertGroupKey(P);I.push(...oA);const EA=D+m,wA=!(W>EA),kA=`offset:${D} limit:${m} total:${W} isCompleted:${wA} current:${I.length} isCommunityRelay:${g}`;return n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. ${kA}`),g?wA?I:(D=EA,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):wA?(n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList start to get community list`),D=0,this._pagingGetGroupList({isCommunityRelay:!0,limit:m,offset:D,groupList:I})):(D=EA,this._pagingGetGroupList({limit:m,offset:D,groupList:I}))}catch(T){if(T.ErrorCode===XI)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:I});if(g)return T.code===pI&&n.debug("_pagingGetGroupList",`${this._name}._pagingGetGroupList ok. community unavailable`),I;throw T}})}_pagingGetJoinedCommunityList(s){return pA(this,void 0,void 0,function*(){const{common:{getCurrentUserID:n},OuterConstant:g,ssoLog:I}=this._core,{groupList:E}=s;let{limit:m,offset:D}=s;try{const M=yield ym({limit:m,offset:D,type:g.GRP_COMMUNITY,memberAccount:n(),supportTopic:1,responseFilter:{GroupBaseInfoFilter:[...ts],SelfInfoFilter:[...Ll]}},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 I.debug("_pagingGetJoinedCommunityList",`${this._name}._pagingGetJoinedCommunityList ok. ${wA}`),EA?E:(D=oA,this._pagingGetJoinedCommunityList({limit:m,offset:D,groupList:E}))}catch(M){if(M.code===$_)return I.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 I=0,E=s.length;I{const{AtFlagList:E,AtMsgSeq:m,From_Account:D}=I;g.push({groupID:s,groupAtType:E,sequence:m,from:D})}),g}},Pu=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:I},common:{getCurrentUserID:E},OuterConstant:{GRP_AVCHATROOM:m}}=this._core,D=yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{name:wA,type:kA,groupID:YA,introduction:LA,notification:SA,avatar:OA,maxMemberNum:HA,joinOption:se,inviteOption:oe,memberList:_i,groupCustomField:Ti,isSupportTopic:bt}=oA;let Ni,gs;_i&&(Ni=_i.map(Bt=>{const{userID:UA,memberCustomField:ii}=Bt;return{Member_Account:UA,AppMemberDefinedData:ii?TE(ii):void 0}})),Ti&&(gs=TE(Ti));const De={Name:wA,Type:kA,GroupId:YA,Introduction:LA,Notification:SA,FaceUrl:OA,MaxMemberCount:HA,ApplyJoinOption:se,InviteJoinOption:oe,MemberList:Ni,AppDefinedData:gs,SupportTopic:bt,webPushFlag:1};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.create_group",data:De})})}(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(I(s.memberList)||I(T)||(s.memberList=(n=s.memberList)===null||n===void 0?void 0:n.filter(oA=>T.includes(oA.userID))),s.type===m)return dn({group:new Ou(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(I){const{errorCode:E,errorInfo:m}=I;throw new g({functionName:"createGroup",code:E,message:m,moreMessage:` groupID:${s.groupID}`})}})}_preCheckParams(s){const{type:n,groupID:g}=s,{utils:{isEmpty:I,isUndefined:E},common:{isCommunity:m}}=this._core,D=!I(g);if(!(()=>{const{GRP_PUBLIC:M,GRP_WORK:T,GRP_MEETING:P,GRP_AVCHATROOM:W,GRP_COMMUNITY:oA}=Wn.core.OuterConstant;return[M,T,P,W,oA]})().includes(n))throw new this._core.helper.ChatError({code:hm});if(!m({type:n})){if(D&&m({groupID:g}))throw new this._core.helper.ChatError({code:ud});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:ud});s.isSupportTopic=this._canIUseTopic(s)?1:0}}_canIUseMemberList(s){return!Ed(s)}_canIUseJoinOption(s){return fv(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:I,GRP_COMMUNITY:E}}=this._core;return n===I||n===E&&g===1}_sendCustomMessage(s,n){var g,I,E,m,D,M;const{OuterConstant:T,common:{t:P}}=this._core;let W=P("CREATE_GROUP"),oA=kc;n===T.GRP_COMMUNITY&&(W=P("CREATE_COMMUNITY"),oA=Sr);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=(I=(g=this._core)===null||g===void 0?void 0:g.message)===null||I===void 0?void 0:I.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,{})}},Ws=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:I}}=this._core;return!I(n)&&!g(n.groupAttributeOption)}handleGroupAttributesUpdated(s){const{groupID:n,groupAttributeOption:g}=s,{serverMainSequence:I,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:I,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:I,operation:E}=s;if(this.hasGroupAttributesCache(n)){const m=this.getGroupAttributesCache(n),{localMainSequence:D}=m;E!==hv&&g-D!==1||(m.serverMainSequence=g,m.localMainSequence=g,m.lastUpdateTime=Date.now(),this._updateGroupAttributesCacheValues({groupAttributes:m,groupAttributeList:I,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:I}=s;I!==Ky?I!==jy?(I===qy&&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:I=[]}=s,E={};if(this.hasGroupAttributesCache(g)){const{values:m}=this.getGroupAttributesCache(g);if(I.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 I.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:I,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||([I,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=[],I=[];return Object.keys(s).forEach(E=>{s[E]!==this._groupAttributesCacheValuesCopy[E]&&g.push(E)}),Object.keys(this._groupAttributesCacheValuesCopy).forEach(E=>{n(s[E])&&I.push(E)}),this._groupAttributesCacheValuesCopy={},{updatedKeyList:g,deletedKeyList:I}}_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={}}},ih=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(Aa)})}dismissGroup(s){return pA(this,void 0,void 0,function*(){const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return pA(this,void 0,void 0,function*(){const m={GroupId:I};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(),Ws.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:s})}catch(g){const{errorCode:I,errorInfo:E}=g;throw new n({functionName:"dismissGroup",code:I,message:E})}})}},Ul=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,I={groupIDList:[n],responseFilter:{GroupBaseInfoFilter:[...ts],AppDefinedDataFilter_Group:g,MemberInfoFilter:[...ld]}},{helper:{ChatError:E}}=this._core;try{const m=yield this.getGroupProfileAdvance(I),{successGroupList:D,failureGroupList:M}=m;if(M.length>0)throw M[0];let T;return!Yi.hasLocalGroup(n)&&Ed(D[0].type)?T=new Ou(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,I=n.filter(T=>!g({groupID:T})),E=n.filter(T=>g({groupID:T}));I.length>50&&(I.length=50),E.length>50&&(E.length=50);const m=yield Promise.all([this._getGroupProfileAdvance(Object.assign(Object.assign({},s),{groupIDList:I})),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:I=!1}=s,E=yo(s,["isCommunityProfile"]);if(E.groupIDList.length===0)return{successGroupList:[],failureGroupList:[]};try{const m=yield function(W,oA){return pA(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 n.debug("_getGroupProfileAdvance",`${this._name}._getGroupProfileAdvance ok, groupID:${E.groupIDList.join(",")}`),{successGroupList:T,failureGroupList:P}}catch(m){if(I)return{successGroupList:[],failureGroupList:[]};throw m}})}_convertGroupProfileKey(s){const n=[];for(let g=0,I=s.length;g0&&I{const{Key:T,Value:P=0}=M;E.set(T,P)}),this._groupCountersMap.set(n,{lastUpdateTime:Date.now(),groupCounterSeq:I,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:I}=this.getLocalGroupCounters(s);if(n.length>0)n.forEach(E=>{I.has(E)&&(g[E]=I.get(E))});else for(const E of I.keys())g[E]=I.get(E);return g}deleteLocalGroupCounters(s){const{groupID:n,counterList:g=[],groupCounterSeq:I}=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:I,counters:E,avChatRoomKey:m})}}setGroupCounters(s,n){if(!this._hasLocalGroupCounters(s))return;const g=this.getLocalGroupCounters(s),{counters:I}=g;let E=!1;Object.entries(n).forEach(([m,D])=>{I.has(m)&&I.get(m)!==D&&(I.set(m,D),E=!0)}),E&&this._groupCountersMap.set(s,Object.assign(Object.assign({},g),{lastUpdateTime:Date.now(),counters:I}))}_hasLocalGroupCounters(s){return this._groupCountersMap.has(s)}reset(){this._groupCountersMap.clear()}},NE=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(Aa)})}joinGroup(s){return pA(this,void 0,void 0,function*(){const{groupID:n}=s,{helper:{ChatError:g},OuterConstant:I,ssoLog:E}=this._core;try{if(Yi.hasLocalGroup(n))try{return yield Ul.getGroupProfile({groupID:n}),dn({status:I.JOIN_STATUS_ALREADY_IN_GROUP,group:Yi.getLocalGroup(n)},{message:`groupID:${n} joinedStatus:${I.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:I}=this._core,{groupID:E}=s,m=Object.assign({},s),D=g.checkBusinessCapabilityBits(Vr);D&&(m.historyMessageFlag=1);const M=yield function(SA,OA){return pA(this,void 0,void 0,function*(){const{groupID:HA,applyMessage:se,historyMessageFlag:oe}=SA,_i={GroupId:HA,ApplyMsg:se,HugeGroupHistoryMsgFlag:oe};return OA.common.buildAndSendPacket({servcmd:"group_open_http_svc.apply_join_group",data:_i})})}(m,this._core),{Type:T,JoinedStatus:P,LongPollingKey:W,StartSeq:oA,HugeGroupFlag:EA,AVChatRoomKey:wA,RspMsgList:kA=[]}=M||{},YA=`groupID:${E} joinedStatus:${P} longPollingKey:${W} startSeq:${oA} avChatRoomFlag:${EA} canGetAVChatRoomHistoryMsg:${D}, historyMessageCount:${kA.length}`;I.debug("_applyJoinGroup",`${this._name}._applyJoinGroup ok, ${YA}`);let LA=new Ou({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 Ul.getGroupProfile({groupID:E})).data.group}catch(SA){I.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:eh})})}_handleJoinResult(s){const{group:n,avChatRoomFlag:g,avChatRoomKey:I}=s;return g===1?(Ws.initGroupAttributesCache({groupID:n.groupID,avChatRoomKey:I}),sc.initGroupCountersCache({groupID:n.groupID,avChatRoomKey:I}),dn(s)):(Yi.updateLocalGroup([n]),Yi.emitGroupListUpdate(),dn({status:this._core.OuterConstant.JOIN_STATUS_SUCCESS,group:n},{message:`groupID:${n.groupID}`}))}},fQ=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(Aa)})}quitGroup(s){return pA(this,void 0,void 0,function*(){if(!Yi.hasLocalGroup(s))throw new this._core.helper.ChatError({code:$y});const{helper:{ChatError:n}}=this._core;try{yield function(I,E){return pA(this,void 0,void 0,function*(){const m={GroupId:I};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(),Ws.deleteGroupAttributesCache(s),dn({groupID:s,type:g},{message:`groupID:${s}`})}catch(g){const{errorCode:I,errorInfo:E}=g;throw new n({functionName:"quitGroup",code:I,message:E,moreMessage:`groupID:${s}`})}})}},AB=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,HA){return pA(this,void 0,void 0,function*(){const se={GroupIdList:[OA],GroupBasePublicInfoFilter:[...ug]};return HA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_public_info",data:se})})}(s,this._core),{GroupInfo:g=[]}=n||{},{AppDefinedData:I=[],ApplyJoinOption:E,CreateTime:m,FaceUrl:D,Introduction:M,InviteJoinOption:T,MaxMemberNum:P,MemberNum:W,Name:oA,Owner_Account:EA,Type:wA,ErrorCode:kA,ErrorInfo:YA}=g[0];if(kA!==0)throw new this._core.helper.ChatError({code:kA,message:YA});const LA=dd(I),SA=new Ou({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(n){const{errorCode:g,errorInfo:I}=n;throw new this._core.helper.ChatError({functionName:"searchGroupByID",code:g,message:I})}})}},eT=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:I},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:oA,introduction:EA,notification:wA,muteAllMembers:kA,joinOption:YA,inviteOption:LA,groupCustomField:SA}=M,OA={GroupId:P,Name:W,FaceUrl:oA,Introduction:EA,Notification:wA,ShutUpAllMember:kA,ApplyJoinOption:YA,InviteJoinOption:LA,AppDefinedData:SA?TE(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 Ou(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:${I(s)}`})}})}_canIUseJoinOption(s){return fv(s)||this._core.common.isCommunity({type:s})}},tT=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:I}=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:z_});if(I===M())throw new m.ChatError({functionName:n,code:Bm});try{return yield function(T,P){return pA(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=I,Yi.emitGroupListUpdate(),dn({group:E})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},yQ=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(Aa)})}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 I=this._onlineMemberCountMap.get(s),{lastReqTime:E=0,memberCount:m=0}=I||{};if(g-E<=6e4)return dn({memberCount:m})}try{const I=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}=I||{};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(I){throw new this._core.helper.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo})}})}},DQ=new class{init(s,n){s.ssoLog.debug("GroupAction.init"),yv.init(s),Pu.init(s),ih.init(s,n),NE.init(s,n),fQ.init(s,n),AB.init(s),Ul.init(s),eT.init(s),tT.init(s),yQ.init(s,n)}dismissGroup(s){return ih.dismissGroup(s)}joinGroup(s){return NE.joinGroup(s)}quitGroup(s){return fQ.quitGroup(s)}getGroupOnlineMemberCount(s){return yQ.getGroupOnlineMemberCount(s)}},Dv=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:I=20}=s||{},{common:E}=this._core;let m;try{m=yield function(P,W){return pA(this,void 0,void 0,function*(){const{type:oA,startTime:EA,limit:wA,handleAccount:kA}=P,YA={Type:oA,StartTime:EA,Limit:wA,Handle_Account:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_pendency",data:YA})})}({type:n,startTime:g,limit:I,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 I=this._convertApplicationData(g),{handled:E}=I,m=yo(I,["handled"]);E===0&&n.push(m)}),n}_convertApplicationData(s){const{Handled:n,AddTime:g,ApplyInviteMsg:I,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:I,addTime:g}}},Sv=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===Lc?yield function(E,m){return pA(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 pA(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 I=Yi.getLocalGroup(g.groupID);return dn({group:I})}catch(I){throw new this._core.helper.ChatError({functionName:"handleGroupApplication",code:I?.errorCode,message:I?.errorInfo})}})}_handleParams(s){var n;const{handleAction:g,handleMessage:I,message:E,application:m}=s;let D,M,T,P,W;if(E){const{payload:oA}=E||{};D=oA.operatorID,M=(n=oA.groupProfile)===null||n===void 0?void 0:n.groupID,T=oA.authentication,P=oA.messageKey}else D=m?.applicant||"",M=m?.groupID||"",T=m?.authentication||"",P=m?.messageKey||0;return m?.applicationType===Lc&&(W=m.userID),{handleAction:g,handleMessage:I,applicant:D,invitee:W,groupID:M,authentication:T,messageKey:P}}},eD=new class{init(s){s.ssoLog.debug("GroupApplication.init"),Dv.init(s),Sv.init(s)}};let uC=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 I=[null,void 0,"",0,NaN];s.memberCustomField&&mm(this.memberCustomField,s.memberCustomField),g(this,s,["memberCustomField","marks","onlineStatus","muteTime"],I)}};function eB(s,n){return pA(this,void 0,void 0,function*(){const{groupID:g,userID:I,muteTime:E,role:m,nameCard:D,memberCustomField:M}=s;let T;M&&(T=TE(M));const P={GroupId:g,Member_Account:I,ShutUpTime:E,Role:m,NameCard:D,AppMemberDefinedData:T};return n.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_member_info",data:P})})}var tD=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(Aa)})}getGroupMemberList(s){return pA(this,void 0,void 0,function*(){const n="getGroupMemberList",{groupID:g,offset:I=0,count:E=100,role:m="",filter:D=""}=s,M=Yi.getLocalGroup(g),T=E>100?100:E,P={groupID:g,offset:I,limit:T,memberRoleFilter:Fu.includes(m)?[m]:void 0,memberInfoFilter:Im};try{const W=yield function(oe,_i){return pA(this,void 0,void 0,function*(){const{isCommunity:Ti}=_i.common,{groupID:bt,offset:Ni,limit:gs,memberRoleFilter:De,memberInfoFilter:Bt}=oe,UA={GroupId:bt,Limit:gs,MemberRoleFilter:De,MemberInfoFilter:Bt};return Ti({groupID:bt})?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:oA,MemberNum:EA,Next:wA}=W||{},kA=`${this._name}.${n} ok, totalMemberCount:${EA} next:${wA}`,{utils:{isArray:YA,isEmpty:LA},common:{isCommunity:SA}}=this._core;if(M&&(M.memberCount=EA),!YA(oA)||oA.length===0)return dn({memberList:[],offset:0},{message:kA});let OA=I+T;SA({groupID:g})&&(OA=LA(wA)?0:wA),oA.lengthD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g50&&(T.warn("getGroupMemberProfile",`${this._name}.${n} userIDList length:${I.length} exceeds limit 50`),I.splice(50));const P=`userIDList length:${I.length} groupID:${g}`;try{const W=yield function(kA,YA){return pA(this,void 0,void 0,function*(){const{groupID:LA,userIDList:SA,memberInfoFilter:OA,memberCustomFieldFilter:HA}=kA,se={GroupId:LA,Member_List_Account:SA,MemberInfoFilter:OA,AppDefinedDataFilter_GroupMember:HA};return YA.common.buildAndSendPacket({servcmd:"group_open_http_svc.get_specified_group_member_info",data:se})})}({groupID:g,userIDList:I,memberCustomFieldFilter:E,memberInfoFilter:[...Im]},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:n,code:W?.errorCode,message:W?.errorInfo,moreMessage:P})}})}_convertMemberInfo(s){const n=[];for(let g=0,I=s.length;gD.userID),I=yield(n=this._core.user.userProfile)===null||n===void 0?void 0:n.getUserProfile({userIDList:g}),E=I?.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,I=s.length;g({Member_Account:M}));try{const M=yield function(wA,kA){return pA(this,void 0,void 0,function*(){const{groupID:YA,userIDList:LA}=wA,SA={GroupId:YA,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:n,code:M?.errorCode,message:M?.errorInfo})}})}_handleResult(s){const n=[],g=[],I=[],E=[];return s.forEach(m=>{const{Result:D,Member_Account:M}=m;D===um?n.push(M):D===Em?g.push(M):D===dm?I.push(M):D===Hy&&E.push(M)}),{failureUserIDList:n,successUserIDList:g,existedUserIDList:I,overLimitUserIDList:E}}},hd=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(Aa)})}deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="deleteGroupMember",{groupID:g,userIDList:I}=s,E=Yi.getLocalGroup(g),{helper:m,utils:{isUndefined:D},ssoLog:M}=this._core;if(D(E))throw new m.ChatError({functionName:n,code:W_});I.length>20&&(M.warn("deleteGroupMember",`${this._name}.${n} userIDList length:${I.length} exceeds limit 20`),I.splice(20));try{return yield function(T,P){return pA(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:I},this._core),dn({group:E,userIDList:I},{message:`groupID:${g} userIDList length:${I.length}`})}catch(T){throw new m.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Mv=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:I,muteTime:E}=s,m=` groupID:${g} userID:${I} muteTime:${E}`;this._preCheckSettingMuteParams(s);try{yield eB(s,this._core);const D=Yi.getLocalGroup(g),M=new uC({userID:I,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:I}=this._core;if(n===g.get("login").userId)throw new I.ChatError({functionName:"setGroupMemberMuteTime",code:AD})}},MQ=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:I,userID:E,role:m}=s,D=`${this._name}.${n} ok, groupID:${I} userID:${E} role:${m}`;this._preCheckSettingRoleParams(s);try{yield eB(s,this._core);const M=Yi.getLocalGroup(I),T=new uC({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:I,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:X_});if(I===m.get("login").userId)throw new D.ChatError({functionName:"setGroupMemberRole",code:pv});const W=[...Fu];if(T({groupID:g})&&W.push(M.GRP_MBR_ROLE_CUSTOM),!W.includes(E))throw new D.ChatError({functionName:"setGroupMemberRole",code:Qm})}},iD=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:I,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=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 oA=new uC({userID:D,nameCard:M});return dn({group:W,member:oA},{message:T})}catch(P){throw new I.ChatError({functionName:g,code:P?.errorCode,message:P?.errorInfo,moreMessage:T})}})}_preCheckSettingNameCardParams(s){const{groupID:n}=s,{helper:g}=this._core,I=Yi.getLocalGroup(n);if(Ed(I?.type))throw new g.ChatError({functionName:"setGroupMemberNameCard",code:pm})}},Dm=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:I}}=this._core;this._preCheckSettingCustomFiledParams(s);const{groupID:E,userID:m=I(),memberCustomField:D}=s,M=`${this._name}.${n} ok, groupID:${E}userID:${m} memberCustomField:${JSON.stringify(D)}`;try{yield eB({groupID:E,userID:m,memberCustomField:D},this._core);const P=Yi.getLocalGroup(E),W=new uC({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,I=Yi.getLocalGroup(n);if(Ed(I?.type))throw new g.ChatError({functionName:"setGroupMemberCustomField",code:pm})}},vv=new class{init(s,n){s.ssoLog.debug("GroupMember.init"),tD.init(s,n),SQ.init(s),Cd.init(s),hd.init(s,n),Mv.init(s),MQ.init(s),iD.init(s),Dm.init(s)}getGroupMemberList(s){return tD.getGroupMemberList(s)}deleteGroupMember(s){return hd.deleteGroupMember(s)}},iT=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{fm(n,oc);const{groupID:g,keyList:I=[]}=s,{avChatRoomKey:E,lastUpdateTime:m}=sc.getLocalGroupCounters(g);if(!(Date.now()-m>=this._getExpireTime()))return{code:0,data:{counters:sc.getLocalCounters(g,I)}};const D=yield function(P){return pA(this,void 0,void 0,function*(){const{groupID:W,GroupCounterKeys:oA,avChatRoomKey:EA}=P,{common:wA}=Wn.core,kA={GroupId:W,keyList:oA,BytesKey:EA};return wA.buildAndSendPacket({servcmd:"group_open_http_svc.get_group_counter",data:kA})})}({groupID:g,keyList:I,avChatRoomKey:E}),{GroupCounter:M=[],GroupCounterSeq:T}=D;return sc.updateLocalGroupCounters({groupID:g,counterList:M,groupCounterSeq:T}),{code:0,data:{counters:sc.getLocalCounters(g,I)}}}catch(g){IC(n,g)}})}_getExpireTime(){const{store:s,utils:{isUndefined:n}}=this._core,g=s.get("cloudConfig")||{},{grp_counter_expire_time:I}=g;return n(I)?3e4:Number(I)}},Sm=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(Uu,s)})}increaseGroupCounter(s){return pA(this,void 0,void 0,function*(){return this._handleCounterOperation(lm,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{fm(g,oc);const{groupID:I,key:E,value:m=0}=n,{avChatRoomKey:D}=sc.getLocalGroupCounters(I),M=s===Uu?this._convertObjectToList(n.counters):[{Key:E,Value:m}],T=yield this._updateGroupCounters({groupID:I,counterList:M,avChatRoomKey:D,mode:s});return sc.setGroupCounters(I,T),{code:0,data:{counters:T}}}catch(I){IC(g,I)}})}_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,I={};return g.forEach(E=>{const{Key:m,Value:D=0}=E;I[m]=D}),I})}_convertObjectToList(s){return Object.entries(s).map(([n,g])=>({Key:n,Value:g||0}))}},tB=new class{init(s){this._core=s,iT.init(s),Sm.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(I=>{const{type:E,groupCounterSeq:m,counterList:D=[]}=I;E!==ti&&E!==tn||this._processAndNotifyCounterUpdate(n,m,D),E===fo&&sc.deleteLocalGroupCounters({groupID:n,groupCounterSeq:m,counterList:D})})}_processAndNotifyCounterUpdate(s,n,g){const{OuterEvent:I,notificationCenter:E}=this._core;sc.updateLocalGroupCounters({groupID:s,groupCounterSeq:n,counterList:g}),g.forEach(({Key:m,Value:D=0})=>{E.emitOuterEvent(I.GROUP_COUNTER_UPDATED,{name:I.GROUP_COUNTER_UPDATED,data:{groupID:s,key:m,value:D}})})}reset(){sc.reset()}},Mm=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:I,avChatRoomKey:E}=Ws.getGroupAttributesCache(n),m=Ws.convertKeyValueMapToList(g);try{const D=yield function(W,oA){return pA(this,void 0,void 0,function*(){const{groupID:EA,mainSequence:wA,groupAttributeList:kA,avChatRoomKey:YA}=W,LA={GroupId:EA,AttrMainSeq:wA,GroupAttr:kA,BytesKey:YA,AttrControl:["RaceConflict"]};return oA.common.buildAndSendPacket({servcmd:"group_open_http_svc.set_group_attr",data:LA})})}({groupID:n,avChatRoomKey:E,groupAttributeList:m,mainSequence:I},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 Ws.saveGroupAttributesCacheValuesCopy(n),Ws.refreshGroupAttributesCache({groupID:n,serverMainSequence:M,groupAttributeList:P,operation:qy}),Ws.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})}})}},oT=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:I}=s,{serverMainSequence:E,avChatRoomKey:m,values:D}=Ws.getGroupAttributesCache(n),M=Ws.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 pA(this,void 0,void 0,function*(){const{groupID:kA,mainSequence:YA,groupAttributeList:LA,avChatRoomKey:SA,richStatusMode:OA}=EA,HA={GroupId:kA,AttrMainSeq:YA,GroupAttr:LA,BytesKey:SA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:OA};return wA.common.buildAndSendPacket({servcmd:"group_open_http_svc.modify_group_attr",data:HA})})}({groupID:n,avChatRoomKey:m,groupAttributeList:M,mainSequence:E,richStatusMode:I},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 Ws.saveGroupAttributesCacheValuesCopy(n),Ws.refreshGroupAttributesCache({groupID:n,serverMainSequence:P,groupAttributeList:oA,operation:Cv}),Ws.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})})}},oD=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:I=[],richStatusMode:E}=s;try{let m;m=I.length===0?yield this._clearGroupAttributes(g,{richStatusMode:E}):yield this._deleteGroupAttributes(g,{keyList:I,richStatusMode:E});const{resultList:D,serverMainSequence:M,operation:T,groupAttributeList:P}=m||{},W=`${this._name}.${n} ok. groupID:${g} operation: ${T}`;return Ws.saveGroupAttributesCacheValuesCopy(g),Ws.refreshGroupAttributesCache({groupID:g,serverMainSequence:M,groupAttributeList:P,operation:T}),Ws.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:I,values:E}=Ws.getGroupAttributesCache(s),{keyList:m,richStatusMode:D}=n,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 pA(this,void 0,void 0,function*(){const{groupID:wA,mainSequence:kA,groupAttributeList:YA,avChatRoomKey:LA,richStatusMode:SA}=oA,OA={GroupId:wA,AttrMainSeq:kA,GroupAttr:YA,BytesKey:LA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:SA};return EA.common.buildAndSendPacket({servcmd:"group_open_http_svc.delete_group_attr",data:OA})})}({groupID:s,avChatRoomKey:I,groupAttributeList:T,mainSequence:g,richStatusMode:D},this._core),{AttrMainSeq:W}=P||{};return{resultList:M,serverMainSequence:W,groupAttributeList:T,operation:jy}})}_clearGroupAttributes(s,n){return pA(this,void 0,void 0,function*(){const{serverMainSequence:g,avChatRoomKey:I,values:E}=Ws.getGroupAttributesCache(s),{richStatusMode:m}=n||{},D=[...E.keys()],M=yield function(P,W){return pA(this,void 0,void 0,function*(){const{groupID:oA,mainSequence:EA,avChatRoomKey:wA,richStatusMode:kA}=P,YA={GroupId:oA,AttrMainSeq:EA,BytesKey:wA,AttrControl:["RaceConflict"],AllowRoomEngineOpt:kA};return W.common.buildAndSendPacket({servcmd:"group_open_http_svc.clear_group_attr",data:YA})})}({groupID:s,avChatRoomKey:I,mainSequence:g,richStatusMode:m},this._core),{AttrMainSeq:T}=M||{};return{resultList:D,serverMainSequence:T,operation:Ky}})}},sD=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:I,localMainSequence:E,serverMainSequence:m}=Ws.getGroupAttributesCache(n),{helper:{ChatError:D}}=this._core,M=`groupID:${n} localMainSequence:${E} serverMainSequence:${m} keyList:${s.keyList}`;if(Date.now()-I>=3e4||E{const{key:oA,value:EA,seq:wA}=W;return{key:oA,value:EA,sequence:wA}});return Ws.refreshGroupAttributesCache({groupID:I,serverMainSequence:M,groupAttributeList:P,operation:hv}),{serverGroupAttributeList:T}})}},vQ=new class{init(s){s.ssoLog.debug("GroupAttribute.init"),Mm.init(s),oT.init(s),oD.init(s),sD.init(s),Ws.init(s)}isGroupAttributesUpdated(s){return Ws.isGroupAttributesUpdated(s)}handleGroupAttributesUpdated(s){const{to:n,elements:{newGroupProfile:g}}=s,{groupAttributeOption:I}=g,{serverMainSequence:E,withChangedAttributeInfo:m}=I,{localMainSequence:D}=Ws.getGroupAttributesCache(n),M=E-D;if(console.log(`GroupAttribute.handleGroupAttributesUpdated groupID:${n} withChangedAttributeInfo:${m} diffSequence:${M}`),M!==0)if(Ws.saveGroupAttributesCacheValuesCopy(n),m!==1||M!==1){if(Ws.hasGroupAttributesCache(n)){const{avChatRoomKey:T}=Ws.getGroupAttributesCache(n);sD.getGroupAttributesFromServer({groupID:n,avChatRoomKey:T}).then(()=>{Ws.emitGroupAttributesUpdated(n)}).catch(()=>{})}}else Ws.handleGroupAttributesUpdated({groupID:n,groupAttributeOption:I})}reset(){Ws.reset()}};function GE(s,n="tips"){const{ClientSeq:g,From_Account:I,MsgClientTime:E,MsgPriority:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,TinyId:P,ToGroupId:W,GroupInfo:oA,MsgBody:EA}=s,wA=function(kA){const{GroupCode:YA,GroupId:LA,GroupName:SA,GroupType:OA,MsgFrom_AccountExtraInfo:HA,From_Account:se,To_Account:oe}=kA;return{groupCode:YA,groupID:LA,groupName:SA,type:OA,messageFromAccountExtraInformation:HA,from:se,to:oe}}(oA);return{clientSequence:g,from:I,clientTime:E,priority:m,random:D,sequence:M,time:T,tinyID:P,to:W,groupProfile:wA,elements:n==="tips"?xu(EA):oh(EA)}}function xu(s){const n={};return Object.keys(s).forEach(g=>{var I,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=(I=s[g])===null||I===void 0?void 0:I.map(m=>nD(m));break;case"MsgOperatorMemberExtraInfo":n.operatorInfo=nD(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:oA,OpType:EA,PushChangedAttrValFlag:wA,GroupAttrInfo:kA}=P,YA=kA.map(LA=>{const{Key:SA,Val:OA,SubKeySeq:HA}=LA;return{key:SA,value:OA,sequence:HA}});return{changedKeyList:W,groupAttributeList:YA,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=AT[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 nD(s){const{ImageUrl:n,NickName:g,Role:I,UserId:E}=s;return{avatar:n,nick:g,role:I,userID:E}}function oh(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=(I=s[g]||[])==null?void 0:I.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 I}),n}class vm{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_TIP,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=xu(n);return new vm(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 I=0;I{n.forEach(I=>{g.userID===I.userID&&Object.assign(g,I)})}):this.content.memberList=n}_initNewGroupProfile(n){this.content.newGroupProfile={};const g=Object.keys(n);for(let I=0;I0&&this._handleGroupTipMessage(g),{conversationUpdateFieldList:I,messageList:g}}_emitGroupTipsEvent(s){var n;const{constants:{WORKFLOW_STEP:g}}=this._core,{messageList:I=[]}=((n=s?.result)===null||n===void 0?void 0:n[g.HANDLE_GROUP_TIPS_NOTIFICATION])||{};if(I.length>0){const{notificationCenter:E,OuterEvent:m}=this._core;E.emitOuterEvent(m.MESSAGE_RECEIVED,{name:m.MESSAGE_RECEIVED,data:I})}}_handleGroupTips(s,n=!0){const{Event:g,GroupTips:I}=s,E=new Map,m=[],D=[];for(let M=0,T=I.length;M{const{operationType:I}=g.payload;switch(I){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:I,operatorInfo:E}=s.payload,{groupID:m}=I,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])?mm(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:I}=this._core,E=Yi.getLocalGroup(s),m=g.getCurrentUserID(),{ownerID:D}=n;m===D&&E.updateGroup({ownerID:D,selfInfo:{role:I.GRP_MBR_ROLE_OWNER}})}_updateSelfRole(s,n){const{OuterConstant:g}=this._core;let I=g.GRP_MBR_ROLE_MEMBER;n===J_?I=g.GRP_MBR_ROLE_OWNER:n===zy&&(I=g.GRP_MBR_ROLE_ADMIN),s.updateSelfInfo({role:I})}_handleGroupMemberCountUpdated(s){const{memberCount:n,groupProfile:{groupID:g}}=s.payload,I=Yi.getLocalGroup(g),{utils:{isNumber:E}}=this._core;I&&E(n)&&I.memberCount!==n&&(I.memberCount=n,Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(g))}_handleGroupTipsRecover(s){const{utils:{isArray:n}}=this._core,{groupTipList:g}=s?.result||{};n(g)&&g.forEach(I=>{const{messageList:E}=this._handleGroupTips({Event:I.Event,GroupTips:[I]},!1);this._handleGroupTipMessage(E)})}_handleMemberGrantAdmin(s){const{OuterConstant:n}=this._core,{groupProfile:g,userIDList:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.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:I}=s.payload,E=this._core.common.getCurrentUserID(),{groupID:m}=g,D=Yi.getLocalGroup(m);D&&I.includes(E)&&(D.updateSelfInfo({role:n.GRP_MBR_ROLE_MEMBER}),Yi.emitGroupListUpdate(),Yi.updateConversationGroupProfile(m))}};class RQ{constructor(n){this.type=Wn.core.OuterConstant.MSG_GRP_SYS_NOTICE,this.content={},this._initContent(n)}static parseServerPushElement(n){const g=oh(n);return new RQ(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 I=0;I0&&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 I={};for(let E=0;E0?[I]:[],messageList:g}}_assembleMessage(s){const{message:{messageFactory:n},OuterConstant:g,utils:{randomInt:I}}=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 RQ(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=I(),E.random=I(),E.generateMessageID()),E}_handleConversationOptions(s,n){const{OuterConstant:g}=this._core,I={conversationID:g.CONV_SYSTEM,unreadCount:0,type:g.CONV_SYSTEM,subType:s.conversationSubType,lastMessage:null};return n&&I.unreadCount++,I}_handleGroupSysTemMessage(s,n){s&&n.forEach(g=>{const{operationType:I}=g.payload;switch(I){case q_:this._handleGroupJoinResult(g);break;case Qv:this._handleMemberKicked(g);break;case K_:this._handleGroupDismissed(g);break;case j_:this._handleGroupInvitedResult(g);break;case Zy:this._handleGroupQuitResult(g);break;case mQ:this._handleMessageRemindTypeSynced(g);break;case Cm:this._handleAVChatRoomMemberBanned(g)}})}_handleGroupJoinResult(s){const{groupProfile:n}=s.payload,{groupID:g,type:I}=n,E=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupJoinResult",` groupID:${g} type:${I} hasLocalGroup:${E}`),E||Ed(I)||(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,I=Yi.hasLocalGroup(g);this._core.ssoLog.debug("_handleGroupInvitedResult",` groupID:${g} hasLocalGroup:${I}`),I||Ul.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,I=Yi.hasLocalGroup(n);this._core.ssoLog.debug("_handleGroupQuitResult",` groupID:${n} type:${g} hasLocalGroup:${I}`),I&&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(Ed(n)){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core;g.deleteConversation(`${I}${s}`)}Yi.deleteLocalGroup(s),Yi.emitGroupListUpdate()}_updateConversationProfile(s,n){const{appStore:{conversationStore:g},OuterConstant:{CONV_GROUP:I}}=this._core,E=`${I}${s}`;g.getConversation(E)&&g.updateConversation(E,n)}},rD=new class{init(s){this._core=s,s.ssoLog.debug("GroupNotificationHandler.init"),Rv.init(s),wv.init(s);const{notificationCenter:n,InnerEvent:g}=s,{InnerEventSubType:I}=n;n.subscribeInnerEvent(g.MESSAGE_PUSH,I.GROUP_TIPS_NOTIFICATION,this._onNewGroupTipsNotification,this),n.subscribeInnerEvent(g.MESSAGE_PUSH,I.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){wv.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},wQ={required:!0,rules:["number"],allowEmpty:!1},Bd={required:!0,rules:["array"],allowEmpty:!1},aD={required:!0,rules:["object"],allowEmpty:!1},sT={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:Bd,memberCustomFieldFilter:{required:!1,rules:["array"],allowEmpty:!0}},addGroupMember:{groupID:vn,userIDList:Bd},deleteGroupMember:{groupID:vn,userIDList:Bd},setGroupMemberMuteTime:{groupID:vn,userID:vn,muteTime:Object.assign(Object.assign({},wQ),{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:Bd},markGroupMemberList:{groupID:vn,markType:Object.assign(Object.assign({},wQ),{customValidator:s=>!(s<1e3)||"markType must be greater than or equal to 1000."}),enableMark:{required:!0,rules:["boolean"],allowEmpty:!1},userIDList:Bd},initGroupAttributes:{groupID:vn,groupAttributes:aD},setGroupAttributes:{groupID:vn,groupAttributes:aD},deleteGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Bd),{allowEmpty:!0})},getGroupAttributes:{groupID:vn,keyList:Object.assign(Object.assign({},Bd),{allowEmpty:!0})},getGroupCounters:{groupID:vn,keyList:{required:!1,rules:["array"],allowEmpty:!0}},setGroupCounters:{groupID:vn,counters:aD},increaseGroupCounter:{groupID:vn,key:vn,value:wQ},decreaseGroupCounter:{groupID:vn,key:vn,value:wQ}},nT={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 rT=new class{constructor(){this._installedSubPlugins=[],this.groupDataHandler=Yi,this.groupAction=DQ,this.groupAttribute=vQ,this.groupMember=vv,this.groupCounter=tB,this.name="Group"}install(s,n=[]){this._core=s,Wn.init(s),Yi.init(s),DQ.init(s,this),vv.init(s,this),eD.init(s),tB.init(s),vQ.init(s),rD.init(s),s.helper.registerValidateConfig({auth:nT,params:sT}),this._installSubPlugins(n);const{notificationCenter:g,InnerEvent:I}=s;g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.DESTROY,this._dispose,this)}getInstalledSubPlugins(){return this._installedSubPlugins}_installSubPlugins(s){const{utils:{isArray:n}}=this._core;s&&n(s)&&s.forEach(g=>{var I;this._installedSubPlugins.includes(g.name)||((I=g.install)===null||I===void 0||I.call(g,this._core,this),this._installedSubPlugins.push(g.name))})}_reset(){Yi.reset(),vQ.reset(),tB.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 iB=new class{init(s){this.core=s}},_v="AV_MBR_LIST",aT="AV_BAN_MBR",bE={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},sh={GROUP_DISMISSED:5,QUIT_GROUP:8,AVCHATROOM_MEMBER_BANNED:21},gD=60,cD=2603,gT=2686,cT=2688,_Q=3122;class Tv{constructor(n){const{core:g,manager:I,groupID:E,getRequestParams:m,onSuccess:D,onFail:M}=n;this._name="Polling",this._core=g,this._manager=I,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 I=this._manager.getCurrentPollingInterval(this._groupID);this._runNextPolling(I)}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 nh{constructor(n){this._maxLength=n,this._map=new Map}set(n){var g;if(this._map.size>=this._maxLength){const I=((g=this._map.entries().next().value)===null||g===void 0?void 0:g[0])||"";this._map.delete(I)}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 Yu=s=>s===bE.GROUP_TIPS_HAS_NO_ROAMING||s===bE.GROUP_TIPS_HAS_ROAMING,TQ=s=>s===bE.GROUP_SYSTEM_MESSAGE;function Rm(s){const n=function(g){const{E:I,MCT:E,MR:m,MP:D,MTS:M,GId:T,MS:P,CCD:W,F_Account:oA,IsSys:EA,GInf:wA,MsgBody:kA}=g,YA=yo(g,["E","MCT","MR","MP","MTS","GId","MS","CCD","F_Account","IsSys","GInf","MsgBody"]);return Object.assign({Event:I,MsgClientTime:E,MsgRandom:m,MsgPriority:D,MsgTimeStamp:M,ToGroupId:T,MsgSeq:P,CloudCustomData:W,From_Account:oA,IsSystemMsg:EA,GroupInfo:lD(wA),MsgBody:lT(kA)},YA)}(s);return function(g){const{Event:I}=g;(Yu(I)||TQ(I))&&(g.From_Account=g.From_Account||"@TIM#SYSTEM"),E=I,(E===bE.BROADCAST_MESSAGE||(m=>m===bE.NORMAL_MESSAGE)(I))&&function(m){const{core:{OuterConstant:D}}=iB;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;Yu(I)&&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),TQ(I)&&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 lD(s){const n=s||{},{GN:g,GT:I,F_Hd:E,F_NN:m,F_Ll:D}=n,M=yo(n,["GN","GT","F_Hd","F_NN","F_Ll"]),T=Object.assign({GroupName:g,GroupType:I},M);return E&&(T.From_AccountHeadurl=E),m&&(T.From_AccountNick=m),D&&(T.From_AccountLevel=D),T}function lT(s){let n=s;Array.isArray(s)||(n=[s]);const g=n.map(I=>{const{O_Account:E,Opt:m,L_Account:D,RT:M,UDF:T,OpInf:P,OnlineInf:W,MsgMemberExtraInfo:oA}=I,EA=yo(I,["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:YA,NN:LA}=kA,SA=yo(kA,["Img","NN"]);return Object.assign({ImageUrl:YA,NickName:LA},SA)}(P)),oA&&(wA.MsgMemberExtraInfo=function(kA){return kA?.map(YA=>{const{Img:LA,NN:SA}=YA,OA=yo(YA,["Img","NN"]);return Object.assign({ImageUrl:LA,NickName:SA},OA)})}(oA)),W&&(wA.OnlineMemberInfo=function(kA){const{ET:YA,Num:LA}=kA;return{ExpireTime:YA,OnlineMemberNum:LA}}(W)),wA});return Array.isArray(s)?g:g[0]}var rh=new class{constructor(){this._name="MessageParser",this._sequenceList=new nh(200),this._messageIDList=new nh(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 I=this._handleMessageList(s,n);if(I.length===0)return;if(!g){const{appStore:{conversationStore:T},OuterConstant:{CONV_GROUP:P},common:{buildLastMessage:W}}=this._core,oA=W(I[I.length-1]);T.updateConversation(`${P}${s}`,{lastMessage:oA})}this._checkMessageStacked(I);const E=I.filter(T=>T.isModified===!0),m=I.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:I}=s;let E=[];this._avChatRoomHandler.isPollingSimplifiedMessage()&&!I?(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:I,messageHelper:E}}=this._core,m=this._avChatRoomHandler.isPollingSimplifiedMessage(),D=[],M=n.length;for(let T=0;Tg===bE.MESSAGE_REVOKED)(n)?(this._handleMessageRevoked(s),null):(g=>g===bE.LIVE_CUSTOM_DATA)(n)?(this._onLiveCustomData(s),null):(g=>g===bE.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 I=g.CONV_GROUP;s.elements.type===g.MSG_GRP_SYS_NOTICE&&(I=g.CONV_SYSTEM);const E=!!s.isSystemMessage,m=n.createMessage(Object.assign(Object.assign({},s),{conversationType:I,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:I,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:`${n.CONV_GROUP}${I}`,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:n}}=this._core,{ToGroupId:g,MsgSeq:I,MsgTimeStamp:E,MsgBody:m}=s,D=m?.Content||m?.MsgContent||"";this._emitEvent({name:n,data:D}),console.log(`${this._name}._onLiveCustomData groupID:${g} sequence:${I} 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,I=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:I}}=s;if(n(I))return;const{OnlineMemberNum:E=0,ExpireTime:m=gD}=I,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 oB=s=>{const{core:{store:n}}=iB;return(n.get("cloudConfig")||{})[s]},ah=s=>{const{core:{utils:{isUndefined:n}}}=iB;return!n(s)},NQ=()=>{const s=oB("polling_interval");return ah(s)?parseInt(s,10):300},sB=()=>{const s=oB("polling_simplified_msg");return ah(s)?parseInt(s,10):0};var Nv=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,I=n.getGroup(s);return I?I.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,I=Og.getLocalOnlineMemberCount(s);if(g(I)||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:${I.memberCount} from local.`),{code:0,data:{memberCount:I.memberCount}}})}_isExpired(s){const n=Og.getLocalOnlineMemberCount(s),g=Date.now(),I=g-n.lastSyncTime>1e3*n.expireTime,E=g-n.latestUpdateTime>1e4,m=g-n.lastReqTime>3e3;return I&&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:I=0,ExpireTime:E=gD}=g||{},m=Date.now(),D={lastSyncTime:m,latestUpdateTime:m,lastReqTime:m,memberCount:I,expireTime:E};return Og.updateLocalOnlineMemberCount(s,D),{memberCount:I}}catch(g){const I=new this._core.helper.ChatError({functionName:n,code:g?.errorCode,message:g?.errorInfo});throw console.error(`${this._name}.${n} fail:`,I),I}})}},Og=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,rh.init(s,this),s.ssoLog.debug("AVChatRoomHandler.init")}onAVChatRoomSystemNotification(s){const{OuterConstant:{GRP_AVCHATROOM:n}}=this._core,{GroupTips:g=[]}=s;for(let I=0;I0&&(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:I},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(),I(`${g}${T}`),Nv.getGroupOnlineMemberCount(T),M.length>0&&rh.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:I,apiMap:{quitGroup:E},ssoLog:m}=this._core;if(n.isUnlimitedAVChatRoom()){if(this._pollingInstanceMap.size>(()=>{const T=oB("polling_count_limit");return ah(T)&&T>0?parseInt(T,10):20})())throw new I.ChatError({code:cT,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:I=1,group:E}=s,{groupID:m}=E;return this._pollingRequestInfoMap.set(m,{longPollingKey:g,startSequence:I}),this._pollingIntervalMap.set(m,NQ()),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 Tv({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:sB()}:{longPollingKey:n,startSequence:g,simplifiedMessage:sB()}}_handleSuccess(s,n){const{ErrorCode:g}=n;if(g!==0){const{longPollingKey:I,startSequence:E}=this._pollingRequestInfoMap.get(s)||{};return void console.warn(`${this._name}._handleSuccess groupID:${s} key:${I} startSeq:${E} errorCode:${g}`)}this._hasJoinedAVChatRoom(s)&&this._handleResponseData(s,n)}_handleResponseData(s,n){const{Key:g,NextSeq:I,NextBroadcastSeq:E,RspMsgList:m=[],RspBroadcastMsgList:D=[]}=n;if(g&&I&&this._pollingRequestInfoMap.set(s,{longPollingKey:g,startSequence:I}),E&&E>this._startBroadcastSequence&&(this._startBroadcastSequence=E),m.length>0)this._getPollingNoMessageCount(s)!==0&&(this._updatePollingNoMessageCount(s,0),this._pollingIntervalMap.set(s,NQ())),rh.onMessageReceived(s,m);else{let M=this._getPollingNoMessageCount(s);if(M+=1,this._updatePollingNoMessageCount(s,M),M===(()=>{const T=oB("polling_no_msg_count");return ah(T)?parseInt(T,10):20})()){const T=NQ()+(()=>{const P=oB("polling_interval_plus");return ah(P)?parseInt(P,10):2e3})();this._pollingIntervalMap.set(s,T)}}D.length>0&&rh.onBroadcastMessageReceived(D)}_handleFailure(s,n){const{ssoLog:g,utils:{safeStringify:I}}=this._core;g.warn("polling",`${this._name}._handleFailure groupID:${s} error: ${I(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){rh.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:I,count:E}=(()=>{const m=oB("av_members_freq_limit");if(ah(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*I?(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 I=this._pollingInstanceMap.get(s);return I?.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:I}=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)}),I.info("longPollingCount",String(s),{moreMessage:`av:${m.join(",")} live:${D.join(",")} code: ${E}`,eventType:29})}}reset(s){this._stopPolling(s),this._startBroadcastSequence=1,rh.reset()}},Gv=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:I,group:{type:E}}}=g;return E===n.GRP_AVCHATROOM?I===n.JOIN_STATUS_ALREADY_IN_GROUP?g:Og.handleJoinGroupResult(g.data):g})}},IT=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:I}}=g;return I===n.GRP_AVCHATROOM&&Og.reset(s),g})}},bv=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:I}}=g;return I===n.GRP_AVCHATROOM&&Og.reset(s),g})}},wm=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:I}=this._core,{groupID:E}=s,m=n.getGroup(E);if(m?.type===I.GRP_AVCHATROOM&&g.checkBusinessCapabilityBits(_v)){if(Og.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 I=yield function(M,T){return pA(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}=I||{},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(I){const E=new g.ChatError({functionName:n,code:I?.errorCode,message:I?.errorInfo});throw console.error(`${this._name}.${n} fail:`,E),E}})}_handleMemberList(s){return s.map(n=>{const{Member_Account:g,NickName:I="",Avatar:E="",Remark:m="",JoinTime:D=0,Marks:M=[]}=n;return{userID:g,nick:I,avatar:E,remark:m,joinTime:D,marks:M,isOnline:!0}})}},_m=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:I},helper:E,OuterConstant:m}=this._core,{groupID:D}=s,M=g.getGroup(D);if(I(M))throw new E.ChatError({functionName:n,code:cD});if(M.type===m.GRP_AVCHATROOM){if(E.checkBusinessCapabilityBits(aT))return this._deleteGroupMember(s);throw new E.ChatError({functionName:n,code:_Q})}return this._parentPlugin.groupMember.deleteGroupMember(s)})}_deleteGroupMember(s){return pA(this,void 0,void 0,function*(){const n="_deleteGroupMember",{appStore:{groupStore:g},helper:I,ssoLog:E}=this._core,{groupID:m,duration:D=0,userIDList:M}=s;if(D===0)throw new I.ChatError({functionName:n,code:gT});try{return yield function(T,P){return pA(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(n,`${this._name}.${n} ok, groupID:${m}`),{code:0,data:{group:g.getGroup(m),userIDList:M}}}catch(T){throw new I.ChatError({functionName:n,code:T?.errorCode,message:T?.errorInfo})}})}},Qd=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:I,enableMark:E,userIDList:m=[]}=s,D=this._generateRequestData(s);try{const M=yield function(oA,EA){return pA(this,void 0,void 0,function*(){const{groupID:wA,operationType:kA,memberList:YA}=oA,LA={GroupId:wA,CommandType:kA,MemberList:YA};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:${I} 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:I,userIDList:E=[]}=s,m=I===!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=[],I=[];return s.length===n.length?(g.push(...n),{successUserIDList:g,failureUserIDList:I}):(n.forEach(E=>{s.find(m=>m.Member_Account===E)?g.push(E):I.push(E)}),{successUserIDList:g,failureUserIDList:I})}},kv=new class{init(s,n){s.ssoLog.debug("AVChatRoomAction.init"),Gv.init(s,n),IT.init(s,n),bv.init(s,n),wm.init(s,n),Nv.init(s,n),_m.init(s,n),Qd.init(s)}},Lv=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:I,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({});Og.hasPollingInstance(m)&&this.stopMessageLongPolling({groupID:m});const T=Og.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:I.GRP_LIVE};return Og.updateLocalLiveGroup(m,W),this._getLiveHistoryMessages({groupID:m,longPollingKey:D,startSequence:M}),Og.startMessageLongPolling({group:W,longPollingKey:D,startSequence:M})}stopMessageLongPolling(s){const{groupID:n}=s;return Og.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 I=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=[]}=I||{};n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages ok, groupID:${g} count:${E.length}`),E.length>0&&Og.handleLiveHistoryMessages(g,E)}catch(I){n.debug("_getLiveHistoryMessages",`${this._name}._getLiveHistoryMessages failed, groupID:${g} info:${I.message}`)}})}},Tm=new class{constructor(){this.name="AVChatRoom"}install(s,n){this._core=s,iB.init(s),Og.init(s,n),kv.init(s,n),Lv.init(s);const{notificationCenter:g,InnerEvent:I}=s,{InnerEventSubType:E}=g;g.subscribeInnerEvent(I.MESSAGE_PUSH,E.GROUP_SYSTEM_NOTIFICATION,this._onAVChatRoomSystemNotification,this),g.subscribeInnerEvent(I.LOGOUT,this._reset,this),g.subscribeInnerEvent(I.DESTROY,this._dispose,this)}_onAVChatRoomSystemNotification(s){Og.onAVChatRoomSystemNotification(s)}_reset(){Og.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 $a=new class{init(s){this.core=s}},Nm="message",nB="user",rB={OR:"or",AND:"and"},mI=20,uT=20,Uv=20,gh={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!s||!!(Array.isArray(s)&&s.length<=5)||"keywordList should be an array and length <= 5"},Gm={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>!s||!![rB.OR,rB.AND].includes(s)||"keywordListMatchType should be OR or AND"},EC={required:!1,rules:["number"],allowEmpty:!0,customValidator:s=>typeof s=="number"&&s>=1&&s<=100||"count must be a number between 1 and 100"},GQ={required:!1,rules:["string"],allowEmpty:!0},Fv={required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.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 I=!1;for(let E=0;E{const{OuterConstant:n}=$a.core;return!(!s?.startsWith(n.CONV_C2C)&&!s?.startsWith(n.CONV_GROUP)&&s!==n.CONV_SYSTEM)||"conversationID is invalid"}},bm=s=>({required:!1,rules:["number"],allowEmpty:!0,customValidator:n=>typeof n=="number"&&n>=0||`${s} should be a number >= 0';`}),ID={required:!1,rules:["string"],allowEmpty:!0,customValidator:s=>{const{OuterConstant:n}=$a.core;return!![n.GENDER_FEMALE,n.GENDER_MALE].includes(s)||"gender is invalid"}},km={searchCloudMessages:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,senderUserIDList:{required:!1,rules:["array"],allowEmpty:!0,customValidator:s=>!!(Array.isArray(s)&&s.length<=5)||"senderUserIDList should be an array and length <= 5"},messageTypeList:Ov,conversationID:Pv,timePosition:bm("timePosition"),timePeriod:bm("timePeriod")},searchCloudUsers:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,miniBirthday:bm("miniBirthday"),maxBirthday:bm("maxBirthday"),gender:ID},searchCloudGroupMembers:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,groupTypeList:Fv,groupIDList:{required:!1,rules:["array"],allowEmpty:!0}},searchCloudGroups:{keywordList:gh,keywordListMatchType:Gm,cursor:GQ,count:EC,groupTypeList:Fv}},uD={searchCloudMessages:!0,searchCloudUsers:!0,searchCloudGroupMembers:!0,searchCloudGroups:!0};var ED=new class{constructor(){this.name="CloudSearch"}install(s){this._core=s,$a.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:uD,params:km})}searchCloudMessages(s){return pA(this,void 0,void 0,function*(){try{const{OuterConstant:n,helper:g}=this._core,{conversationID:I,timePeriod:E,timePosition:m}=s,D=yo(s,["conversationID","timePeriod","timePosition"]),M=Object.assign({count:100},D);I&&(I.startsWith(n.CONV_C2C)?M.account=I.replace(n.CONV_C2C,""):I.startsWith(n.CONV_GROUP)&&(M.groupID=I.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:HA,senderUserIDList:se,messageTypeList:oe,endTime:_i,startTime:Ti,cursor:bt,account:Ni,groupID:gs}=LA,De={Count:SA,KeywordList:OA,MatchType:HA,SendUserIDList:se,MsgTypeList:oe,EndTime:_i,StartTime:Ti,Cursor:bt,PeerAccount:Ni,GroupID:gs};return $a.core.common.buildAndSendPacket({servcmd:"message_search.query",data:De})})}(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:HA,UserID:se}=LA,oe=HA?`${n.CONV_GROUP}${HA}`:`${n.CONV_C2C}${se}`;if(this._isSearchingAllConversations(s)&&OA>1)return{conversationID:oe,messageCount:OA,messageList:[]};const _i=SA.map(Ti=>g.isEmpty(HA)?function(bt,Ni){const gs=Ni.OuterConstant.CONV_C2C,De=Ni.message.messageHelper.parseServerPushMessage(bt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},De),{conversationType:gs,flow:"in"}));return Bt.setElement(De.elements),Bt}(Ti,this._core):function(bt,Ni){const gs=Ni.OuterConstant.CONV_GROUP,De=Ni.message.messageHelper.parseServerGroupMessage(bt),Bt=Ni.message.messageFactory.createMessage(Object.assign(Object.assign({},De),{conversationType:gs,flow:"in"}));return Bt.setElement(De.elements),Bt}(Ti,this._core));return{conversationID:oe,messageCount:OA,messageList:_i}}),cursor:EA,totalCount:oA},successLog:{message:kA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:Nm,functionName:"searchCloudMessages"})}})}searchCloudUsers(s){return pA(this,void 0,void 0,function*(){var n;try{const{keywordListMatchType:g,count:I=uT}=s,E=yo(s,["keywordListMatchType","count"]),m=Object.assign({count:I,keywordListMatchType:g===rB.AND?1:0},E);this._setBirthdayRangeParams(m,s);const D=yield function(kA){return pA(this,void 0,void 0,function*(){const{count:YA,keywordList:LA,keywordListMatchType:SA,miniBirthday:OA,maxBirthday:HA,cursor:se,gender:oe}=kA,_i={Count:YA,Keywords:LA,KeywordMatchType:SA,Cursor:se,UserBirthStart:OA,UserBirthEnd:HA,Gender:oe};return $a.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: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,YA=oA.length;kA({tag:se.Tag,value:se.StrValue})),HA=(n=this._core.user.userProfile)===null||n===void 0?void 0:n.createProfile(LA,OA);wA.push(HA)}return{code:0,data:{searchResultList:wA,cursor:W,totalCount:P},successLog:{message:EA}}}catch(g){const{errorCode:I,errorInfo:E}=g||{};this._handleError({errorCode:I,errorInfo:E,searchType:nB,functionName:"searchCloudUsers"})}})}searchCloudGroupMembers(s){return pA(this,void 0,void 0,function*(){try{const{count:n=Uv,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===rB.AND?1:0},I),m=yield function(wA){return pA(this,void 0,void 0,function*(){const{count:kA,keywordList:YA,keywordListMatchType:LA,groupTypeList:SA,cursor:OA,groupIDList:HA}=wA,se={Count:kA,Keywords:YA,KeywordMatchType:LA,Cursor:OA,GroupType:SA,GroupIdList:HA};return $a.core.common.buildAndSendPacket({servcmd:"group_member_search.query",data:se})})}(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:YA,GroupType:LA,GroupFaceUrl:SA,GroupMemberUserName:OA,GroupMemberUserID:HA,GroupMemberNameCard:se,GroupMemberAvatar:oe=""}=wA,_i={groupID:kA,name:YA,type:LA,avatar:SA},Ti={userID:HA,nick:OA,nameCard:se,avatar:oe};if(EA.has(kA)){const bt=EA.get(kA);bt.memberList.push(Ti),EA.set(kA,bt)}else EA.set(kA,{groupInfo:_i,memberList:[Ti]})}),{code:0,data:{searchResultList:[...EA.values()],cursor:P,totalCount:W},successLog:{message:oA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:nB,functionName:"searchCloudGroupMembers"})}})}searchCloudGroups(s){return pA(this,void 0,void 0,function*(){try{const{count:n=mI,keywordListMatchType:g}=s,I=yo(s,["count","keywordListMatchType"]),E=Object.assign({count:n,keywordListMatchType:g===rB.AND?1:0},I),m=yield function(EA){return pA(this,void 0,void 0,function*(){const{count:wA,keywordList:kA,keywordListMatchType:YA,groupTypeList:LA,cursor:SA}=EA,OA={Count:wA,Keywords:kA,KeywordMatchType:YA,Cursor:SA,GroupType:LA};return $a.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:YA,GroupIntroduction:LA,GroupMemberNum:SA,GroupName:OA,GroupOwnerTinyID:HA,GroupOwnerUserID:se,GroupOwnerUserName:oe,GroupType:_i,GroupAddOption:Ti,GroupInviteOption:bt}=wA;return{avatar:kA,groupID:YA,introduction:LA,memberCount:SA,name:OA,ownerTinyID:HA,ownerID:se,ownerNick:oe,type:_i,joinOption:Ti,inviteOption:bt}}(EA))||[],cursor:P,totalCount:W},successLog:{message:oA}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};this._handleError({errorCode:g,errorInfo:I,searchType:nB,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:I}=this._core;let E=s;throw s===60020?E="SearchUnable":g!==Nm&&s===27003?E="SearchParamsError":g!==Nm&&s===60018&&(E="SearchOverLimit"),new I.ChatError({code:E,message:n})}_isSearchingAllConversations(s){return this._core.helper.isEmpty(s.conversationID)}_setBirthdayRangeParams(s,n){const{miniBirthday:g,maxBirthday:I}=n;g!==void 0&&(s.miniBirthday=g,I===void 0&&(s.maxBirthday=4294967295)),I!==void 0&&(s.maxBirthday=I)}};function ch(s,n){return Math.round(Number(s)*Math.pow(10,n))/Math.pow(10,n)}const xv="qualityStat",dD="im-ssolog-quality-stat";var CD;(function(s){s[s.ONLINE=8]="ONLINE"})(CD||(CD={}));const Lm="networkRTT",lh="messageE2EDelay",aB="sendMessageC2C",Ih="sendMessageGroup",uh="sendMessageGroupAV",gB="sendMessageRichMedia",cB="cosUpload",dC="messageReceivedGroup",bQ="messageReceivedGroupAVPush",kQ="messageReceivedGroupAVPull",ET={[Lm]:2,[lh]:3,[aB]:4,[Ih]:5,[uh]:6,[gB]:7,[dC]:8,[bQ]:9,[kQ]:10,[cB]:11},Yv=[aB,Ih,uh,gB,cB],Eh=[dC,bQ,kQ],lB=[Lm,lh,aB,Ih,uh,gB,cB,dC,bQ,kQ],hD={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},Um="quality_stat";var LQ=new class{constructor(){this._messageStatsMap=new Map,this._userSideErrorCodes=new Set(Object.values(hD))}init(s){this._core=s,Object.values(Yv).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:I,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,I);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:I,failedCountOfUserSide:E}=n,m=ch(I/g*100,2),D=I+E,M=ch(D/g*100,2),T=this._calcAverageValue(n,s);return this._resetStat(s),{total_count:g,success_count_business:I,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 I=(g=n?.code)!==null&&g!==void 0?g:n?.errorCode;if(this._isUserSideError(I)){const E=this._getSendMessageSpecifiedKey(s),m=E&&this._messageStatsMap.get(E);m&&m.failedCountOfUserSide++}}_handleSendCost(s,n){const g=this._getSendMessageSpecifiedKey(s),I=g&&this._messageStatsMap.get(g);I&&(I.costSum+=Date.now()-n,I.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:I,MSG_FILE:E,CONV_C2C:m,CONV_GROUP:D,GRP_AVCHATROOM:M}=this._core.OuterConstant;if([n,g,I,E].includes(s.type))return gB;if(s.conversationType===m)return aB;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?uh:Ih}}_calcAverageValue(s,n){return s.costCount===0?0:Math.round(n===cB?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)}},UQ=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:I},ssoLog:E}=this._core;if(g(n)||!this._currentCycleStats.has(n))return void E.debug("addMessageSequence",`${xv}.addMessageSequence invalid key:${n}`);const{conversationID:m,sequence:D}=s,M=m.replace(I,""),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&&(I+=m.length,g+=M-D+1)}),g===0?null:(this._transferCycleDataOptimized(s),{total_count:g,success_count_business:I,percent_business:ch(I/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(Eh).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((I,E)=>{const m=I.dirty?[...I.sortedSequences].sort((D,M)=>D-M):I.sortedSequences;g.set(E,{sortedSequences:m,minSeq:I.minSeq,maxSeq:I.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:I}=this._core.appStore,E=I.getGroup(s.to);if(!E)return null;const{type:m}=E;return m===g?kQ:dC}}_insertToLastCycle(s,n){n.dirty&&(n.sortedSequences.sort((I,E)=>I-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,I=s.length-1;for(;g<=I;){const E=Math.floor((g+I)/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:I}}=this._core,E=[g,I];n.forEach(m=>{!E.includes(m.type)&&m.clientTime>0&&this.addMessageDelay(m.clientTime)})}_calculateAverageDelay(s){return s===0?0:ch(this._totalDelay/s,1)}_calculatePercentage(s,n){return ch(s/n*100,2)}},Vv=new class{init(s){this.core=s}},dT=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:I,LOGOUT:E,DESTROY:m},constants:{WORKFLOW_NAME:D,WORKFLOW_STEP:M}}=s;Vv.init(s),LQ.init(s),UQ.init(s),FQ.init(s),n.registerWorkflowStep(D.SYNC_SERVER_INFO_AFTER_LOGIN,M.QUALITY_REPORT,this.handleLoginSuccess,this),g.subscribeInnerEvent(I,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,I=s.get("cloudConfig")||{},{q_rpt_interval:E}=I,m=g(E)?12e4:Number(E);n.taskScheduler.addTask({id:Um,intervalMs:m,callback:this.report,context:this})}report(){this._wholePeriod=!0;const s=[...lB.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:I}=s;g===n.MESSAGE_SEND_SUCCESS_RATE&&LQ.dispatchSendStats(I)}_needSkipReport(){return this._isSDKAppIDInBlacklist()&&!this._isTinyIDInWhitelist()}_isSDKAppIDInBlacklist(){const{store:s,utils:n}=this._core,g=s.get("cloudConfig")||{},I=s.get("instance")||{},{sdkAppId:E}=I,{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")||{},I=s.get("login")||{},E=Number(I.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:ET[s],timestamp:Date.now(),network_type:CD.ONLINE,extension:""};return Object.assign(Object.assign({},g),n)}_getStatResultByKey(s){switch(s){case lh:return FQ.getStatResult();case aB:case Ih:case uh:case gB:case cB:return LQ.getStatResult(s);case dC:case bQ:case kQ:return UQ.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:I,channel:E}=Vv.core,m="imopenstat.tim_web_report_v2",D=I.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=`${xv}._cacheFailedLogs`;let g=[...this._failedLogsCache.get(dD)||[],...s];g.length>10&&(g=g.slice(g.length-10),console.log(`${n} logs overflow, keeping last 10 items`)),this._failedLogsCache.set(dD,g),console.log(`${n} count: ${g.length}`),this._pendingReports=[]}_reset(){const{helper:s}=this._core;s.taskScheduler.removeTask(Um)}_dispose(){const{notificationCenter:s,InnerEvent:{QUALITY_STAT:n,LOGOUT:g,DESTROY:I}}=this._core;s.unSubscribeInnerEvent(n,this._handleQualityStat,this),s.unSubscribeInnerEvent(g,this._reset,this),s.unSubscribeInnerEvent(I,this._dispose,this),this._reset(),FQ.dispose(),UQ.dispose()}};const gl=new class{init(s){this.core=s}};function Jv(s){return pA(this,void 0,void 0,function*(){var n;const{message:g,user:I,appStore:E,constants:{OuterConstant:m}}=gl.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;gl.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:P,latestNick:W,isSentByMe:!1})}}const{data:M}=(yield I.userProfile.getMyProfile())||{};if(M){const{avatar:T,nick:P}=M;g.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:s,latestAvatar:T,latestNick:P,isSentByMe:!0})}})}function Hv(s){return pA(this,void 0,void 0,function*(){const n=s.map(g=>g.revoker);try{const g=yield function(I){return pA(this,void 0,void 0,function*(){var E,m;const D=yield(E=gl.core.user.userProfile)===null||E===void 0?void 0:E.getUserProfile({userIDList:I});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(I=>{const{revoker:E}=I;g[E]&&(I.revokerInfo.nick=g[E].nick||"",I.revokerInfo.avatar=g[E].avatar||"",I.revokerInfo.userID=E)})}catch(g){console.debug(g)}})}const BD=1,qv=2,dh=20,OQ=2500,Kv=1,Ch=300;function PQ(s){return pA(this,void 0,void 0,function*(){var n,g;const{appStore:I,utils:{isEmpty:E},common:{getCurrentUserID:m},notificationCenter:D,OuterEvent:M,OuterConstant:{CONV_C2C:T}}=gl.core,{messageList:P,conversationID:W}=s,oA=I.conversationStore.getConversationMap();let EA=(n=oA.get(W))===null||n===void 0?void 0:n.peerReadTime;if(!EA){const kA=W.replace(T,""),YA=yield function(LA){return pA(this,void 0,void 0,function*(){const SA={To_Account:LA};return gl.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:SA})})}([kA]);if(YA){const{ReadTime:LA}=YA;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,I.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 jv=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:I,CONV_GROUP:E},InnerEvent:{HISTORY_MESSAGE_FETCHED:m},notificationCenter:D}=this._core,{conversationID:M,nextReqMessageID:T}=s,P=dh;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 n.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:Number(T),count:P,direction:g.FORWARD,shouldMarkCompleted:!0}):M.startsWith(I)&&(oA=yield n.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,messageID:T,count:P,direction:g.FORWARD,shouldMarkCompleted:!0})),oA){const{nextReqMessageIDFromServer:EA,hasNoMoreHistoryMessage:wA,messageList:kA}=oA,YA=n.messageDataHandler.prependLocalMessageList({messageList:kA,conversationID:M});(function(se){const{appStore:oe,message:_i,OuterConstant:Ti}=gl.core,bt=oe.conversationStore.getConversation(se),Ni=_i.messageDataHandler.getLocalMessageList(se);if(!bt||Ni.length===0||se===Ti.CONV_SYSTEM)return;const gs=[];for(let Bt=0;BtUA.isRevoked).length;De=gs.length-bt.unreadCount-Bt}else De=gs.length-bt.unreadCount;for(let Bt=0;Btse.isRevoked);yield Hv(SA),D.emitInnerEvent(m,YA);const OA={nextReqMessageID:wA?"":String(EA),messageList:LA,isCompleted:wA},HA=LA.map(se=>se.sequence);return{code:0,data:OA,successLog:{message:`conversationID: ${M} nextReqMessageID: ${T} availableLocalMessagesCount: ${W} sequenceList: ${JSON.stringify(HA)}`}}}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:I}=n||{};throw new this._core.helper.ChatError({code:g,message:I,moreMessage:`options: ${this._core.utils.safeStringify(s)}`})}})}getMessageListHopping(s){return pA(this,void 0,void 0,function*(){var n,g;const{OuterConstant:{Direction:I,CONV_C2C:E,CONV_GROUP:m},utils:{safeStringify:D}}=this._core,{conversationID:M,sequence:T,time:P,direction:W=I.FORWARD}=s,{utils:{isEmpty:oA},message:EA,notificationCenter:wA,InnerEvent:{HISTORY_MESSAGE_FETCHED:kA}}=this._core;if(![I.BACKWARD,I.FORWARD].includes(W))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${D(s)}`});let{count:YA=dh}=s;YA=YA>dh?dh:YA;let LA=null;if(M.startsWith(m)){if(LA=yield EA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:M,sequence:T,count:YA,direction:W}),LA){const{nextReqMessageIDFromServer:SA,hasNoMoreHistoryMessage:OA,messageList:HA,invisibleSequenceList:se}=LA;if(this._core.message.messageDataHandler.storeSparseMessageList(HA),wA.emitInnerEvent(kA,HA),W===I.FORWARD){const oe=OA&&SA<1;return{code:0,data:{messageList:HA,isCompleted:oe,nextMessageSeq:oe?"":SA}}}if(W===I.BACKWARD){if(oA(HA)&&oA(se))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const oe=((n=HA?.[HA.length-1])===null||n===void 0?void 0:n.sequence)||0,_i=((g=se?.[se.length-1])===null||g===void 0?void 0:g.sequence)||0;return{code:0,data:{messageList:HA.filter(Ti=>Ti.sequence>=T),isCompleted:!OA,nextMessageSeq:OA?Math.max(oe,_i)+1:""}}}return{code:0,data:LA}}}else if(M.startsWith(E)&&(LA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:M,count:YA+1,time:P,direction:W}),LA)){const{messageList:SA,lastMessageTime:OA,hasNoMoreHistoryMessage:HA}=LA;return wA.emitInnerEvent(kA,SA),HA||(W===I.FORWARD?SA.shift():SA.pop()),EA.messageDataHandler.storeSparseMessageList(SA),yield PQ({messageList:SA,conversationID:M}),{code:0,data:{messageList:SA,isCompleted:HA,nextMessageTime:HA?"":OA}}}})}clearHistoryMessage(s){return pA(this,void 0,void 0,function*(){var n;const{appStore:g,common:{ChatError:I,getCurrentUserID:E},OuterConstant:{CONV_C2C:m,CONV_GROUP:D},apiMap:M,message:T}=this._core,P=g.conversationStore.getConversation(s);if(!P)throw new I({code:OQ});const W={fromAccount:E()},{type:oA}=P;oA===m?(W.type=BD,W.toAccount=s.replace(m,"")):oA===D&&(W.type=qv,W.toGroupID=s.replace(D,""));try{return yield(n=M?.setMessageRead)===null||n===void 0?void 0:n.call(M,{conversationID:s}),(yield function(wA){return pA(this,void 0,void 0,function*(){const{fromAccount:kA,type:YA,toAccount:LA,toGroupID:SA}=wA,OA={From_Account:kA,Type:YA,To_Account:LA,ToGroupid:SA};return gl.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:n}=this._core;n.conversationStore.updateConversation(s,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:s,nextReqMessageID:n}){const{OuterConstant:{CONV_C2C:g,CONV_GROUP:I}}=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(I)&&(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:I}=this._core;return nn.startsWith(E)?EA.ID===g:String(EA.sequence)===g),W=oA>I?oA-I:0,T=oA):W=M>I?M-I:0,P.messageList=D.slice(W,oA),P.isCompleted=T<=I&&m.messageHistory.completedHistoryConversations.has(n),P.isCompleted?P.nextReqMessageID="":P.nextReqMessageID=this._generateNextReqMessageID({conversationID:n,targetIndex:W}),n.startsWith(E)&&(yield Jv(n),yield PQ({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}}},IB=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:I,InnerEvent:E}}=s;n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),n.registerWorkflowStep(g.SYNC_SERVER_INFO_AFTER_RE_ONLINE,I.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:I}}=this._core;if(I(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=[],I=[];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:I})),g.push(M.replace(n.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:g,groupTipList:I}})}_recoverGroupHistoryForConversation(s){return pA(this,arguments,void 0,function*({conversationID:n,localLastMessageSequence:g,serverLastMessageSequence:I,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,YA=I-g,LA=Math.min(20,YA),SA={},OA=yield oA.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:n,sequence:g+LA,direction:P.Direction.FORWARD,count:LA}),{nextReqMessageIDFromServer:HA,hasNoMoreHistoryMessage:se,messageList:oe,serverGroupTipList:_i}=OA;m(_i)&&E.push(..._i);const Ti=se&&HA<0,bt=[];if(m(oe)&&(oe.forEach(Ni=>{oA.messageReceiver.groupMessageReceiver.updateMessageProfile(Ni),Ni.from===P.CONV_SYSTEM&&(Ni.isSystemMessage=!1),oA.messageDataHandler.storeConversationMessage(Ni)&&!M(Ni.payload)&&(bt.push(Ni),Ni._isExcludedFromLastMessage||(SA.lastMessage=kA(Ni)))}),bt.length>0&&W.emitOuterEvent(T.MESSAGE_RECEIVED,{name:T.MESSAGE_RECEIVED,data:bt})),!Ti&&oe.length>0){const Ni=oe[oe.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:n,localLastMessageSequence:Ni,serverLastMessageSequence:I,groupTipList:E})}D(SA.lastMessage)&&(SA.lastMessage.messageForShow=wA(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,I]of n){const E=Array.from(I.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),I=g[g.length-1];return I?.sequence}_shouldRecoverHistory(s){const{localLastMessageSequence:n,serverLastMessageSequence:g}=s;if(typeof n!="number"||typeof g!="number")return!1;const I=g-n;return g!==0&&n>0&&I>=Kv&&I{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:I}={}}=n,E=this._getLocalLastMessageTime(g);this._shouldRecoverC2CHistory({localLastMessageTime:E,serverLastMessageTime:I})&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:E,serverLastMessageTime:I}))})))})}_shouldRecoverC2CHistory(s){const{localLastMessageTime:n,serverLastMessageTime:g}=s,I=g-n;return n>0&&I>=1&&I<=600}_recoverHistoryForC2CConversation(s){return pA(this,void 0,void 0,function*(){var n;const{conversationID:g,localLastMessageTime:I,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:YA}}=this._core;try{const LA={},SA=yield EA.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:g,direction:W.Direction.BACKWARD,time:I,count:20});if(M(SA))return;const{hasNoMoreHistoryMessage:OA,messageList:HA}=SA,se=[];m(HA)&&(HA.forEach(_i=>{EA.messageDataHandler.storeConversationMessage(_i)&&!M(_i.payload)&&(se.push(_i),_i._isExcludedFromLastMessage||(LA.lastMessage=YA(_i)))}),se.length>0&&oA.emitOuterEvent(P.MESSAGE_RECEIVED,{name:P.MESSAGE_RECEIVED,data:se}));const oe=(n=HA[HA.length-1])===null||n===void 0?void 0:n.time;!OA&&oe>E&&(yield this._recoverHistoryForC2CConversation({conversationID:g,localLastMessageTime:oe,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:n}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(s))return this._lastMessageTimeMapOnDisconnect.get(s);const g=n.messageDataHandler.getLocalMessageList(s),I=g[g.length-1];return I?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},uB=new class{constructor(){this.name="HistoryMessage"}install(s){this._core=s,gl.init(s),jv.init(s),IB.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),IB.dispose()}_reset(){IB.reset()}},QD=new class{init(s){this.core=s}},CC=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:I}}=this._core;try{if(!I(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:I}}=this._core,{atomicStoreID:E}=s;try{I(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:I,eventCode:E,eventResult:m,eventMessage:D,moreMessage:M,extensionMessage:T}=s;g.createSSOLogData({method:T,code:I,message:D,eventType:30,costTime:E,uiPlatform:m,moreMessage:M}).end(!0)}catch(I){g.debug(`reportRoomEngineEvent Report failed: ${n(I)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},xQ=new class{constructor(){this.name="DataReport"}install(s){this._core=s;const{notificationCenter:n,InnerEvent:{LOGOUT:g,DESTROY:I}}=s;QD.init(s),CC.init(s),n.subscribeInnerEvent(g,this._reset,this),n.subscribeInnerEvent(I,this._dispose,this)}_reset(){CC.reset()}_dispose(){const{notificationCenter:s,InnerEvent:{LOGOUT:n,DESTROY:g}}=this._core;s.unSubscribeInnerEvent(n,this._reset,this),s.unSubscribeInnerEvent(g,this._dispose,this),CC.dispose()}};let Fm=sr.STANDARD,EB=[];Fm=sr.STANDARD,EB=[ZC,eC,tC,iC,vc,dT,uB,xQ,RE,vi,jn,rT,Tm,ED,VI];function dB(s,n){const{operationType:g,memberInfoList:I,operatorInfo:E}=s||{};let m={};if(vs(I)?vs(E)||(m=E):g!==_g.JOINED&&g!==_g.KICKED&&g!==_g.ADMIN_SET&&g!==_g.ADMIN_CANCELED||(m=Object.assign({},I[0])),!vs(m)){const{nick:D="",avatar:M=""}=m;n.nick=D,n.avatar=M}}const YQ=s=>({lastTime:s?.time||s?.lastTime||0,lastSequence:s?.sequence||s?.lastSequence||0,fromAccount:s?.from||s?.fromAccount||"",messageForShow:Wc(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 VQ=Object.freeze({__proto__:null,ChatError:as,WorkflowManager:Rs,buildAndSendPacket:ag,buildLastMessage:YQ,get builtInPlugins(){return EB},checkBusinessCapabilityBits:en,deepMerge:sd,getCurrentUserID:Ar,getErrorMessage:ss,getMessagePreviewText:Wc,isC2CConv:s=>l(s)&&s.slice(0,3)===ba.CONV_C2C,isCommunity:zr,isGroupConv:s=>l(s)&&s.slice(0,5)===ba.CONV_GROUP,isInternational:Ml,isTopic:jc,isUnlimitedAVChatRoom:function(){var s;return!!(!((s=me.store.get("instance"))===null||s===void 0)&&s.unlimitedAVChatRoom)},liteChatInstanceMap:Ea,registerInterceptor:Sc,registerValidateConfig:Kc,requireAuth:td,get sdkEdition(){return Fm},setGroupTipsUserInfo:dB,t:Su,updateGroupAtInfo:(s,n)=>{const{CONV_AT_ME:g,CONV_AT_ALL:I,CONV_AT_ALL_AT_ME:E}=ko;if(function(M,T){const{CONV_AT_ME:P,CONV_AT_ALL:W,CONV_AT_ALL_AT_ME:oA}=ko,{groupID:EA,sequence:wA}=M;let kA=!1;return zr({groupID:EA})&&T.forEach(YA=>{YA.messageSequence===wA&&(YA.atTypeArray.includes(P)&&M.groupAtType.includes(W)&&(YA.atTypeArray=[oA]),YA.atTypeArray.includes(W)&&M.groupAtType.includes(P)&&(YA.atTypeArray=[oA],YA.__random=M.__random,YA.__sequence=M.__sequence),kA=!0)}),kA}(s,n))return;let m=[...s.groupAtType];m.includes(g)&&m.includes(I)&&(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:Dr,validateParameters:nI});class $I{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return $I._instance||($I._instance=new $I),$I._instance}static setInstance(n){$I._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 I=[];I=p(n)?n:[n];const E=I.findIndex(D=>D?.name==="AVChatRoom"),m=E>-1?I.splice(E,1):[];I.forEach(D=>{this._isPluginInstalled(D.name)||(D&&Mg(D.install)?(g.add(D.name),Mg(D.getInstalledSubPlugins)?(m?.forEach(M=>g.add(M?.name)),D.install(dr.getInstance().exposeApiForPlugin(),m)):D.install(dr.getInstance().exposeApiForPlugin()),Mg(D.handleLoginSuccess)&&this._isLoggedIn()&&D.handleLoginSuccess()):Mg(D)?(g.add(D.name),D(dr.getInstance().exposeApiForPlugin()),Mg(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=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}}var CB=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(s){return this._conversationMap.get(s)}updateConversation(s,n,g){const{emit:I=!0,needSort:E=!1}=g||{},m=this._conversationMap.get(s);m&&!vs(n)&&(Object.keys(n).forEach(D=>{m[D]=n[D]}),I&&me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED,{needSort:E}))}deleteConversation(s){this._conversationMap.has(s)&&(this._conversationMap.delete(s),me.notificationCenter.emitInnerEvent(so.CONVERSATION_UPDATED))}},JQ=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&&!vs(n)&&Object.keys(n).forEach(I=>{g[I]=n[I]})}},HQ=new class{constructor(){this._messagesByConversation=new Map}updateMessage(s,n,g){var I;const{operation:E,updateUnreadCount:m=!0}=g,D=yo(g,["operation","updateUnreadCount"]),M=[];for(const T of n){const P=(I=this._messagesByConversation.get(s))===null||I===void 0?void 0:I.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;jc(g)?me.notificationCenter.emitInnerEvent(pu[s],n):me.notificationCenter.emitInnerEvent(s,n)}},nc=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)}},pD=Object.freeze({__proto__:null,conversationStore:CB,groupStore:JQ,messageStore:HQ,userStore:nc});class dr{static getInstance(){return dr._instance||(dr._instance=new dr),dr._instance}static setInstance(n){dr._instance=n}constructor(){this._experimentalApiMap={statTUIKeyFeatures:this.statKeyFeatureUsage.bind(this),setApplicationID:this.setApplicationID.bind(this)},this._apiHandlersMap={},this._apiMap={on:me.notificationCenter.subscribeOuterEvent.bind(me.notificationCenter),off:me.notificationCenter.unSubscribeOuterEvent.bind(me.notificationCenter),destroy:this.destroy.bind(this),callExperimentalAPI:this.callExperimentalAPI.bind(this),use:$I.getInstance().installExternalPlugin.bind($I.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(n){me.ssoLog.debug("registerPlugin",n)}statKeyFeatureUsage(n){me.ssoLog.debug("statTUIKeyFeatures",n)}setLogLevel(n){me.ssoLog.debug("setLogLevel",n),me.ssoLog.setLogLevel(n)}setApplicationID(n){me.store.set("instance",{applicationID:n})}getApiMap(){return this._apiMap}setApiMap(n){this._apiMap=n}registerApi(n){const{common:{timeManager:g},utils:{safeStringify:I}}=me,{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),UI.includes(E)&&me.ssoLog.debug(E,`${E} start params: ${I(T)}`),Dr(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 me.ssoLog.error(E,`${E} fail ${wA?.message||wA?.errorMessage})`,{error:wA,costTime:g.getServerTimeMs()-P,eventType:W,method:E}),wA}})}registerExperimentalAPI(n,g,I){const E=I||n;this._experimentalApiMap[n]=g[E].bind(g)}destroy(){return pA(this,void 0,void 0,function*(){var n,g;try{!((n=me.store.get("login"))===null||n===void 0)&&n.isLogin&&(yield this._apiMap.logout()),me.notificationCenter.emitInnerEvent(so.DESTROY)}catch(I){console.debug("destroy error: ",I)}finally{me.notificationCenter.emitOuterEvent(yr.SDK_DESTROY,{SDKAppID:(g=me.store.get("instance"))===null||g===void 0?void 0:g.sdkAppId}),Ea.clear(),$I.getInstance().clear(),Rs.getInstance().destroy(),me.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:so,InnerEventSubType:me.notificationCenter.InnerEventSubType,OuterEvent:yr,OuterConstant:ko,SignalingEvent:Jc,helper:Object.assign(Object.assign(Object.assign({},me.utils),me.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Sc,registerValidateConfig:Kc,checkBusinessCapabilityBits:en,registerWorkflowStep:Rs.getInstance().registerWorkflowStep.bind(Rs.getInstance()),ChatError:as}),apiMap:this._apiMap},me),{constants:Object.assign(Object.assign({},Wa),me.constants),common:Object.assign(Object.assign(Object.assign({},VQ),me.common),{workflowManager:Rs.getInstance()}),utils:me.utils,appStore:pD})}callExperimentalAPI(n,g){return me.ssoLog.debug(`callExperimentalAPI.${n} start params: ${me.utils.safeStringify(g)}`),this._experimentalApiMap[n]?this._experimentalApiMap[n](g):(me.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${n} not found, params: ${me.utils.safeStringify(g)}`),Promise.reject(new as({code:ua.INVALID_OPERATION})))}_isPromiseLike(n){return n!==null&&typeof n=="object"&&typeof n.then=="function"}_handleAsyncResult(n,g,I,E){return n.then(m=>(this._reportApiSuccessLog({result:m,apiName:g,eventType:I,startTime:E}),m)).catch(m=>{throw me.ssoLog.error(g,`${g} fail ${m?.message||m?.errorMessage})`,{error:m,costTime:me.common.timeManager.getServerTimeMs()-E,eventType:I,method:g,startTime:E}),m})}_reportApiSuccessLog(n){let{result:g,apiName:I,startTime:E,eventType:m}=n;const{timeManager:D}=me.common,{successLog:{message:M,moreMessage:T}={message:"",moreMessage:""}}=g||{},P=D.getServerTimeMs();I==="login"&&(E+=D.getTimeOffsetWithServer()),UI.includes(I)&&me.ssoLog.info(I,`${I} success ${M} ${T}`,{costTime:P-E,eventType:m,message:M,moreMessage:T,startTime:E}),g?.successLog&&delete g.successLog}}class Wv{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:n,store:g}=me;g.set("login",{isReady:!1}),dr.getInstance().registerApi({apiName:"login",context:this}),dr.getInstance().registerApi({apiName:"logout",context:this}),dr.getInstance().registerApi({apiName:"getLoginUser",context:this}),dr.getInstance().registerApi({apiName:"isReady",context:this}),dr.getInstance().registerApi({apiName:"getServerTime",context:this}),dr.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),n.subscribeInnerEvent(so.RECONNECTED,this._reLogin,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}login(n){return pA(this,void 0,void 0,function*(){var g;const{sdkEdition:I}=me.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new as({functionName:"login",code:ua.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=me.channel.getSocketAdapter())===null||g===void 0?void 0:g.getId(),{appId:D,href:M}=me.store.get("instance")||{},{instanceID:T,customStatus:P}=E||{};return{code:0,data:E,successLog:{message:I,moreMessage:`socketID:${m} instanceID:${T} customStatus:${P} href: ${M} appId: ${D}`}}}catch(E){const{errorCode:m}=E;m!==ua.REPEAT_LOGIN&&(this._latestLoginAt=0);const D=new as({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 Du(this._customLoginInfo);if(g){const{instanceID:I,customStatus:E}=g;me.store.set("login",{statusInstanceId:I}),Rs.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:E,statusType:uE.USER_STATUS_ONLINE});const m=(n=me.channel.getSocketAdapter())===null||n===void 0?void 0:n.getId();me.ssoLog.info("reLogin",`socketId:${m} instanceId:${I}`)}}catch(g){console.warn(g)}})}logout(){return pA(this,arguments,void 0,function*(n=sa.USER_INITIATED){const{ssoLog:g}=me;g.debug("logout",`logout start logoutReason: ${n}`);try{yield this._performLogout(n),g.info("logout","logout success"),me.ssoLog.uploadSSOLogData()}catch(I){const{errorCode:E}=I;throw new as({functionName:"logout",code:E})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?Ar():""}isReady(){var n;return(n=me.store.get("login"))===null||n===void 0?void 0:n.isReady}setCustomLoginInfo(n=""){this._customLoginInfo=n}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),Rs.getInstance().reset(),me.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:n}=me.common;return n.getServerTimeMs()}_updateAndEmitSDKReady(){me.store.set("login",{isReady:!0}),setTimeout(()=>{me.notificationCenter.emitOuterEvent(yr.SDK_READY,{name:yr.SDK_READY})},1)}_updateAndEmitSDKNotReady(){me.store.set("login",{isReady:!1}),me.notificationCenter.emitOuterEvent(yr.SDK_NOT_READY,{name:yr.SDK_NOT_READY})}_validateAfterLogin(n){const g="login";if(!n)throw new as({functionName:g,message:"login response is empty"});const{tinyID:I,a2Key:E}=n||{};if(!I)throw new as({functionName:g,code:ua.NO_TINYID});if(!E)throw new as({functionName:g,code:ua.NO_A2KEY})}_createRepeatLoginResponse(){var n;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:ss({code:"RepeatLogin",replacement1:(n=me.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:I}=n;return me.store.set("login",{userId:g,userSig:I}),this._latestLoginAt=Date.now(),Du(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(n=>{setTimeout(()=>n(null),1)})})}_handleLoginSuccess(n){const{timeManager:g}=me.common,{helloInterval:I,timeStamp:E,customStatus:m,purchaseBits:D}=n,M=1e3*E;g.calculateTimeOffsetWithServer(this._latestLoginAt,M),this._helloInterval=I||120,this._updateLoginStore(n),me.user.userStatus.setCustomStatus(m),Rs.getInstance().executeWorkflow(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:D}),me.common.taskScheduler.addTask({id:Ng,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(n){return function(g){return pA(this,void 0,void 0,function*(){const{logoutReason:I}=g,E="im_open_status.wslogout",m=me.common.generateProtocolData({servcmd:E,data:{wslogout_type:I,isWebUniapp:0}}),D=`${m.head.seq}${E}`;return yield me.channel.sendPacket(m,{requestId:D})})}({logoutReason:n})}_updateLoginStore(n){const{a2Key:g,tinyID:I,instanceID:E,authKey:m}=n;me.store.set("login",{a2Key:g,tinyID:I,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=me.common.generateProtocolData({servcmd:n,data:{isWebUniapp:0}}),I=`${g.head.seq}${n}`;return me.channel.sendPacket(g,{requestId:I})}()}catch(n){me.ssoLog.warn("_sendOnlinePresenceRequest",` error:${n.message}`)}})}_isLoginIn(){var n;return((n=me.store.get("login"))===null||n===void 0?void 0:n.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){me.common.taskScheduler.removeTask(Ng),this._helloInterval=120,this._latestSendOnlinePresenceRequestTime=0,this._latestLoginAt=0,this._customLoginInfo="",me.store.clear("login"),me.store.set("login",{isReady:!1}),me.store.set("instance",{applicationID:0})}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.RECONNECTED,this._reLogin,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}const zv={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},CT={logout:!0};class hh{constructor(){this.loginAction=new Wv,this.kickedOutHandler=new yu,this.loginAction.init(),this.kickedOutHandler.init(),Kc({auth:CT,params:zv})}}var Jr,Vu,kE;(function(s){s.CONV_C2C="C2C",s.CONV_GROUP="GROUP",s.CONV_TOPIC="TOPIC",s.CONV_SYSTEM="@TIM#SYSTEM"})(Jr||(Jr={})),function(s){s.MSG_PRIORITY_HIGH="High",s.MSG_PRIORITY_NORMAL="Normal",s.MSG_PRIORITY_LOW="Low",s.MSG_PRIORITY_LOWEST="Lowest"}(Vu||(Vu={})),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 mD={1:Vu.MSG_PRIORITY_HIGH,2:Vu.MSG_PRIORITY_NORMAL,3:Vu.MSG_PRIORITY_LOW,4:Vu.MSG_PRIORITY_LOWEST},fD=0,Zv=1;var Ju;(function(s){s.IN="in",s.OUT="out"})(Ju||(Ju={}));const Xv=2,qQ={};function Au(s){if(!s)return 0;if(qQ[s]===void 0){const n=new Date,g=`3${n.getHours()}`.slice(-2),I=`0${n.getMinutes()}`.slice(-2),E=`0${n.getSeconds()}`.slice(-2);qQ[s]=parseInt([g,I,E,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${qQ[s]}`)}else qQ[s]+=1;return qQ[s]}class LE{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=Vu.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:g=me.common.timeManager.getServerTimeSeconds()||0,senderTinyID:I,currentUser:E,needReadReceipt:m,isSupportExtension:D,customModerationConfigurationId:M,to:T,from:P,nick:W="",avatar:oA="",time:EA,messageControlInfo:wA,tinyID:kA,cloudCustomData:YA="",messageLifeTime:LA,messageVersion:SA=0,conversationType:OA,sequence:HA,checkResult:se=0,isPlaceMessage:oe=0,messageFlagBits:_i,receiverList:Ti,isSystemMessage:bt=!1,status:Ni=Or.SUCCESS,revokeReason:gs="",conversationSubType:De,clientSequence:Bt,protocol:UA="JSON",revokerInfo:ii={userID:"",nick:"",avatar:""},readReceiptInfo:ws={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Gi,groupProfile:Lr,atUserList:xi,flow:ar,isRead:wt=!1,priority:_t=Vu.MSG_PRIORITY_NORMAL,onlineOnlyFlag:qu=!1,nameCard:ln="",quoteInfo:ho}=n;var cl;this.clientTime=g,this.senderTinyID=I||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=Gi===void 0?(cl=cl||99999999,Math.round(Math.random()*cl)):Gi,this.time=EA||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!wA?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!wA?.excludedFromUnreadCount,this.isModified=!!SA,this.cloudCustomData=YA,this.messageLifeTime=LA,this.from=P||null,this.sequence=HA||0,this.conversationType=OA||Jr.CONV_C2C,this.hasRiskContent=se>1,this.version=SA,this.isPlaceMessage=oe,this.isRevoked=oe===2||_i===8,this.isSystemMessage=bt,this.readReceiptInfo=ws,this.revokeReason=gs,this.revokerInfo=ii,this._receiverList=Ti,this.conversationSubType=De,this.revoker=ii?.revoker||"",this.clientSequence=Bt||HA||0,this.status=Ni,this.atUserList=xi||[],this.flow=ar,this.isRead=wt,this.priority=_t,this._onlineOnlyFlag=qu,this.nameCard=ln,this.quoteInfo=ho,this.reInitialize(E),this._initC2CReadReceiptInfo(n),this._extractGroupInfo(Lr)}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,I;return this._relayFlag?{isValid:!0}:((n=this._elements)===null||n===void 0?void 0:n.length)>0?(I=(g=this._elements[0])===null||g===void 0?void 0:g.validateBeforeSend)===null||I===void 0?void 0:I.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:I=0}=n;this.conversationType===Jr.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=g===1,this.readReceiptInfo.timestamp=I)}_extractGroupInfo(n){if(!n)return;const{From_AccountNick:g,From_AccountHeadurl:I,MsgFrom_AccountExtraInfo:E,GroupType:m}=n,{NameCard:D}=E||{};typeof g=="string"&&(this.nick=g),typeof I=="string"&&(this.avatar=I),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 I=this.conversationType;I!==Jr.CONV_SYSTEM?(g=I===Jr.CONV_C2C?n===this.from?this.to:this.from:this.to,this.conversationID=g?`${I}${g}`:null):this.conversationID=Jr.CONV_SYSTEM}_initSequence(n){this.clientSequence===0&&n&&(this.clientSequence=Au(n)),this.sequence===0&&this.conversationType===Jr.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Jr.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(n){this.isRead=n}}class pd{static parseServerPushElement(n){const{MsgContent:g={}}=n,{Data:I,Ext:E,Desc:m}=g;return new pd({data:I,description:m,extension:E})}constructor(n){this.type=kE.MSG_CUSTOM;const{data:g="",description:I="",extension:E=""}=n;this.content={data:g,description:I,extension:E}}transformToServerFormat(n){const{isMergerMessage:g=!1}=n||{},I=g?this.payload:this.content,{data:E,description:m,extension:D}=I;return{MsgType:this.type,MsgContent:{Data:E,Ext:D,Desc:m}}}validateBeforeSend(){const{isEmpty:n}=me.utils,g=[this.content.data,this.content.description,this.content.extension].some(I=>!n(I));return{isValid:g,error:g?null:{message:"content can not be empty"}}}}class md{static parseServerPushElement(n){const{MsgContent:g={Text:""}}=n,{Text:I}=g;return new md({text:I})}constructor(n){this.type=Rg.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||{},I=g?this.payload:this.content,{text:E}=I;return{MsgType:this.type,MsgContent:{Text:E}}}}var Om=new class{constructor(){this._elementClassMap={[kE.MSG_CUSTOM]:pd,[kE.MSG_TEXT]:md}}init(){dr.getInstance().registerApi({apiName:"createCustomMessage",context:this}),dr.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=Ju.OUT}=s,{userId:I}=me.store.get("login")||{};this._isSendByCurrentInstance({from:n,flow:g,currentUser:I})?this._updateWithSenderInfo(s):this._isMultiEndpointSyncMessage({from:n,flow:g,currentUser:I})&&(s.flow=Ju.OUT);const E=Object.assign(Object.assign({},s),{currentUser:I});return new LE(E)}createCustomMessage(s){const n=Ar(),g=this.createMessage(Object.assign(Object.assign({},s),{from:n})),I=this._elementClassMap[kE.MSG_CUSTOM];if(!g)return null;if(I){const E=new I(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)||"",I=new md({text:g}),E=Ar(),m=me.message.messageFactory.createMessage(Object.assign(Object.assign({},s),{from:E}));return m.setElement(I),m}_updateWithSenderInfo(s){var n,g;const{nick:I,avatar:E,conversationType:m,to:D}=s,{userId:M,tinyID:T}=me.store.get("login")||{},P=nc.getUserProfile(M);return s.nick=I||P?.nick||"",s.avatar=E||P?.avatar||"",s.tinyID=s.tinyID||T||"",s.from=M,s.status=Or.UNSENT,s.flow=Ju.OUT,m===ba.CONV_GROUP&&(s.nameCard=(g=(n=JQ.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:I}=s;return n===I&&g===Ju.IN}_isSendByCurrentInstance(s){const{from:n,flow:g,currentUser:I}=s;return n===I&&g===Ju.OUT}};const $v={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}},fd={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 AR(s,n){return Object.keys(n).forEach(g=>{const{range:I,defaultValue:E}=n[g];s[g]=I.includes(s[g])?s[g]:E}),s}function KQ(s){const n=s.lastIndexOf(".");return n===-1?s:s.slice(0,n)}function eR(s){const{androidInfo:n={},androidOPPOChannelID:g=""}=s,I=n.OPPOChannelID||g,E=AR(n,fd),{sound:m="",FCMChannelID:D=""}=E,M=yo(E,["sound","FCMChannelID"]);return Object.assign(Object.assign({},M),{Sound:KQ(m),OPPOChannelID:I,GoogleChannelID:D})}function tR(s){const{apnsInfo:n={},ignoreIOSBadge:g=!1,disableVoipPush:I}=s,E=AR(n,yD),{ignoreIOSBadge:m,disableVoipPush:D,enableIOSBackgroundNotification:M}=E,T=yo(E,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),P=m===!0||g===!0?1:0;let W;return r(I)||(W=I===!1?1:0),r(D)||(W=D===!1?1:0),Object.assign(Object.assign({},T),{BadgeMode:P,IsVoipPush:W,ContentAvailable:M?1:0})}function DD(s){return me.utils.isPlainObject(s)?{PushFlag:s.disablePush===!0?1:0,Title:s.title||"",Desc:s.description||"",Ext:s.extension||"",ApnsInfo:tR(s),AndroidInfo:eR(s)}:$v}function Pm(s){const{From_AccountHeadurl:n,From_AccountNick:g,IsNeedReadReceipt:I,IsPeerRead:E,IsSyncMsg:m,MsgBody:D,MsgClientTime:M,MsgLifeTime:T,MsgRandom:P,MsgSeq:W,MsgTimeStamp:oA,SendMsgControl:EA,SupportMessageExtension:wA,TinyId:kA,MsgCheckResult:YA,CloudCustomData:LA,MsgVersion:SA,MsgFlagBits:OA,RevokerInfo:HA,InnerSdkCustomData:se}=s;let oe,{From_Account:_i,To_Account:Ti}=s;if(m===1){const bt=Ti;Ti=_i,_i=bt}if(HA){const{Reason:bt,Revoker_Account:Ni,Revoker_FromUin:gs}=HA;oe={reason:bt,revoker:Ni,revokerFromUin:gs,userID:Ni}}return{from:_i,avatar:n,nick:g,needReadReceipt:I===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:Ti,tinyID:kA,checkResult:YA,cloudCustomData:LA,revokerInfo:oe,messageVersion:SA,messageFlagBits:OA,readReceiptSentByPeer:E,elements:hC(D),onlineOnlyFlag:T===0,quoteInfo:jQ(se)}}function xm(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,To_Account:M,MsgVersion:T,CloudCustomData:P,MsgCheckResult:W}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,to:M,elements:hC(g),messageVersion:T,cloudCustomData:P,checkResult:W}}function SD(s){const{ClientSeq:n,From_Account:g,GroupInfo:I,MsgBody:E,MsgClientTime:m,MsgRandom:D,MsgSeq:M,MsgTimeStamp:T,SendMsgControl:P,SupportMessageExtension:W,TinyId:oA,CloudCustomData:EA,MsgVersion:wA,MsgCheckResult:kA,NeedReadReceipt:YA,IsPlaceMsg:LA,RevokerInfo:SA,GroupAtInfo:OA,OnlineOnlyFlag:HA,InnerSdkCustomData:se}=s;let oe,_i=Vu.MSG_PRIORITY_NORMAL;if(Object.keys(mD).includes(String(s.MsgPriority))&&(_i=mD[s.MsgPriority]),SA){const{Reason:bt,Revoker_Account:Ni,Revoker_FromUin:gs}=SA;oe={reason:bt,revoker:Ni,revokerFromUin:gs,userID:Ni}}const Ti=function(bt){const Ni=[];return Array.isArray(bt)&&bt.forEach(gs=>{gs.GroupAtAllFlag===fD?Ni.push(gs.GroupAt_Account):gs.GroupAtAllFlag===Zv&&Ni.push(ko.MSG_AT_ALL)}),Ni}(OA);return{clientSequence:n,from:g,groupProfile:I,clientTime:m,priority:_i,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:YA,isPlaceMessage:LA,revokerInfo:oe,atUserList:Ti,elements:hC(E),to:hT(s),onlineOnlyFlag:HA===1,quoteInfo:jQ(se)}}function hT(s){const{utils:{isEmpty:n},constants:{IS_TOPIC_MESSAGE:g}}=me,{ToGroupId:I,GroupInfo:{MillionGroupFlag:E=0,TopicId:m}={}}=s;return E!==g||n(m)?I:m}function hC(s){if(!s)return null;if(Array.isArray(s))return s.map(g=>{const I=me.message.messageFactory.getElementClass(g.MsgType);return I?.parseServerPushElement(g)});const n=me.message.messageFactory.getElementClass(s.MsgType);return n?.parseServerPushElement(s)}function MD(s){const{From_Account:n,MsgBody:g,MsgClientTime:I,MsgRandom:E,MsgSeq:m,MsgTimeStamp:D,GroupId:M,TopicId:T,MsgVersion:P,CloudCustomData:W,MsgCheckResult:oA}=s;return{from:n,clientTime:I,random:E,sequence:m,time:D,groupID:M,topicID:T,elements:hC(g),messageVersion:P,cloudCustomData:W,checkResult:oA}}function jQ(s){const{utils:{isString:n,safeStringify:g},ssoLog:I}=me;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 I.debug("_parseServerQuoteInfo",g(E)),null}}function WQ({conversationUpdateFields:s,message:n}){const{conversationID:g,conversationType:I,conversationSubType:E,flow:m,_isExcludedFromUnreadCount:D,_isExcludedFromLastMessage:M}=n,T=M?"":YQ(n),P=!D&&m===Ju.IN;s.has(g)?(s.get(g).lastMessage=T,P&&s.get(g).unreadCount++):s.set(g,{conversationID:g,type:I,subType:E,unreadCount:P?1:0,lastMessage:T})}function hB(s){return s.filter(n=>{const g=!vs(n?._elements),I=n?.isPlaceMessage===1;return g||me.ssoLog.error("emptyMessageBody",`from:${n.from} to:${n.to} sequence:${n.sequence}`),g&&!I})}function BB(s){const{messageDataHandler:n}=me.message;return!n.isInMessageList(s)&&!n.isMessageSentByCurrentInstance(s)}var iR=Object.freeze({__proto__:null,autoIncrementIndex:Au,createAndroidPushInfo:eR,createApnsPushInfo:tR,createOfflinePushInfo:DD,filterValidMessages:hB,getAndroidSoundName:KQ,parseServerGroupMessage:SD,parseServerPushC2CModifyMessage:xm,parseServerPushGroupModifyMessage:MD,parseServerPushMessage:Pm,parseServerPushMessageElement:hC,shouldStoreMessage:BB,updateConversationFields:WQ});const{isPlainObject:oR}=me.utils;function zQ(s,n={}){const{onlineUserOnly:g,messageControlInfo:I}=n;let{offlinePushInfo:E}=n;s.conversationType===Jr.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(I&&oR(I)){const{excludedFromUnreadCount:M,excludedFromLastMessage:T,excludedFromContentModeration:P}=I;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 vD(s){const{webhookInfo:{disableCloudMessagePreHook:n=!1,disableCloudMessagePostHook:g=!1}={}}=s||{};if(!n&&!g)return;const I=[];return n&&I.push("ForbidBeforeSendMsgCallback"),g&&I.push("ForbidAfterSendMsgCallback"),I}function Bh(s,n){return pA(this,void 0,void 0,function*(){const g=s.conversationType===Jr.CONV_GROUP?function(E,m){var D;const M=zQ(E,m),{onlineUserOnly:T,cloudCustomData:P,messageControlInfo:W,offlinePushInfo:oA}=M,EA=JSON.parse(JSON.stringify(E.transformElementsToServerFormat()));let wA;return p(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=me.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:DD(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:vD(m),InnerSdkCustomData:pB(E)}}}(s,n):function(E,m){var D;const M=zQ(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=me.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:DD(oA),ForbidCallbackControl:vD(m),InnerSdkCustomData:pB(E)}}}(s,n),I=yield ag(g);return I?{time:I.MsgTime,messageDropReason:I.MsgDropReason,sequence:I.MsgSeq}:null})}function Qh(s){return pA(this,void 0,void 0,function*(){const{from:n,to:g,version:I=0,sequence:E,random:m,time:D,type:M,cloudCustomData:T}=s,P={From_Account:n,To_Account:g,MsgVersion:I,MsgSeq:E,MsgRandom:m,MsgTime:D,MsgType:M,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:T},W=yield ag({servcmd:"openim.modify_c2c_msg",data:P});if(W){const{MsgBody:oA,MsgVersion:EA,CloudCustomData:wA}=W;return{elements:hC(oA),messageVersion:EA,cloudCustomData:wA}}})}function QB(s){return pA(this,void 0,void 0,function*(){const{to:n,version:g=0,sequence:I,cloudCustomData:E}=s,m={GroupId:n,MsgVersion:g,MsgSeq:I,MsgBody:s.transformElementsToServerFormat(),CloudCustomData:E},D=yield ag({servcmd:"openim.modify_group_msg",data:m});if(D){const{MsgBody:M,MsgVersion:T,CloudCustomData:P}=D;return{elements:hC(M),messageVersion:T,cloudCustomData:P}}})}function ph(s){return pA(this,void 0,void 0,function*(){const{groupID:n,count:g,messageSequence:I,messageSequenceList:E,getType:m}=s,D={GroupId:n,ReqMsgNumber:g,WithRecalledMsg:1,Version:1,GetType:m};return I&&(D.ReqMsgSeq=I),p(E)&&E.length>0&&(D.ReqMsgSeqList=E),yield ag({servcmd:"group_open_http_svc.group_msg_get",data:D})})}function Ym(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E,direction:m}=s;return ag({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g,WithRecalledMsg:1,LastMsgTime:I,MsgKey:E,GetDirection:m}})})}function pB(s){if(me.utils.isObject(s.quoteInfo)){const{msgID:n,messageSequence:g,messageTime:I}=s.quoteInfo;return JSON.stringify({businessQuote:{messageID:n,messageSequence:g,messageTime:I}})}}var RD=Object.freeze({__proto__:null,createMessagePackOptions:zQ,generateForbidCallbackControl:vD,getC2CRoamingMessagesByAnchor:Ym,getGroupRoamingMessagesByAnchor:ph,getRoamingMessages:function(s){return pA(this,void 0,void 0,function*(){const{peerAccount:n,count:g,lastMessageTime:I,messageKey:E}=s;return(yield ag({servcmd:"openim.getroammsg",data:{Peer_Account:n,MaxCnt:g||15,LastMsgTime:I||0,MsgKey:E,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Qh,modifyGroupMessage:QB,sendMessage:Bh});const{isPlainObject:BT}=me.utils,{MSG_AUDIO:wD,MSG_FILE:_D,MSG_IMAGE:sR,MSG_VIDEO:nR,MSG_MERGER:rR}=ko;class Vm{constructor(){this._sendProtocolMap=new Map}init(){dr.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:n=>![wD,_D,sR,nR,rR].includes(n[0].type)})}registerSendProtocol(n,g,I){this._sendProtocolMap.set(n,g.bind(I))}sendMessage(n,g){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:I,SEND_COST:E,SUCCESS_COUNT:m,FAILED_COUNT:D}=nr;if(!(n instanceof LE))throw new as({code:ua.MSG_INSTANCE_REQUIRED});const M=n.validateBeforeSend();if(!M.isValid){const{code:W,message:oA=""}=M.error||{};throw new as({code:W,message:oA})}this._reportMessageSendQuality({name:I,message:n});let T=!1;const{messageDataHandler:P}=me.message||{};try{const{messageControlInfo:W}=g||{};let oA=null;P.addRandomOfSentMessage(n.random);const EA=Date.now(),wA=this._getSendProtocol(n);if(n.conversationType===Jr.CONV_C2C?(T=g?.onlineUserOnly===!0,oA=yield wA(n,g)):n.conversationType===Jr.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(n),oA=yield wA(n,g)),oA){const{messageDropReason:kA,sequence:YA,time:LA}=oA;if(this._updateNickAndAvatarOfSentMessageByMe(n),kA&&this._logRateLimitInfo(n,YA,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&&(me.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${SA.ID}`),P.deleteConversationMessage(SA))}return n.status=Or.SUCCESS,n.time=LA,n.conversationType===Jr.CONV_GROUP&&(n.sequence=YA),T?n._onlineOnlyFlag=!0:(P.storeConversationMessage(n),this._applySentMessageControlInfo(n,W),this._emitOnlineMessageSent(n)),n.type===Rg.MSG_STREAM?{code:0,data:{message:n,streamMessageID:oA.streamMessageID}}:{code:0,data:{message:n}}}}catch(W){n.status=Or.FAIL,P.removeRandomOfSentMessage(n.random);let{errorCode:oA}=W||{},EA=W?.errorInfo||W?.message||"";throw this._hasRiskContent(oA)&&(n.hasRiskContent=!0),T||this._isRejectedByRestApi(oA)||P.storeConversationMessage(n),this._reportMessageSendQuality({name:D,message:n,error:W}),new as({code:oA,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:I,conversationType:E}=n,m=jc(I)?so.TOPIC_NEW_MESSAGE:so.NEW_MESSAGE;me.notificationCenter.emitInnerEvent(m,{result:{conversationUpdateFieldList:[{conversationID:I,type:E,message:n,lastMessage:g,unreadCount:0}]}})}_applySentMessageControlInfo(n,g){g&&BT(g)&&(g.excludedFromLastMessage===!0&&(n._isExcludedFromLastMessage=!0),g.excludedFromUnreadCount===!0&&(n._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(n,g,I){const E=`from:${n.from} to:${n.to} sequence:${g} messageDropReason:${I}`;me.ssoLog.warn("messageDropReason",E)}_updateNickAndAvatarOfSentMessageByMe(n){const{messageDataHandler:g}=me.message||{};let I=!1;const{conversationID:E}=n,m=g.getLatestMsgSentByMe(E);if(m){const{nick:D,avatar:M}=m;D===n.nick&&M===n.avatar||(I=!0),I&&g.updateNickAndAvatarOfSentMessage({conversationID:E,latestNick:n.nick,latestAvatar:n.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(n){return pA(this,void 0,void 0,function*(){var g,I,E;const{to:m,from:D}=n;let M=m,T=JQ.getGroup(M);if(zr({groupID:M})&&T?.isSupportTopic)throw new as({code:ua.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(jc(m)&&([M]=m.split(oa.TOPIC),T=JQ.getGroup(M)),!T&&typeof((g=dr.getInstance().getApiMap())===null||g===void 0?void 0:g.getGroupProfile)=="function"){const P=yield dr.getInstance().getApiMap().getGroupProfile({groupID:M});if(((E=(I=P?.data)===null||I===void 0?void 0:I.group)===null||E===void 0?void 0:E.type)===ko.GRP_AVCHATROOM){const W=ss({code:ua.MSG_SEND_FAIL_NOT_IN_AV,replacement1:D,replacement2:M});throw new as({code:ua.MSG_SEND_FAIL_NOT_IN_AV,message:W})}}return!0})}_reportMessageSendQuality(n){me.notificationCenter.emitInnerEvent(so.QUALITY_STAT,{label:oI.MESSAGE_SEND_SUCCESS_RATE,data:n})}_getSendProtocol(n){return this._sendProtocolMap.get(n.type)||Bh}}var QT=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){me.notificationCenter.subscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.subscribeInnerEvent(so.DESTROY,this._dispose,this)}get _messagesByConversation(){return HQ.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 I=this._getUniqueIdOfMessage(s);return this._messagesByConversation.get(g).set(I,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),I=this._messagesByConversation.get(s.conversationID);if(I?.has(g)){const E=I?.get(g);if(!n||E?.isModified===!0)return!0}return!1}deleteConversationMessage(s){var n;const{conversationID:g=""}=s,I=this._getUniqueIdOfMessage(s);this._messagesByConversation.has(g)&&((n=this._messagesByConversation.get(g))===null||n===void 0||n.delete(I))}modifyConversationMessage(s,n){var g;if(!this._messagesByConversation.has(s)&&!this._sparseMessagesByConversation.has(s))return{isUpdated:!1,message:null};const I=this._getUniqueIdOfMessage(n),E=this._getMessageFromLocalMessage(s,I);if(E){const{messageVersion:m,elements:D,cloudCustomData:M,checkResult:T=0}=n,P=T>1;if(me.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${E.version} remoteVersion:${m}`),E.versionE.ID===s)||null,n)break;if(!n){const I=Array.from(this._sparseMessagesByConversation.values());for(const E of I)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:I}){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 HQ.updateMessage(s,[M],{isRevoked:!0,revoker:I,operation:fc.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=I,m}}_findMessageBySequenceAndRandom({messageList:s,sequence:n,random:g}){for(let I=0;I0){const D=new Map([...E,...m.entries()]);this._messagesByConversation.set(g,D),this._updateLatestMessageSentByMe(g),this._updateLatestMessageSentByPeer(g)}return I}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 I=this._sparseMessagesByConversation.get(n);for(let E=0;E=0;I--)if(g[I].flow==="out"){this._setLatestMsgSentByMe(s,g[I]);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 I=g.length-1;I>=0;I--)if(g[I].flow==="in"){this._setLatestMsgSentByPeer(s,g[I]);break}}}_getUniqueIdOfMessage(s){const{from:n,to:g,random:I,sequence:E,time:m}=s;return`${n}-${g}-${I}-${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:I,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:oA}=T;oA===M&&(P!==I&&(T.nick=I),W!==g&&(T.avatar=g))})}isInMessageList(s){var n;const{conversationID:g}=s;if(!g||!this._messagesByConversation.has(g))return!1;const I=this._getUniqueIdOfMessage(s);return(n=this._messagesByConversation.get(g))===null||n===void 0?void 0:n.has(I)}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(),me.notificationCenter.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}};function Jm(s,n){const g=CB.getConversation(s);if(g?.lastMessage){const{lastMessage:I}=g,{lastTime:E,lastSequence:m,version:D}=I,{time:M,sequence:T,messageVersion:P,elements:W,cloudCustomData:oA}=n;E===M&&m===T&&D!==P&&(I.type=W[0].type,I.payload=W[0].content,I.messageForShow=Wc(I.type,I.payload),I.cloudCustomData=oA,I.version=P,CB.updateConversation(s,{lastMessage:I}))}}class aR{init(){dr.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(n){return pA(this,void 0,void 0,function*(){const{to:g,payload:I,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=I)}try{let W=null,oA=null;if(m===Jr.CONV_C2C?W=yield Qh(n):m===Jr.CONV_GROUP&&(W=yield QB(n)),W){let EA=`${m}${g}`;return g===Ar()&&m===Jr.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:n},successLog:{message:`to:${g}`}}}}catch(W){const{errorCode:oA}=W||{};throw new as({functionName:"modifyMessage",code:oA,moreMessage:`to:${g}`})}})}_handleModifyMessageSuccess(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent(yr.MESSAGE_MODIFIED,{name:yr.MESSAGE_MODIFIED,data:[E]}),me.notificationCenter.emitInnerEvent(so.MESSAGE_MODIFIED,{conversationID:g,message:E}),Jm(g,n)}_canModifyMessageElement(n){return[kE.MSG_TEXT,kE.MSG_CUSTOM,kE.MSG_LOCATION,kE.MSG_FACE].includes(n)}}class mh{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_C2C_NEW_MESSAGE,Ht.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){Rs.getInstance().executeWorkflow(Pt.RECEIVE_C2C_NEW_MESSAGE,n)}_handleC2CMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.message||{},E=[],m=new Map;return g.C2cMsgArray.forEach(D=>{const M=this._generateC2CMessage(D);this._updateMessageProfile(M);let T=M.isModified===1;I.isMessageSentByCurrentInstance(M)?M.isModified=T:T=!1,M._onlineOnlyFlag?I.isMessageSentByCurrentInstance(M)||E.push(M):BB(M)&&(I.storeConversationMessage(M)&&WQ({conversationUpdateFields:m,message:M}),I.isMessageSentByCurrentInstance(M)&&!T||E.push(M))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEventsAfterReceiveNewMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(I)}_emitMessageEventsAfterSyncUnreadMessage(n){var g;const{messages:I=[]}=((g=n.result)===null||g===void 0?void 0:g[Ht.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(I)}_emitMessageEvents(n){const g=n?.filter(E=>E?.isModified===!0)||[];g.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:g});const I=n?.filter(E=>!E?.isModified);I.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:I})}_generateC2CMessage(n){const g=Jr.CONV_C2C,I=Pm(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ju.IN})),{elements:m}=I;return E.setElement(m),E}_updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.getLatestMsgSentByPeer(T);if(P){const{nick:W,avatar:oA}=P;r(D)||r(M)?(n.nick=l(W)?W:n.nick,n.avatar=l(oA)?oA:n.avatar):D===W&&M===oA||(I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!1}),this._updateConversationUserProfile({conversationID:T,nick:D,avatar:M}))}}else{const P=I.getLatestMsgSentByMe(T);!P||D===P.nick&&M===P.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}}_updateConversationUserProfile(n){const{conversationID:g,nick:I,avatar:E}=n,m=CB.getConversation(g),{userProfile:D={}}=m||{};D.avatar===E&&D.nick===I||CB.updateConversation(g,{userProfile:Object.assign(Object.assign({},D),{nick:I,avatar:E})})}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),me.notificationCenter.emitInnerEvent("ModifyMessageSuccess",n),Jm(g,n)}_handleC2CMessageModify(n){n.C2cMsgModNotifys.forEach(g=>{var I;const E=Jr.CONV_C2C;let m=xm(g);const{to:D,from:M}=m;let T=`${E}${D}`;D===((I=me.store.get("login"))===null||I===void 0?void 0:I.userId)&&(T=`${E}${M}`),m=Object.assign({conversationType:E,conversationID:T},m),this._updateMessageListDueToModify(m)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),me.notificationCenter.unSubscribeInnerEvent(so.MESSAGE_PUSH,g.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),me.notificationCenter.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class fh{init(){const{notificationCenter:n}=me,{InnerEventSubType:g}=n;Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),Rs.getInstance().registerWorkflowStep(Pt.RECEIVE_GROUP_NEW_MESSAGE,Ht.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,g.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(n){this._canExecuteReceiverNewMessageWorkFlow(n)&&Rs.getInstance().executeWorkflow(Pt.RECEIVE_GROUP_NEW_MESSAGE,n)}_handleGroupMessagePush(n){const g=n.data||{},{messageDataHandler:I}=me.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;I.isMessageSentByCurrentInstance(T)?T.isModified=P:P=!1,T._onlineOnlyFlag?I.isMessageSentByCurrentInstance(T)||E.push(T):BB(T)&&I.storeConversationMessage(T)&&(E.push(T),WQ({conversationUpdateFields:m,message:T}))}),{conversationUpdateFieldList:[...m.values()],messages:E}}_emitMessageEvents(n){var g;const{messages:I}=((g=n.result)===null||g===void 0?void 0:g[Ht.HANDLE_GROUP_NEW_MESSAGE])||{},E=I?.filter(D=>D?.isModified===!0)||[];E.length>0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:E});const m=I?.filter(D=>!D?.isModified)||[];m.length>0&&me.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:m})}_generateGroupMessage(n){const g=Jr.CONV_GROUP,I=SD(n),E=me.message.messageFactory.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:Ju.IN})),{elements:m}=I;return E.setElement(m),E}updateMessageProfile(n){var g;const{messageDataHandler:I}=me.message||{},E=(g=me.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=I.getLatestMsgSentByMe(T);!W||D===W.nick&&M===W.avatar||I.updateNickAndAvatarOfSentMessage({conversationID:T,latestNick:D,latestAvatar:M,isSentByMe:!0})}else if(m===ko.CONV_SYSTEM){const{operationType:W,memberInfoList:oA,operatorInfo:EA}=P;let wA={};if(vs(oA)?vs(EA)||(wA=EA):[_g.JOINED,_g.KICKED,_g.ADMIN_SET,_g.ADMIN_CANCELED].includes(W)&&(wA=Object.assign({},oA[0])),!vs(wA)){const{nick:kA="",avatar:YA=""}=wA;n.nick=kA,n.avatar=YA}}}_updateMessageListDueToModify(n){const{conversationID:g}=n,{isUpdated:I,message:E}=me.message.messageDataHandler.modifyConversationMessage(g,n);I===!0&&me.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[E]}),Jm(g,n)}_handleGroupMessageModify(n){n.GroupMsgModNotifys.forEach(g=>{const I=Jr.CONV_GROUP;let E=MD(g);const{topicID:m,groupID:D}=E,M=m||D,T=`${I}${M}`;E=Object.assign({conversationType:I,conversationID:T,to:M},E),this._updateMessageListDueToModify(E)})}_dispose(){const{notificationCenter:n}=me,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:g,GROUP_MESSAGE_MODIFIED:I}}=n;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,g,this._handleGroupMessagePush,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,I,this._handleGroupMessageModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(n){var g,I;const{GroupId:E,GroupType:m}=((I=(g=n?.GroupMsgArray)===null||g===void 0?void 0:g[0])===null||I===void 0?void 0:I.GroupInfo)||{},D=m===ka.GRP_AVCHATROOM;return!(!JQ.getGroup(E)&&D)}}var TD=new class{constructor(){this.c2cMessageReceiver=new mh,this.groupMessageReceiver=new fh}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const gR={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)}}},pT={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var mT=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:I,sequence:E,messageSequenceList:m,shouldMarkCompleted:D=!1,getType:M}=s,T=n.replace(ba.CONV_GROUP,""),P=[];let W=E;if(I===Hc.BACKWARD){if(typeof E!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};W=E+g-1}const oA=yield ph({groupID:T,count:g,messageSequence:W,messageSequenceList:m,getType:M});if(oA){const{RspMsgList:EA=[],NextReqMsgSeq:wA=0,IsFinished:kA,InvisibleMsgSeq:YA}=oA,LA=`groupID:${T} sequence:${E} reqSeq:${W} direction:${I} complete:${kA} nextSequence:${wA} remoteMsgCount:${EA.length} invisibleSequenceList:${YA}`,SA=[];for(let se=0;se=E),OA&&D&&this.completedHistoryConversations.add(n);const HA=hB(SA);return me.ssoLog.info("getGroupRoamingMessagesByAnchor",LA),{messageList:HA,invisibleSequenceList:YA,nextReqMessageIDFromServer:wA,hasNoMoreHistoryMessage:OA,serverGroupTipList:P}}}catch(n){const{errorCode:g,errorInfo:I}=n||{};throw new as({code:g,message:I})}})}clearHistoryMessageListFetchAnchors(s){this._historyMessageListFetchAnchors.delete(s)}isHistoryMessageFetchCompleted(s){return this.completedHistoryConversations.has(s)}_parseMessage(s){var n;const g=ba.CONV_GROUP;s.Event===4&&(s.MsgBody.MsgType=ko.MSG_GRP_TIP);const I=SD(s),E=Om.createMessage(Object.assign(Object.assign({},I),{conversationType:g,flow:"in"}));return dB(((n=I.elements)===null||n===void 0?void 0:n.content)||{},E),E.setElement(I.elements),E}getC2CRoamingMessagesByAnchor(s){return pA(this,void 0,void 0,function*(){var n;try{const{conversationID:g,count:I,messageID:E,time:m,direction:D,shouldMarkCompleted:M=!1}=s;let T=m,P="";if(!m){const EA=E?me.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(ba.CONV_C2C,""),oA=yield Ym({count:I,lastMessageTime:T,messageKey:P,peerAccount:W,direction:D});if(oA){const{MsgList:EA=[],Complete:wA,MsgKey:kA,LastMsgTime:YA}=oA;this._historyMessageListFetchAnchors.set(g,{messageKey:kA,lastMessageTime:YA});const LA=[];for(let se=0;se{const{tag:E,value:m}=I;E&&E.indexOf(GD)>-1?g.profileCustomField.push({key:E,value:m}):yd.has(E)&&(g[yd.get(E)]=m)}),Object.assign(Object.assign({},Hm),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!==bD&&n.push({tag:Fl[g.toUpperCase()],value:s[g]})}),s.profileCustomField&&p(s.profileCustomField)&&s.profileCustomField.forEach(g=>{n.push({tag:g.key,value:g.value})}),n}normalizeProfileFields(s){const n={},g=[];return s.forEach(I=>{const{tag:E,value:m}=I;if(E&&E.indexOf(GD)>-1&&g.push({key:E,value:m}),yd.has(E)&&m!==void 0){const D=yd.get(E);n[D]=m}}),g.length>0&&(n.profileCustomField=g),n}};const{generateProtocolData:lR}=me.common;function IR(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 I=lR({servcmd:n,data:g}),E=`${I.head.seq}${n}`,m=yield me.channel.sendPacket(I,{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:YA,ResultCode:LA,ResultInfo:SA,StandardSequence:OA,ProfileItem:HA}=wA,se=Hu.parseProfileItem(HA);EA.push({userId:kA,customSequence:YA,resultCode:LA,resultInfo:SA,standardSequence:OA,profileItem:se})}),{actionStatus:M,errorCode:T,errorDisplay:P,errorInfo:W,userProfile:EA}}(m)})}function UE(s){return nc.getFriendMap().has(s)}const{isEmpty:kD}=me.utils;class qm{constructor(){this._strangerProfileMap=new Map}init(){dr.getInstance().registerApi({apiName:"getMyProfile",context:this}),dr.getInstance().registerApi({apiName:"getUserProfile",context:this}),dr.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=Hu.createProfile.bind(Hu);const{notificationCenter:n}=me;Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const n=Ar(),g=yield IR([n]);if(g){const I=this._handleProfileFormResponse(g)[0];return nc.getUserProfileMap().set(n,I),{code:0,data:I}}}catch(n){const{errorCode:g,errorInfo:I}=n;throw new as({functionName:"getMyProfile",code:g,message:I})}})}getUserProfile(n){return pA(this,void 0,void 0,function*(){try{let{userIDList:g}=n;const{userIdListToRequest:I,profileFromCache:E}=this._filterRequestAndCacheUsers(g);if(I.length===0)return{code:0,data:E,successLog:{message:`userIDList.length:${g.length}`}};I.length>cR&&(me.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),I.length=cR);const{data:m,error:D}=yield this._batchFetchUserProfiles(I),M=I.length,T=m.length,P=M-T;if(E.length===0&&M===P&&!kD(D))throw D;if(p(m))return m.forEach(oA=>{UE(oA.userID)?nc.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 as(g)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const n=Ar(),g=nc.getUserProfileMap().has(n);return g?{code:0,data:g}:this.getMyProfile()})}updateMyProfile(n){return pA(this,void 0,void 0,function*(){const g=Ar(),I={};for(const m in n)n[m]!==void 0&&(I[m]=n[m]);const E=Hu.convertParamsToProfile(I);try{yield function(P){return pA(this,void 0,void 0,function*(){const W="profile.portrait_set",oA=lR({servcmd:W,data:P}),EA=`${oA.head.seq}${W}`,wA=yield me.channel.sendPacket(oA,{requestId:EA});if(wA){const{ActionStatus:kA,ErrorCode:YA,ErrorDisplay:LA,ErrorInfo:SA}=wA;return{actionStatus:kA,errorCode:YA,errorDisplay:LA,errorInfo:SA}}})}({From_Account:g,ProfileItem:E});const D=nc.getUserProfile(g);let M;M=D?Object.assign(Object.assign({},D),I):Hu.createProfile(g,E);const T=!ng(D,M,["lastUpdatedTime"]);return M.lastUpdatedTime=Date.now(),nc.getUserProfileMap().set(g,M),T&&this._emitProfileUpdated(M),{code:0,data:M,successLog:{message:`profileArray: ${me.utils.safeStringify(E)}`}}}catch(m){const{errorCode:D,errorInfo:M}=m;throw new as({functionName:"updateMyProfile",code:D,message:M,moreMessage:`params: ${me.utils.safeStringify(n)}`})}})}updateMyNickAndAvatar(n){return pA(this,void 0,void 0,function*(){const g=Ar(),I=Date.now(),E=nc.getUserProfile(g);let m={};m=E?Object.assign(E,n):Hu.createProfile(g,n),m.lastUpdatedTime=I,nc.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:Hu.parseProfileList(T)}}(n.ProfileDataMod[0]);if(kD(g))return;const{isProfileUpdated:I,profile:E}=this._handleProfileModified(g);I&&this._emitProfileUpdated(E)}_emitProfileUpdated(n){me.notificationCenter.emitInnerEvent(so.PROFILE_UPDATE,{name:so.PROFILE_UPDATE,data:[n]}),me.notificationCenter.emitOuterEvent(yr.PROFILE_UPDATED,{name:yr.PROFILE_UPDATED,data:[n]}),CB.updateConversation(`C2C${n?.userID}`,{userProfile:n})}_dispose(){const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(n){const{userId:g,profileList:I}=n,E=nc.getUserProfile(g);if(!(Ar()===g||UE(g)&&E))return{isProfileUpdated:!1,profile:null};const m=Hu.normalizeProfileFields(I),D=Object.keys(m).some(W=>W===bD?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,bD)?this._mergeProfileCustomField(E.profileCustomField,m.profileCustomField):E.profileCustomField,P=Object.assign(Object.assign(Object.assign({},E),m),{profileCustomField:T,lastUpdatedTime:M});return nc.getUserProfileMap().set(g,P),{isProfileUpdated:D,profile:P}}_filterRequestAndCacheUsers(n){const g=[],I=[];return n.forEach(E=>{const m=nc.getUserProfileMap().has(E);UE(E)&&m?I.push(nc.getUserProfile(E)):this._isStrangerAndProfileValid(E)?I.push(this._strangerProfileMap.get(E)):g.push(E)}),{userIdListToRequest:g,profileFromCache:I}}_handleProfileFormResponse(n){const{userProfile:g}=n;if(!Array.isArray(g))return[];const I=g.filter(m=>m.userId!=="@TLS#NOT_FOUND"&&m.userId!==""&&!kD(m.profileItem)),E=Date.now();return I.map(m=>{const D=Hu.createProfile(m.userId,m.profileItem);return D.lastUpdatedTime=E,D})}_isStrangerAndProfileValid(n){var g;if(!UE(n)){const{lastUpdatedTime:I=0}=this._strangerProfileMap.get(n)||{},E=((g=me.store.get("cloudConfig"))===null||g===void 0?void 0:g.stranger_profile_expiration_time)||6e5;return Date.now()-I<=E}return!1}_chunkUserIDList(n,g){return Array.from({length:Math.ceil(n.length/g)},(I,E)=>n.slice(E*g,(E+1)*g))}_batchFetchUserProfiles(n){return pA(this,void 0,void 0,function*(){const g=[],I=[];let E={};return this._chunkUserIDList(n,100).forEach(m=>{g.push(IR(m))}),(yield Promise.allSettled(g)).forEach(m=>{if(m.status==="fulfilled"){const D=m.value,M=this._handleProfileFormResponse(D);p(M)&&I.push(...M)}else if(m.status==="rejected"){const{code:D,message:M}=m.reason||{};E={errorCode:D,message:M}}}),{data:I,error:E}})}_isCustomFieldChanged(n=[],g=[]){if(!p(g)||g.length===0)return!1;if(!p(n)||n.length===0)return!0;const I=new Map(n.map(E=>[E.key,E.value]));return g.some(E=>I.get(E.key)!==E.value)}_mergeProfileCustomField(n=[],g=[]){const I=p(n)?n.map(E=>Object.assign({},E)):[];return p(g)&&g.length!==0&&g.forEach(({key:E,value:m})=>{const D=I.find(M=>M.key===E);D?D.value=m:I.push({key:E,value:m})}),I}_reset(){nc.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const Km=new Map,LD=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let s=0,n=LD.length;s>(-2*m&6)):0)E="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(E);try{return decodeURIComponent(escape(g))}catch(I){return console.warn(I),""}}const{isEmpty:yT}=me.utils,{generateProtocolData:jm}=me.common;function uR(s){return pA(this,void 0,void 0,function*(){const n="im_open_status.ws_get_user_status",g=jm({servcmd:n,data:{To_Account:s}}),I=`${g.head.seq}${n}`,E=yield me.channel.sendPacket(g,{requestId:I});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:YA,Detail:LA=[]}=EA;return{userID:wA,statusType:kA,customStatus:ZQ(YA),onlineDevices:DT(LA)}}),oA=T.map(EA=>{const{To_Account:wA,Invalid_Account:kA,ErrorCode:YA,ErrorInfo:LA}=EA;return{userID:yT(kA)?wA:kA,code:YA,message:LA}});return{errorCode:D,errorInfo:M,successUserList:W,failureUserList:oA}}(E)})}function DT(s){const n=[];return s?.forEach(g=>{const{Platform:I,Status:E}=g;E==="Online"&&n.push(I)}),n}class ST{constructor(){this._customStatus=""}init(){const{notificationCenter:n}=me;dr.getInstance().registerApi({apiName:"getUserStatus",context:this}),dr.getInstance().registerApi({apiName:"setSelfStatus",context:this}),dr.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),dr.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.USER_STATUS_UPDATE,this._onReOnline,this),n.subscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this)}setSelfStatus(n){return pA(this,void 0,void 0,function*(){const g=Ar(),{customStatus:I}=n;try{return yield function(E){return pA(this,void 0,void 0,function*(){const m="im_open_status.ws_set_custom_status",D=jm({servcmd:m,data:{CustomStatus:E}}),M=`${D.head.seq}${m}`,T=yield me.channel.sendPacket(D,{requestId:M});if(T){const{ErrorCode:P,ErrorInfo:W}=T;return{errorCode:P,errorInfo:W}}})}(I),this._customStatus=I,{code:0,data:{userID:g,statusType:yh,customStatus:I},successLog:{message:`customStatus: ${I}`}}}catch(E){const{errorCode:m,errorInfo:D}=E;throw new as({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 I=yield this._getUserStatus(g);return Object.assign(Object.assign({},I),{successLog:{message:`userIDList length: ${g.length}`}})})}setCustomStatus(n){const g=ZQ(n);this._customStatus=g}subscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{const{userIDList:g=[]}=n;this._checkBusinessCapabilityBits("subscribeUserStatus");const I=this._getMaxUserCount("subscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_subscribe",W=jm({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:I}=g;throw new as({functionName:"subscribeUserStatus",code:I})}})}unsubscribeUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:g=[]}=n,I=this._getMaxUserCount("unsubscribe"),E=this._sliceUserIDList(g,I),m=yield function(M){return pA(this,void 0,void 0,function*(){const{channel:T}=me,P="im_open_status.ws_status_unsubscribe";let W={};W=M.length===0?{UnsubscribeAll:1}:{To_Account:M};const oA=jm({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:I}=g;throw new as({functionName:"unsubscribeUserStatus",code:I})}})}_onUserStatusUpdate(n){const{UserStatusList:g=[]}=n||{},I=g.map(E=>{const{To_Account:m,Status:D,CustomStatus:M,Platform:T}=E,P={userID:m,statusType:D,customStatus:ZQ(M)};return T&&(P.onlineDevices=T),P});this._emitUserStatusUpdatedEvent(I)}_onReOnline(n){const g=ZQ(n.data.customStatus);if(this._customStatus===g)return;this._customStatus=g;const I={userID:Ar(),statusType:yh,customStatus:g};this._emitUserStatusUpdatedEvent(I)}_emitUserStatusUpdatedEvent(n){me.notificationCenter.emitOuterEvent(yr.USER_STATUS_UPDATED,{name:yr.USER_STATUS_UPDATED,data:n})}_sliceUserIDList(n,g){return n.slice(0,g)}_parseResponse(n){const{ErrorList:g=[]}=n;return g.map(I=>{const{To_Account:E,Invalid_Account:m,ErrorCode:D,ErrorInfo:M}=I;return{userID:me.utils.isEmpty(m)?E:m,code:D,message:M}})}_checkBusinessCapabilityBits(n){if(!me.store.get("commercialConfig").get(fT))throw new as({functionName:n,code:ua.NO_USE,replacement1:n})}_getMaxUserCount(n){const g=me.store.get("cloudConfig")||{},I={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}=I[n],D=g[E]||m;return parseInt(D,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:Ar(),statusType:yh,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(n){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const g=this._getMaxUserCount("query"),I=this._sliceUserIDList(n,g),E=yield uR(I),{successUserList:m,failureUserList:D}=E||{};return{code:0,data:{successUserList:m,failureUserList:D}}}catch(g){const{errorCode:I}=g;throw new as({functionName:"getUserStatus",code:I})}})}_isOnlyMeInArray(n){const g=Ar();return n.length===1&&n.indexOf(g)>-1}_dispose(){const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.MESSAGE_PUSH,n.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this),n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),this._reset()}_reset(){this._customStatus=""}}const UD={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(GD))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}}},MT={getMyProfile:!0,getUserProfile:!0,updateMyProfile:!0,setSelfStatus:!0,getUserStatus:!0,subscribeUserStatus:!0,unsubscribeUserStatus:!0};class vT{constructor(){this.userProfile=new qm,this.userStatus=new ST,this.userProfile.init(),this.userStatus.init(),Kc({auth:MT,params:UD})}}function FD(s){const n=[];if(!l(s))return n;const g=s.length;if(g===0)return n;for(let I=g-1;I>=0;I--)s[I]==="1"&&n.push(2**(g-I-1));return n}var Dd,BC,Sd;(function(s){s.NOT_START="notStart",s.PENDING="pending",s.RESOLVED="resolved",s.REJECTED="rejected"})(Dd||(Dd={})),function(s){s[s.C2C=1]="C2C",s[s.GROUP=2]="GROUP"}(BC||(BC={})),function(s){s[s.C2C=8]="C2C",s[s.GROUP=2]="GROUP"}(Sd||(Sd={}));class OD{constructor(){this._name="SyncConversationHandler",this._pagingStatus=Dd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}init(){const{notificationCenter:n}=me;Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Ht.CONVERSATION_RECOVER,this._syncConversationList,this),Rs.getInstance().registerWorkflowStep(Pt.SYNC_SERVER_INFO_AFTER_LOGIN,Ht.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),n.subscribeInnerEvent(so.LOGOUT,this._reset,this),n.subscribeInnerEvent(so.DESTROY,this._dispose,this),me.ssoLog.debug(`${this._name}.init`)}isSyncCompleted(){return this._pagingStatus===Dd.RESOLVED}_syncConversationListAfterLogin(){return pA(this,void 0,void 0,function*(){return this._pagingStatus=Dd.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}}=me;n.debug("_syncConversationList","start");try{const I=yield this._pagingGetConversationList(!0);this._pagingStatus=Dd.RESOLVED;const{conversationList:E=[]}=I||{};return n.info("_syncConversationList",`success count:${E.length}`),I}catch(I){const E=new as(I);n.error("_syncConversationList",`fail ${g(I)}`,{error:E})}})}_pagingGetConversationList(n){return pA(this,void 0,void 0,function*(){try{const g=[];this._pagingStatus=Dd.PENDING;const I=yield function(oA){return pA(this,void 0,void 0,function*(){const{fromAccount:EA,pagingTimeStamp:wA,pagingStartIndex:kA,pagingPinnedTimeStamp:YA,pagingPinnedStartIndex:LA}=oA;return ag({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:EA,StartIndex:kA,TimeStamp:wA,TopStartIndex:LA,TopTimeStamp:YA}})})}({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}=I||{};let W=[];if(E===1&&(this._pagingStatus=Dd.RESOLVED),m.length>0&&(W=this._getConversationOptions(m),g.push(...W)),me.notificationCenter.emitInnerEvent(so.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(n);g.push(...oA)}return{conversationList:g}}catch(g){throw g}})}_getConversationOptions(n){const{utils:{isUndefined:g}}=me,I=this._convertConversationKey(n);return this._filterValidConversations(I).map(E=>(g(E.lastMsg)&&(E.lastMsg={elements:[]}),E.type===BC.C2C?this._assembleC2COption(E):this._assembleGroupOption(E)))}_filterValidConversations(n){return n.filter(({type:g,userID:I})=>g===BC.C2C&&!function(E){let m;return E.startsWith(ko.CONV_C2C)&&(m=E.replace(ko.CONV_C2C,"")),m==="@TLS#ERROR"||m==="@TLS#NOT_FOUND"}(I)||g===2)}_assembleC2COption(n){var g,I,E,m,D,M,T,P;const W=this._createUserprofile(n);return{conversationID:`${ko.CONV_C2C}${n.userID}`,type:ko.CONV_C2C,lastMessage:{lastTime:n.time,lastSequence:n.sequence,fromAccount:n.lastC2CMsgFromAccount,type:!((g=n.lastMsg)===null||g===void 0)&&g.elements[0]?(I=n.lastMsg)===null||I===void 0?void 0:I.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===Sd.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:FD(n.standardMark),conversationGroupList:[],remark:n.friendRemark||"",messageRemindType:this._transMsgRemindType(n.messageRemindType)}}_createUserprofile(n){var g;const{userID:I,nick:E,peerAvatar:m}=n,D=[{tag:"Tag_Profile_IM_Nick",value:E},{tag:"Tag_Profile_IM_Image",value:m}];return(g=me.user.userProfile)===null||g===void 0?void 0:g.createProfile(I,D)}_computeIsPeerRead(n){const g=Ar(),{lastC2CMsgFromAccount:I,time:E,c2cPeerReadTime:m}=n;return I===g&&E<=m}_assembleGroupOption(n){var g,I,E,m,D;return{conversationID:`${ko.CONV_GROUP}${n.groupID}`,type:ko.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:n.time,lastSequence:n.sequence,fromAccount:n.msgGroupFromAccount},this._patchTypeAndPayload(n)),{cloudCustomData:((E=(I=(g=n.lastMsg)===null||g===void 0?void 0:g.elements)===null||I===void 0?void 0:I[0])===null||E===void 0?void 0:E.cloudCustomData)||"",isRevoked:n.lastMessageFlag===Sd.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:FD(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,I,E;const{utils:{isEmpty:m}}=me;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=ko.MSG_GRP_TIP,M=Object.assign(Object.assign({},this._parseContent(D,n.GroupTips.MsgBody)),{groupProfile:{from:T,groupName:P}})}return n.MsgBody&&(D=(I=n.MsgBody[0])===null||I===void 0?void 0:I.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 I;if(!g)return g;const E=me.message.messageFactory.getElementClass(n);return E?(I=E.parseServerPushElement(g))===null||I===void 0?void 0:I.content:g}_amendLayersOverLimitProp(n){const{LayersOverLimit:g}=n;return yo(n,["LayersOverLimit"]).layersOverLimit=g===1,n}_transMsgRemindType(n){let g="";return n===0?g=ko.MSG_REMIND_ACPT_AND_NOTE:n===1?g=ko.MSG_REMIND_DISCARD:n===2?g=ko.MSG_REMIND_ACPT_NOT_NOTE:n===3&&(g=ko.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),g}_patchTypeAndPayload(n){var g;const{utils:{isUndefined:I}}=me,{event:E,elements:m=[]}=n.lastMsg||{};return I(E)?{type:m[0]?m[0].type:null,payload:m[0]?this._amendLayersOverLimitProp(m[0].content):null}:{type:ko.MSG_GRP_TIP,payload:((g=m?.[0])===null||g===void 0?void 0:g.content)||{}}}_computeGroupUnreadCount(n){const{unreadCount:g=0,noUnreadCount:I=0}=n,E=g-I;return E>0?E:0}_reset(){this._pagingStatus=Dd.NOT_START,this._pagingTimeStamp=0,this._pagingStartIndex=0,this._pagingPinnedTimeStamp=0,this._pagingPinnedStartIndex=0}_dispose(){this._reset();const{notificationCenter:n}=me;n.unSubscribeInnerEvent(so.LOGOUT,this._reset,this),n.unSubscribeInnerEvent(so.DESTROY,this._dispose,this)}}class PD{constructor(){this.syncConversationHandler=new OD,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Wr}`);var xD={create:function(s){var n,g;const{SDKAppID:I,testEnv:E=!1,devMode:m=!1,unlimitedAVChatRoom:D=!1,scene:M="",oversea:T=!1,instance:P,disableIndependentDomain:W=!1,proxyServer:oA=""}=s;let EA=I;if(!function(kA){if(typeof kA=="number")return!0;const YA=Number(kA);return!Number.isNaN(YA)}(EA))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(EA=Number(EA),Ea.has(EA))return Ea.get(EA);let wA=null;if(P)wA=P,wA._workflowManager&&Rs.setInstance(wA._workflowManager),wA._pluginManager&&wA._pluginManager.installBuiltInPlugin(EB),P.isReady()&&((g=(n=Rs.getInstance()).executeWorkflow)===null||g===void 0||g.call(n,Pt.SYNC_SERVER_INFO_AFTER_LOGIN));else{const kA=function(){function se(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${se()+se()}${se()}${se()}${se()}${se()}${se()}${se()}`}();me.init({sdkAppId:EA,instanceId:kA,testEnv:E,devMode:m,unlimitedAVChatRoom:D,disableIndependentDomain:W,scene:M,oversea:T,sdkEdition:Fm,version:Wr,proxyServer:oA}),Rs.getInstance().init(),me.message=new ND,me.user=new vT,me.login=new hh,me.conversation=new PD,$I.getInstance().installBuiltInPlugin(EB),wA=dr.getInstance().exposeApiForClient(),wA._workflowManager=Rs.getInstance(),wA._pluginManager=$I.getInstance();const{utils:{IS_WORKER_AVAILABLE:YA,USER_AGENT:LA,getPlatformType:SA,isIOSWebView:OA}}=me,HA=`instanceID:${kA} SDKAppID:${I} platform:${qA} host:${SA()} isIOSWebView:${OA} workerAvailable:${YA} UserAgent:${LA}`;me.ssoLog.info("sdkConstruct",HA)}return Ea.set(EA,wA),wA},TSignaling:Jc,EVENT:yr,VERSION:Wr,TYPES:ko};return xD})}(l1)),l1.exports}var _iA=wiA();const tg=B3(_iA);var I1={exports:{}},TiA=I1.exports,Z5;function NiA(){return Z5||(Z5=1,function(t,i){(function(r,l){t.exports=l()})(TiA,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 ft=0;ft"u"&&typeof uni.requireNativePlugin=="function",PA=MA&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios",ge=(MA&&uni.getDeviceInfo().platform.toLocaleLowerCase(),lA||aA||mA||IA||tA||MA),de=F!==void 0&&(F.nativeModuleProxy!==void 0||F.ReactNative!==void 0),Ve=aA?qq:mA?tt:IA?swan:tA?my:lA?wx:MA?uni:{},Be=function(re){if(k(re)!=="object"||re===null)return!1;var qe=Object.getPrototypeOf(re);if(qe===null)return!0;for(var ft=qe;Object.getPrototypeOf(ft)!==null;)ft=Object.getPrototypeOf(ft);return qe===ft};function ct(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(Be(re)){for(var qe in re)if(Object.prototype.hasOwnProperty.call(re,qe))return!1;return!0}return!1}var mt=function(){return u(function re(){r(this,re),this._n="WebRequest"},[{key:"request",value:function(re,qe){var ft=this,si="".concat(this._n,".request"),Vt=re.downloadUrl||"",gi=(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(si," URL:").concat(Fi)),re.qs){var _o=function(ki){var os=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",Ko=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"=";return ct(ki)?"":Be(ki)?Object.keys(ki).map(function($i){var jt=encodeURIComponent($i)+Ko;return Array.isArray(ki[$i])?ki[$i].map(function(io){return jt+encodeURIComponent(io)}).join(os):jt+encodeURIComponent(ki[$i])}).filter(Boolean).join(os):void 0}(re.qs);_o&&(Fi+="".concat(Fi.indexOf("?")===-1?"?":"&").concat(_o))}var to=new XMLHttpRequest;to.open(gi,Fi,!0),to.responseType=re.dataType||"text";var uo=re.headers||{};if(re.uploadByIP&&(uo=w(w({},uo),{},{host:re.uploadIP})),!ct(uo))for(var Ys in uo)uo.hasOwnProperty(Ys)&&Ys.toLowerCase()!=="content-length"&&Ys.toLowerCase()!=="user-agent"&&Ys.toLowerCase()!=="origin"&&Ys.toLowerCase()!=="host"&&to.setRequestHeader(Ys,uo[Ys]);return to.onload=function(){if(to.status===200)qe(null,ft._xhrRes(to,ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),uo));else{if(re.uploadIP&&re.url.indexOf(re.uploadIP)===-1)return re.url=function(os,Ko){return os.replace(/^http(s)?:\/\/(.*?)\//,"https://".concat(Ko,"/"))}(re.url,re.uploadIP),re.uploadByIP=!0,ft.request(re,qe);var ki={code:to.status,message:JSON.stringify(to.responseText)};qe(ki,ft._xhrRes(to,ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),uo))}},to.onerror=function(ki){var os=ft._xhrBody(to,Vt,re.uploadByIP&&re.uploadIP),Ko={code:to.status,message:JSON.stringify(to.responseText)};os||to.statusText||to.status!==0||(ki.message="CORS blocked or network error"),qe(Ko,ft._xhrRes(to,os)),Ko=null},re.onProgress&&to.upload&&(to.upload.onprogress=function(ki){var os=ki.total,Ko=ki.loaded,$i=Math.floor(100*Ko/os);re.onProgress({total:os,loaded:Ko,percent:($i>=100?100:$i)/100})}),to.send(re.resources),to}},{key:"_xhrRes",value:function(re,qe){var ft={};return re.getAllResponseHeaders().trim().split(` +`).forEach(function(si){if(si){var Vt=si.indexOf(":"),gi=si.substr(0,Vt).trim().toLowerCase(),Fi=si.substr(Vt+1).trim();ft[gi]=Fi}}),{statusCode:re.status,statusMessage:re.statusText,headers:ft,data:qe}}},{key:"_xhrBody",value:function(re,qe,ft){return re.status===200&&qe?{location:qe,uploadIP:ft}:{response:re.responseText,uploadIP:ft}}}])}(),Ke=["unknown","image","video","audio","log"],Dt=["name"],qt=function(){return u(function re(){r(this,re)},[{key:"request",value:function(re,qe){var ft=this,si=re.resources,Vt=si===void 0?"":si,gi=re.headers,Fi=gi===void 0?{}:gi,_o=re.url,to=re.downloadUrl,uo=to===void 0?"":to,Ys=_o,ki=null,os=uo.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/),Ko=decodeURIComponent(os[3]),$i=Ko.indexOf("?")>-1?Ko.split("?")[0]:Ko,jt={key:re.fileKey?re.fileKey:$i,success_action_status:200,"Content-Type":""},io={};if(PA){var bi=_o.split("?sign=");if(bi.length>1){var Ms=bi[1];Ys="".concat(bi[0],"?sign=").concat(encodeURIComponent("".concat(Ms))),io.sign=decodeURIComponent(Ms),io.signature=decodeURIComponent(Ms)}}var qA={url:Ys,header:Fi,name:"file",filePath:Vt,formData:w(w({},jt),io),timeout:re.timeout||3e5};if(tA){var ce=qA;ce.name,qA=w(w({},function(Pe,kt){if(Pe==null)return{};var it,gt,Xt=function(Ge,je){if(Ge==null)return{};var Mt={};for(var Rt in Ge)if({}.hasOwnProperty.call(Ge,Rt)){if(je.includes(Rt))continue;Mt[Rt]=Ge[Rt]}return Mt}(Pe,kt);if(Object.getOwnPropertySymbols){var $t=Object.getOwnPropertySymbols(Pe);for(gt=0;gt<$t.length;gt++)it=$t[gt],kt.includes(it)||{}.propertyIsEnumerable.call(Pe,it)&&(Xt[it]=Pe[it])}return Xt}(ce,Dt)),{},{fileName:"file",fileType:Ke[re.fileType]})}return(ki=Ve.uploadFile(w(w({},qA),{},{success:function(Pe){ft._handleResponse({response:Pe,downloadUrl:uo,callback:qe})},fail:function(Pe){ft._handleResponse({response:Pe,downloadUrl:uo,callback:qe})}}))).onProgressUpdate&&ki.onProgressUpdate(function(Pe){re.onProgress&&re.onProgress({total:Pe.totalBytesExpectedToSend,loaded:Pe.totalBytesSent,percent:Math.floor(Pe.progress)/100})}),ki}},{key:"_handleResponse",value:function(re){var qe=re.downloadUrl,ft=re.response,si=re.callback,Vt=ft.header,gi={};if(Vt)for(var Fi in Vt)Vt.hasOwnProperty(Fi)&&(gi[Fi.toLowerCase()]=Vt[Fi]);var _o=+ft.statusCode;_o===200?si(null,{statusCode:_o,headers:gi,data:w(w({},ft.data),{},{location:qe})}):si({code:_o,message:JSON.stringify(ft.data)},{statusCode:_o,headers:gi,data:void 0})}}])}(),It=function(){return u(function re(){r(this,re)},[{key:"request",value:function(re,qe){var ft=this,si=re.resources,Vt=si===void 0?"":si,gi=re.fileKey,Fi=gi===void 0?"":gi,_o=re.url,to=re.downloadUrl,uo=to===void 0?"":to,Ys=new FormData;Ys.append("key",Fi),Ys.append("success_action_status",200),Ys.append("file",{uri:Vt,type:"application/octet-stream",name:"uploaded_file"}),fetch(_o,{method:"POST",headers:{"Content-Type":"multipart/form-data"},body:Ys}).then(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})}).catch(function(ki){ft._handleResponse({response:ki,downloadUrl:uo,callback:qe})})}},{key:"_handleResponse",value:function(re){var qe=re.downloadUrl,ft=re.response,si=re.callback,Vt=ft.headers,gi=ft.status,Fi=Vt&&Vt.map||{};gi===200?si(null,{statusCode:200,headers:Fi,data:{location:qe}}):si({code:gi,message:JSON.stringify(ft)},{statusCode:gi,headers:Fi,data:void 0})}}])}();return function(){return u(function re(){r(this,re),this.retry=1,this.tryCount=0,this.systemClockOffset=0,this.httpRequest=ge?new qt:de?new It:new mt,console.log("TIMUploadPlugin.VERSION: ".concat("1.4.3"))},[{key:"uploadFile",value:function(re,qe){var ft=this;return this.httpRequest.request(re,function(si,Vt){si&&ft.tryCount=3e4&&(this.systemClockOffset=_o-Fi,qe=!0)}else Math.floor(re.statusCode/100)===5&&(qe=!0)}return qe}}],[{key:"getVersion",value:function(){return"1.4.3"}}])}()})}(I1)),I1.exports}var GiA=NiA();const biA=B3(GiA);/** +* @vue/shared v3.5.13 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**//*! #__NO_SIDE_EFFECTS__ */function Q3(t){const i=Object.create(null);for(const r of t.split(","))i[r]=1;return r=>r in i}const fa={},f_=[],CQ=()=>{},kiA=()=>!1,rY=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&(t.charCodeAt(2)>122||t.charCodeAt(2)<97),p3=t=>t.startsWith("onUpdate:"),$l=Object.assign,m3=(t,i)=>{const r=t.indexOf(i);r>-1&&t.splice(r,1)},LiA=Object.prototype.hasOwnProperty,qr=(t,i)=>LiA.call(t,i),Ss=Array.isArray,y_=t=>aY(t)==="[object Map]",rZ=t=>aY(t)==="[object Set]",Xs=t=>typeof t=="function",mg=t=>typeof t=="string",nm=t=>typeof t=="symbol",Ta=t=>t!==null&&typeof t=="object",aZ=t=>(Ta(t)||Xs(t))&&Xs(t.then)&&Xs(t.catch),gZ=Object.prototype.toString,aY=t=>gZ.call(t),UiA=t=>aY(t).slice(8,-1),cZ=t=>aY(t)==="[object Object]",f3=t=>mg(t)&&t!=="NaN"&&t[0]!=="-"&&""+parseInt(t,10)===t,dL=Q3(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),gY=t=>{const i=Object.create(null);return r=>i[r]||(i[r]=t(r))},FiA=/-(\w)/g,KC=gY(t=>t.replace(FiA,(i,r)=>r?r.toUpperCase():"")),OiA=/\B([A-Z])/g,Yy=gY(t=>t.replace(OiA,"-$1").toLowerCase()),cY=gY(t=>t.charAt(0).toUpperCase()+t.slice(1)),_K=gY(t=>t?`on${cY(t)}`:""),Ny=(t,i)=>!Object.is(t,i),u1=(t,...i)=>{for(let r=0;r{Object.defineProperty(t,i,{configurable:!0,enumerable:!1,writable:l,value:r})},Sj=t=>{const i=parseFloat(t);return isNaN(i)?t:i},PiA=t=>{const i=mg(t)?Number(t):NaN;return isNaN(i)?t:i};let X5;const lY=()=>X5||(X5=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function hr(t){if(Ss(t)){const i={};for(let r=0;r{if(r){const l=r.split(YiA);l.length>1&&(i[l[0].trim()]=l[1].trim())}}),i}function Xi(t){let i="";if(mg(t))i=t;else if(Ss(t))for(let r=0;r!!(t&&t.__v_isRef===!0),Si=t=>mg(t)?t:t==null?"":Ss(t)||Ta(t)&&(t.toString===gZ||!Xs(t.toString))?uZ(t)?Si(t.value):JSON.stringify(t,EZ,2):String(t),EZ=(t,i)=>uZ(i)?EZ(t,i.value):y_(i)?{[`Map(${i.size})`]:[...i.entries()].reduce((r,[l,u],p)=>(r[TK(l,p)+" =>"]=u,r),{})}:rZ(i)?{[`Set(${i.size})`]:[...i.values()].map(r=>TK(r))}:nm(i)?TK(i):Ta(i)&&!Ss(i)&&!cZ(i)?String(i):i,TK=(t,i="")=>{var r;return nm(t)?`Symbol(${(r=t.description)!=null?r:i})`:t};/** +* @vue/reactivity v3.5.13 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let Hd;class jiA{constructor(i=!1){this.detached=i,this._active=!0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.parent=Hd,!i&&Hd&&(this.index=(Hd.scopes||(Hd.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(hL){let i=hL;for(hL=void 0;i;){const r=i.next;i.next=void 0,i.flags&=-9,i=r}}let t;for(;CL;){let i=CL;for(CL=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 BZ(t){for(let i=t.deps;i;i=i.nextDep)i.version=-1,i.prevActiveLink=i.dep.activeLink,i.dep.activeLink=i}function QZ(t){let i,r=t.depsTail,l=r;for(;l;){const u=l.prevDep;l.version===-1?(l===r&&(r=u),S3(l),ziA(l)):i=l,l.dep.activeLink=l.prevActiveLink,l.prevActiveLink=void 0,l=u}t.deps=i,t.depsTail=r}function Mj(t){for(let i=t.deps;i;i=i.nextDep)if(i.dep.version!==i.version||i.dep.computed&&(pZ(i.dep.computed)||i.dep.version!==i.version))return!0;return!!t._dirty}function pZ(t){if(t.flags&4&&!(t.flags&16)||(t.flags&=-17,t.globalVersion===kL))return;t.globalVersion=kL;const i=t.dep;if(t.flags|=2,i.version>0&&!t.isSSR&&t.deps&&!Mj(t)){t.flags&=-3;return}const r=Ra,l=Wh;Ra=t,Wh=!0;try{BZ(t);const u=t.fn(t._value);(i.version===0||Ny(u,t._value))&&(t._value=u,i.version++)}catch(u){throw i.version++,u}finally{Ra=r,Wh=l,QZ(t),t.flags&=-3}}function S3(t,i=!1){const{dep:r,prevSub:l,nextSub:u}=t;if(l&&(l.nextSub=u,t.prevSub=void 0),u&&(u.prevSub=l,t.nextSub=void 0),r.subs===t&&(r.subs=l,!l&&r.computed)){r.computed.flags&=-5;for(let p=r.computed.deps;p;p=p.nextDep)S3(p,!0)}!i&&!--r.sc&&r.map&&r.map.delete(r.key)}function ziA(t){const{prevDep:i,nextDep:r}=t;i&&(i.nextDep=r,t.prevDep=void 0),r&&(r.prevDep=i,t.nextDep=void 0)}let Wh=!0;const mZ=[];function Vy(){mZ.push(Wh),Wh=!1}function Jy(){const t=mZ.pop();Wh=t===void 0?!0:t}function $5(t){const{cleanup:i}=t;if(t.cleanup=void 0,i){const r=Ra;Ra=void 0;try{i()}finally{Ra=r}}}let kL=0;class ZiA{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 M3{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(!Ra||!Wh||Ra===this.computed)return;let r=this.activeLink;if(r===void 0||r.sub!==Ra)r=this.activeLink=new ZiA(Ra,this),Ra.deps?(r.prevDep=Ra.depsTail,Ra.depsTail.nextDep=r,Ra.depsTail=r):Ra.deps=Ra.depsTail=r,fZ(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=Ra.depsTail,r.nextDep=void 0,Ra.depsTail.nextDep=r,Ra.depsTail=r,Ra.deps===r&&(Ra.deps=l)}return r}trigger(i){this.version++,kL++,this.notify(i)}notify(i){y3();try{for(let r=this.subs;r;r=r.prevSub)r.sub.notify()&&r.sub.dep.notify()}finally{D3()}}}function fZ(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)fZ(l)}const r=t.dep.subs;r!==t&&(t.prevSub=r,r&&(r.nextSub=t)),t.dep.subs=t}}const T1=new WeakMap,$M=Symbol(""),vj=Symbol(""),LL=Symbol("");function lu(t,i,r){if(Wh&&Ra){let l=T1.get(t);l||T1.set(t,l=new Map);let u=l.get(r);u||(l.set(r,u=new M3),u.map=l,u.key=r),u.track()}}function em(t,i,r,l,u,p){const y=T1.get(t);if(!y){kL++;return}const w=_=>{_&&_.trigger()};if(y3(),i==="clear")y.forEach(w);else{const _=Ss(t),k=_&&f3(r);if(_&&r==="length"){const F=Number(l);y.forEach((j,lA)=>{(lA==="length"||lA===LL||!nm(lA)&&lA>=F)&&w(j)})}else switch((r!==void 0||y.has(void 0))&&w(y.get(r)),k&&w(y.get(LL)),i){case"add":_?k&&w(y.get("length")):(w(y.get($M)),y_(t)&&w(y.get(vj)));break;case"delete":_||(w(y.get($M)),y_(t)&&w(y.get(vj)));break;case"set":y_(t)&&w(y.get($M));break}}D3()}function XiA(t,i){const r=T1.get(t);return r&&r.get(i)}function A_(t){const i=Tr(t);return i===t?i:(lu(i,"iterate",LL),JC(t)?i:i.map(Iu))}function IY(t){return lu(t=Tr(t),"iterate",LL),t}const $iA={__proto__:null,[Symbol.iterator](){return GK(this,Symbol.iterator,Iu)},concat(...t){return A_(this).concat(...t.map(i=>Ss(i)?A_(i):i))},entries(){return GK(this,"entries",t=>(t[1]=Iu(t[1]),t))},every(t,i){return Kp(this,"every",t,i,void 0,arguments)},filter(t,i){return Kp(this,"filter",t,i,r=>r.map(Iu),arguments)},find(t,i){return Kp(this,"find",t,i,Iu,arguments)},findIndex(t,i){return Kp(this,"findIndex",t,i,void 0,arguments)},findLast(t,i){return Kp(this,"findLast",t,i,Iu,arguments)},findLastIndex(t,i){return Kp(this,"findLastIndex",t,i,void 0,arguments)},forEach(t,i){return Kp(this,"forEach",t,i,void 0,arguments)},includes(...t){return bK(this,"includes",t)},indexOf(...t){return bK(this,"indexOf",t)},join(t){return A_(this).join(t)},lastIndexOf(...t){return bK(this,"lastIndexOf",t)},map(t,i){return Kp(this,"map",t,i,void 0,arguments)},pop(){return Vk(this,"pop")},push(...t){return Vk(this,"push",t)},reduce(t,...i){return Az(this,"reduce",t,i)},reduceRight(t,...i){return Az(this,"reduceRight",t,i)},shift(){return Vk(this,"shift")},some(t,i){return Kp(this,"some",t,i,void 0,arguments)},splice(...t){return Vk(this,"splice",t)},toReversed(){return A_(this).toReversed()},toSorted(t){return A_(this).toSorted(t)},toSpliced(...t){return A_(this).toSpliced(...t)},unshift(...t){return Vk(this,"unshift",t)},values(){return GK(this,"values",Iu)}};function GK(t,i,r){const l=IY(t),u=l[i]();return l!==t&&!JC(t)&&(u._next=u.next,u.next=()=>{const p=u._next();return p.value&&(p.value=r(p.value)),p}),u}const AoA=Array.prototype;function Kp(t,i,r,l,u,p){const y=IY(t),w=y!==t&&!JC(t),_=y[i];if(_!==AoA[i]){const j=_.apply(t,p);return w?Iu(j):j}let k=r;y!==t&&(w?k=function(j,lA){return r.call(this,Iu(j),lA,t)}:r.length>2&&(k=function(j,lA){return r.call(this,j,lA,t)}));const F=_.call(y,k,l);return w&&u?u(F):F}function Az(t,i,r,l){const u=IY(t);let p=r;return u!==t&&(JC(t)?r.length>3&&(p=function(y,w,_){return r.call(this,y,w,_,t)}):p=function(y,w,_){return r.call(this,y,Iu(w),_,t)}),u[i](p,...l)}function bK(t,i,r){const l=Tr(t);lu(l,"iterate",LL);const u=l[i](...r);return(u===-1||u===!1)&&w3(r[0])?(r[0]=Tr(r[0]),l[i](...r)):u}function Vk(t,i,r=[]){Vy(),y3();const l=Tr(t)[i].apply(t,r);return D3(),Jy(),l}const eoA=Q3("__proto__,__v_isRef,__isVue"),yZ=new Set(Object.getOwnPropertyNames(Symbol).filter(t=>t!=="arguments"&&t!=="caller").map(t=>Symbol[t]).filter(nm));function toA(t){nm(t)||(t=String(t));const i=Tr(this);return lu(i,"has",t),i.hasOwnProperty(t)}class DZ{constructor(i=!1,r=!1){this._isReadonly=i,this._isShallow=r}get(i,r,l){if(r==="__v_skip")return i.__v_skip;const u=this._isReadonly,p=this._isShallow;if(r==="__v_isReactive")return!u;if(r==="__v_isReadonly")return u;if(r==="__v_isShallow")return p;if(r==="__v_raw")return l===(u?p?IoA:RZ:p?vZ:MZ).get(i)||Object.getPrototypeOf(i)===Object.getPrototypeOf(l)?i:void 0;const y=Ss(i);if(!u){let _;if(y&&(_=$iA[r]))return _;if(r==="hasOwnProperty")return toA}const w=Reflect.get(i,r,Xl(i)?i:l);return(nm(r)?yZ.has(r):eoA(r))||(u||lu(i,"get",r),p)?w:Xl(w)?y&&f3(r)?w:w.value:Ta(w)?u?qh(w):WM(w):w}}class SZ extends DZ{constructor(i=!1){super(!1,i)}set(i,r,l,u){let p=i[r];if(!this._isShallow){const _=av(p);if(!JC(l)&&!av(l)&&(p=Tr(p),l=Tr(l)),!Ss(i)&&Xl(p)&&!Xl(l))return _?!1:(p.value=l,!0)}const y=Ss(i)&&f3(r)?Number(r)t,H2=t=>Reflect.getPrototypeOf(t);function roA(t,i,r){return function(...l){const u=this.__v_raw,p=Tr(u),y=y_(p),w=t==="entries"||t===Symbol.iterator&&y,_=t==="keys"&&y,k=u[t](...l),F=r?Rj:i?wj:Iu;return!i&&lu(p,"iterate",_?vj:$M),{next(){const{value:j,done:lA}=k.next();return lA?{value:j,done:lA}:{value:w?[F(j[0]),F(j[1])]:F(j),done:lA}},[Symbol.iterator](){return this}}}}function q2(t){return function(...i){return t==="delete"?!1:t==="clear"?void 0:this}}function aoA(t,i){const r={get(u){const p=this.__v_raw,y=Tr(p),w=Tr(u);t||(Ny(u,w)&&lu(y,"get",u),lu(y,"get",w));const{has:_}=H2(y),k=i?Rj:t?wj:Iu;if(_.call(y,u))return k(p.get(u));if(_.call(y,w))return k(p.get(w));p!==y&&p.get(u)},get size(){const u=this.__v_raw;return!t&&lu(Tr(u),"iterate",$M),Reflect.get(u,"size",u)},has(u){const p=this.__v_raw,y=Tr(p),w=Tr(u);return t||(Ny(u,w)&&lu(y,"has",u),lu(y,"has",w)),u===w?p.has(u):p.has(u)||p.has(w)},forEach(u,p){const y=this,w=y.__v_raw,_=Tr(w),k=i?Rj:t?wj:Iu;return!t&&lu(_,"iterate",$M),w.forEach((F,j)=>u.call(p,k(F),k(j),y))}};return $l(r,t?{add:q2("add"),set:q2("set"),delete:q2("delete"),clear:q2("clear")}:{add(u){!i&&!JC(u)&&!av(u)&&(u=Tr(u));const p=Tr(this);return H2(p).has.call(p,u)||(p.add(u),em(p,"add",u,u)),this},set(u,p){!i&&!JC(p)&&!av(p)&&(p=Tr(p));const y=Tr(this),{has:w,get:_}=H2(y);let k=w.call(y,u);k||(u=Tr(u),k=w.call(y,u));const F=_.call(y,u);return y.set(u,p),k?Ny(p,F)&&em(y,"set",u,p):em(y,"add",u,p),this},delete(u){const p=Tr(this),{has:y,get:w}=H2(p);let _=y.call(p,u);_||(u=Tr(u),_=y.call(p,u)),w&&w.call(p,u);const k=p.delete(u);return _&&em(p,"delete",u,void 0),k},clear(){const u=Tr(this),p=u.size!==0,y=u.clear();return p&&em(u,"clear",void 0,void 0),y}}),["keys","values","entries",Symbol.iterator].forEach(u=>{r[u]=roA(u,t,i)}),r}function v3(t,i){const r=aoA(t,i);return(l,u,p)=>u==="__v_isReactive"?!t:u==="__v_isReadonly"?t:u==="__v_raw"?l:Reflect.get(qr(r,u)&&u in l?r:l,u,p)}const goA={get:v3(!1,!1)},coA={get:v3(!1,!0)},loA={get:v3(!0,!1)};const MZ=new WeakMap,vZ=new WeakMap,RZ=new WeakMap,IoA=new WeakMap;function uoA(t){switch(t){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function EoA(t){return t.__v_skip||!Object.isExtensible(t)?0:uoA(UiA(t))}function WM(t){return av(t)?t:R3(t,!1,ooA,goA,MZ)}function doA(t){return R3(t,!1,noA,coA,vZ)}function qh(t){return R3(t,!0,soA,loA,RZ)}function R3(t,i,r,l,u){if(!Ta(t)||t.__v_raw&&!(i&&t.__v_isReactive))return t;const p=u.get(t);if(p)return p;const y=EoA(t);if(y===0)return t;const w=new Proxy(t,y===2?l:r);return u.set(t,w),w}function D_(t){return av(t)?D_(t.__v_raw):!!(t&&t.__v_isReactive)}function av(t){return!!(t&&t.__v_isReadonly)}function JC(t){return!!(t&&t.__v_isShallow)}function w3(t){return t?!!t.__v_raw:!1}function Tr(t){const i=t&&t.__v_raw;return i?Tr(i):t}function CoA(t){return!qr(t,"__v_skip")&&Object.isExtensible(t)&&lZ(t,"__v_skip",!0),t}const Iu=t=>Ta(t)?WM(t):t,wj=t=>Ta(t)?qh(t):t;function Xl(t){return t?t.__v_isRef===!0:!1}function $e(t){return hoA(t,!1)}function hoA(t,i){return Xl(t)?t:new BoA(t,i)}class BoA{constructor(i,r){this.dep=new M3,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=r?i:Tr(i),this._value=r?i:Iu(i),this.__v_isShallow=r}get value(){return this.dep.track(),this._value}set value(i){const r=this._rawValue,l=this.__v_isShallow||JC(i)||av(i);i=l?i:Tr(i),Ny(i,r)&&(this._rawValue=i,this._value=l?i:Iu(i),this.dep.trigger())}}function gA(t){return Xl(t)?t.value:t}const QoA={get:(t,i,r)=>i==="__v_raw"?t:gA(Reflect.get(t,i,r)),set:(t,i,r,l)=>{const u=t[i];return Xl(u)&&!Xl(r)?(u.value=r,!0):Reflect.set(t,i,r,l)}};function wZ(t){return D_(t)?t:new Proxy(t,QoA)}function Ns(t){const i=Ss(t)?new Array(t.length):{};for(const r in t)i[r]=_Z(t,r);return i}class poA{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 XiA(Tr(this._object),this._key)}}class moA{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 kK(t,i,r){return Xl(t)?t:Xs(t)?new moA(t):Ta(t)&&arguments.length>1?_Z(t,i,r):$e(t)}function _Z(t,i,r){const l=t[i];return Xl(l)?l:new poA(t,i,r)}class foA{constructor(i,r,l){this.fn=i,this.setter=r,this._value=void 0,this.dep=new M3(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=kL-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!r,this.isSSR=l}notify(){if(this.flags|=16,!(this.flags&8)&&Ra!==this)return hZ(this,!0),!0}get value(){const i=this.dep.track();return pZ(this),i&&(i.version=this.dep.version),this._value}set value(i){this.setter&&this.setter(i)}}function yoA(t,i,r=!1){let l,u;return Xs(t)?l=t:(l=t.get,u=t.set),new foA(l,u,r)}const K2={},N1=new WeakMap;let VM;function DoA(t,i=!1,r=VM){if(r){let l=N1.get(r);l||N1.set(r,l=[]),l.push(t)}}function SoA(t,i,r=fa){const{immediate:l,deep:u,once:p,scheduler:y,augmentJob:w,call:_}=r,k=de=>u?de:JC(de)||u===!1||u===0?tm(de,1):tm(de);let F,j,lA,aA,mA=!1,IA=!1;if(Xl(t)?(j=()=>t.value,mA=JC(t)):D_(t)?(j=()=>k(t),mA=!0):Ss(t)?(IA=!0,mA=t.some(de=>D_(de)||JC(de)),j=()=>t.map(de=>{if(Xl(de))return de.value;if(D_(de))return k(de);if(Xs(de))return _?_(de,2):de()})):Xs(t)?i?j=_?()=>_(t,2):t:j=()=>{if(lA){Vy();try{lA()}finally{Jy()}}const de=VM;VM=F;try{return _?_(t,3,[aA]):t(aA)}finally{VM=de}}:j=CQ,i&&u){const de=j,Ve=u===!0?1/0:u;j=()=>tm(de(),Ve)}const tA=WiA(),MA=()=>{F.stop(),tA&&tA.active&&m3(tA.effects,F)};if(p&&i){const de=i;i=(...Ve)=>{de(...Ve),MA()}}let PA=IA?new Array(t.length).fill(K2):K2;const ge=de=>{if(!(!(F.flags&1)||!F.dirty&&!de))if(i){const Ve=F.run();if(u||mA||(IA?Ve.some((Be,ct)=>Ny(Be,PA[ct])):Ny(Ve,PA))){lA&&lA();const Be=VM;VM=F;try{const ct=[Ve,PA===K2?void 0:IA&&PA[0]===K2?[]:PA,aA];_?_(i,3,ct):i(...ct),PA=Ve}finally{VM=Be}}}else F.run()};return w&&w(ge),F=new dZ(j),F.scheduler=y?()=>y(ge,!1):ge,aA=de=>DoA(de,!1,F),lA=F.onStop=()=>{const de=N1.get(F);if(de){if(_)_(de,4);else for(const Ve of de)Ve();N1.delete(F)}},i?l?ge(!0):PA=F.run():y?y(ge.bind(null,!0),!0):F.run(),MA.pause=F.pause.bind(F),MA.resume=F.resume.bind(F),MA.stop=MA,MA}function tm(t,i=1/0,r){if(i<=0||!Ta(t)||t.__v_skip||(r=r||new Set,r.has(t)))return t;if(r.add(t),i--,Xl(t))tm(t.value,i,r);else if(Ss(t))for(let l=0;l{tm(l,i,r)});else if(cZ(t)){for(const l in t)tm(t[l],i,r);for(const l of Object.getOwnPropertySymbols(t))Object.prototype.propertyIsEnumerable.call(t,l)&&tm(t[l],i,r)}return t}/** +* @vue/runtime-core v3.5.13 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/function XL(t,i,r,l){try{return l?t(...l):t()}catch(u){uY(u,i,r)}}function Zh(t,i,r,l){if(Xs(t)){const u=XL(t,i,r,l);return u&&aZ(u)&&u.catch(p=>{uY(p,i,r)}),u}if(Ss(t)){const u=[];for(let p=0;p>>1,u=cE[l],p=UL(u);p=UL(r)?cE.push(t):cE.splice(voA(i),0,t),t.flags|=1,NZ()}}function NZ(){G1||(G1=TZ.then(bZ))}function RoA(t){Ss(t)?S_.push(...t):Sy&&t.id===-1?Sy.splice(s_+1,0,t):t.flags&1||(S_.push(t),t.flags|=1),NZ()}function ez(t,i,r=gQ+1){for(;rUL(r)-UL(l));if(S_.length=0,Sy){Sy.push(...i);return}for(Sy=i,s_=0;s_t.id==null?t.flags&2?-1:1/0:t.id;function bZ(t){try{for(gQ=0;gQ{l._d&&dz(-1);const p=b1(i);let y;try{y=t(...u)}finally{b1(p),l._d&&dz(1)}return y};return l._n=!0,l._c=!0,l._d=!0,l}function wa(t,i){if(Zl===null)return t;const r=QY(Zl),l=t.dirs||(t.dirs=[]);for(let u=0;ut.__isTeleport,BL=t=>t&&(t.disabled||t.disabled===""),tz=t=>t&&(t.defer||t.defer===""),iz=t=>typeof SVGElement<"u"&&t instanceof SVGElement,oz=t=>typeof MathMLElement=="function"&&t instanceof MathMLElement,_j=(t,i)=>{const r=t&&t.to;return mg(r)?i?i(r):null:r},UZ={name:"Teleport",__isTeleport:!0,process(t,i,r,l,u,p,y,w,_,k){const{mc:F,pc:j,pbc:lA,o:{insert:aA,querySelector:mA,createText:IA,createComment:tA}}=k,MA=BL(i.props);let{shapeFlag:PA,children:ge,dynamicChildren:de}=i;if(t==null){const Ve=i.el=IA(""),Be=i.anchor=IA("");aA(Ve,r,l),aA(Be,r,l);const ct=(Ke,Dt)=>{PA&16&&(u&&u.isCE&&(u.ce._teleportTarget=Ke),F(ge,Ke,Dt,u,p,y,w,_))},mt=()=>{const Ke=i.target=_j(i.props,mA),Dt=FZ(Ke,i,IA,aA);Ke&&(y!=="svg"&&iz(Ke)?y="svg":y!=="mathml"&&oz(Ke)&&(y="mathml"),MA||(ct(Ke,Dt),E1(i,!1)))};MA&&(ct(r,Be),E1(i,!0)),tz(i.props)?aE(()=>{mt(),i.el.__isMounted=!0},p):mt()}else{if(tz(i.props)&&!t.el.__isMounted){aE(()=>{UZ.process(t,i,r,l,u,p,y,w,_,k),delete t.el.__isMounted},p);return}i.el=t.el,i.targetStart=t.targetStart;const Ve=i.anchor=t.anchor,Be=i.target=t.target,ct=i.targetAnchor=t.targetAnchor,mt=BL(t.props),Ke=mt?r:Be,Dt=mt?Ve:ct;if(y==="svg"||iz(Be)?y="svg":(y==="mathml"||oz(Be))&&(y="mathml"),de?(lA(t.dynamicChildren,de,Ke,u,p,y,w),N3(t,i,!0)):_||j(t,i,Ke,Dt,u,p,y,w,!1),MA)mt?i.props&&t.props&&i.props.to!==t.props.to&&(i.props.to=t.props.to):j2(i,r,Ve,k,1);else if((i.props&&i.props.to)!==(t.props&&t.props.to)){const qt=i.target=_j(i.props,mA);qt&&j2(i,qt,null,k,0)}else mt&&j2(i,Be,ct,k,1);E1(i,MA)}},remove(t,i,r,{um:l,o:{remove:u}},p){const{shapeFlag:y,children:w,anchor:_,targetStart:k,targetAnchor:F,target:j,props:lA}=t;if(j&&(u(k),u(F)),p&&u(_),y&16){const aA=p||!BL(lA);for(let mA=0;mA{t.isMounted=!0}),qZ(()=>{t.isUnmounting=!0}),t}const GC=[Function,Array],OZ={mode:String,appear:Boolean,persisted:Boolean,onBeforeEnter:GC,onEnter:GC,onAfterEnter:GC,onEnterCancelled:GC,onBeforeLeave:GC,onLeave:GC,onAfterLeave:GC,onLeaveCancelled:GC,onBeforeAppear:GC,onAppear:GC,onAfterAppear:GC,onAppearCancelled:GC},PZ=t=>{const i=t.subTree;return i.component?PZ(i.component):i},NoA={name:"BaseTransition",props:OZ,setup(t,{slots:i}){const r=RsA(),l=ToA();return()=>{const u=i.default&&VZ(i.default(),!0);if(!u||!u.length)return;const p=xZ(u),y=Tr(t),{mode:w}=y;if(l.isLeaving)return LK(p);const _=sz(p);if(!_)return LK(p);let k=Tj(_,y,l,r,j=>k=j);_.type!==lE&&FL(_,k);let F=r.subTree&&sz(r.subTree);if(F&&F.type!==lE&&!JM(_,F)&&PZ(r).type!==lE){let j=Tj(F,y,l,r);if(FL(F,j),w==="out-in"&&_.type!==lE)return l.isLeaving=!0,j.afterLeave=()=>{l.isLeaving=!1,r.job.flags&8||r.update(),delete j.afterLeave,F=void 0},LK(p);w==="in-out"&&_.type!==lE?j.delayLeave=(lA,aA,mA)=>{const IA=YZ(l,F);IA[String(F.key)]=F,lA[My]=()=>{aA(),lA[My]=void 0,delete k.delayedLeave,F=void 0},k.delayedLeave=()=>{mA(),delete k.delayedLeave,F=void 0}}:F=void 0}else F&&(F=void 0);return p}}};function xZ(t){let i=t[0];if(t.length>1){for(const r of t)if(r.type!==lE){i=r;break}}return i}const GoA=NoA;function YZ(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 Tj(t,i,r,l,u){const{appear:p,mode:y,persisted:w=!1,onBeforeEnter:_,onEnter:k,onAfterEnter:F,onEnterCancelled:j,onBeforeLeave:lA,onLeave:aA,onAfterLeave:mA,onLeaveCancelled:IA,onBeforeAppear:tA,onAppear:MA,onAfterAppear:PA,onAppearCancelled:ge}=i,de=String(t.key),Ve=YZ(r,t),Be=(Ke,Dt)=>{Ke&&Zh(Ke,l,9,Dt)},ct=(Ke,Dt)=>{const qt=Dt[1];Be(Ke,Dt),Ss(Ke)?Ke.every(It=>It.length<=1)&&qt():Ke.length<=1&&qt()},mt={mode:y,persisted:w,beforeEnter(Ke){let Dt=_;if(!r.isMounted)if(p)Dt=tA||_;else return;Ke[My]&&Ke[My](!0);const qt=Ve[de];qt&&JM(t,qt)&&qt.el[My]&&qt.el[My](),Be(Dt,[Ke])},enter(Ke){let Dt=k,qt=F,It=j;if(!r.isMounted)if(p)Dt=MA||k,qt=PA||F,It=ge||j;else return;let re=!1;const qe=Ke[W2]=ft=>{re||(re=!0,ft?Be(It,[Ke]):Be(qt,[Ke]),mt.delayedLeave&&mt.delayedLeave(),Ke[W2]=void 0)};Dt?ct(Dt,[Ke,qe]):qe()},leave(Ke,Dt){const qt=String(t.key);if(Ke[W2]&&Ke[W2](!0),r.isUnmounting)return Dt();Be(lA,[Ke]);let It=!1;const re=Ke[My]=qe=>{It||(It=!0,Dt(),qe?Be(IA,[Ke]):Be(mA,[Ke]),Ke[My]=void 0,Ve[qt]===t&&delete Ve[qt])};Ve[qt]=t,aA?ct(aA,[Ke,re]):re()},clone(Ke){const Dt=Tj(Ke,i,r,l,u);return u&&u(Dt),Dt}};return mt}function LK(t){if(dY(t))return t=Uy(t),t.children=null,t}function sz(t){if(!dY(t))return LZ(t.type)&&t.children?xZ(t.children):t;const{shapeFlag:i,children:r}=t;if(r){if(i&16)return r[0];if(i&32&&Xs(r.default))return r.default()}}function FL(t,i){t.shapeFlag&6&&t.component?(t.transition=i,FL(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 VZ(t,i=!1,r){let l=[],u=0;for(let p=0;p1)for(let p=0;pk1(mA,i&&(Ss(i)?i[IA]:i),r,l,u));return}if(M_(l)&&!u){l.shapeFlag&512&&l.type.__asyncResolved&&l.component.subTree.component&&k1(t,i,r,l.component.subTree);return}const p=l.shapeFlag&4?QY(l.component):l.el,y=u?null:p,{i:w,r:_}=t,k=i&&i.r,F=w.refs===fa?w.refs={}:w.refs,j=w.setupState,lA=Tr(j),aA=j===fa?()=>!1:mA=>qr(lA,mA);if(k!=null&&k!==_&&(mg(k)?(F[k]=null,aA(k)&&(j[k]=null)):Xl(k)&&(k.value=null)),Xs(_))XL(_,w,12,[y,F]);else{const mA=mg(_),IA=Xl(_);if(mA||IA){const tA=()=>{if(t.f){const MA=mA?aA(_)?j[_]:F[_]:_.value;u?Ss(MA)&&m3(MA,p):Ss(MA)?MA.includes(p)||MA.push(p):mA?(F[_]=[p],aA(_)&&(j[_]=F[_])):(_.value=[p],t.k&&(F[t.k]=_.value))}else mA?(F[_]=y,aA(_)&&(j[_]=y)):IA&&(_.value=y,t.k&&(F[t.k]=y))};y?(tA.id=-1,aE(tA,r)):tA()}}}lY().requestIdleCallback;lY().cancelIdleCallback;const M_=t=>!!t.type.__asyncLoader,dY=t=>t.type.__isKeepAlive;function boA(t,i){HZ(t,"a",i)}function koA(t,i){HZ(t,"da",i)}function HZ(t,i,r=bI){const l=t.__wdc||(t.__wdc=()=>{let u=r;for(;u;){if(u.isDeactivated)return;u=u.parent}return t()});if(CY(i,l,r),r){let u=r.parent;for(;u&&u.parent;)dY(u.parent.vnode)&&LoA(l,i,r,u),u=u.parent}}function LoA(t,i,r,l){const u=CY(i,t,l,!0);qg(()=>{m3(l[i],u)},r)}function CY(t,i,r=bI,l=!1){if(r){const u=r[t]||(r[t]=[]),p=i.__weh||(i.__weh=(...y)=>{Vy();const w=AU(r),_=Zh(i,r,t,y);return w(),Jy(),_});return l?u.unshift(p):u.push(p),p}}const rm=t=>(i,r=bI)=>{(!xL||t==="sp")&&CY(t,(...l)=>i(...l),r)},UoA=rm("bm"),Cc=rm("m"),FoA=rm("bu"),OoA=rm("u"),qZ=rm("bum"),qg=rm("um"),PoA=rm("sp"),xoA=rm("rtg"),YoA=rm("rtc");function VoA(t,i=bI){CY("ec",t,i)}const JoA="components";function HoA(t,i){return KoA(JoA,t,!0,i)||t}const qoA=Symbol.for("v-ndc");function KoA(t,i,r=!0,l=!1){const u=Zl||bI;if(u){const p=u.type;{const w=GsA(p,!1);if(w&&(w===i||w===KC(i)||w===cY(KC(i))))return p}const y=nz(u[t]||p[t],i)||nz(u.appContext[t],i);return!y&&l?p:y}}function nz(t,i){return t&&(t[i]||t[KC(i)]||t[cY(KC(i))])}function zd(t,i,r,l){let u;const p=r,y=Ss(t);if(y||mg(t)){const w=y&&D_(t);let _=!1;w&&(_=!JC(t),t=IY(t)),u=new Array(t.length);for(let k=0,F=t.length;ki(w,_,void 0,p));else{const w=Object.keys(t);u=new Array(w.length);for(let _=0,k=w.length;_PL(i)?!(i.type===lE||i.type===Kr&&!KZ(i.children)):!0)?t:null}const Nj=t=>t?I6(t)?QY(t):Nj(t.parent):null,QL=$l(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=>Nj(t.parent),$root:t=>Nj(t.root),$host:t=>t.ce,$emit:t=>t.emit,$options:t=>WZ(t),$forceUpdate:t=>t.f||(t.f=()=>{_3(t.update)}),$nextTick:t=>t.n||(t.n=$L.bind(t.proxy)),$watch:t=>EsA.bind(t)}),UK=(t,i)=>t!==fa&&!t.__isScriptSetup&&qr(t,i),joA={get({_:t},i){if(i==="__v_skip")return!0;const{ctx:r,setupState:l,data:u,props:p,accessCache:y,type:w,appContext:_}=t;let k;if(i[0]!=="$"){const aA=y[i];if(aA!==void 0)switch(aA){case 1:return l[i];case 2:return u[i];case 4:return r[i];case 3:return p[i]}else{if(UK(l,i))return y[i]=1,l[i];if(u!==fa&&qr(u,i))return y[i]=2,u[i];if((k=t.propsOptions[0])&&qr(k,i))return y[i]=3,p[i];if(r!==fa&&qr(r,i))return y[i]=4,r[i];Gj&&(y[i]=0)}}const F=QL[i];let j,lA;if(F)return i==="$attrs"&&lu(t.attrs,"get",""),F(t);if((j=w.__cssModules)&&(j=j[i]))return j;if(r!==fa&&qr(r,i))return y[i]=4,r[i];if(lA=_.config.globalProperties,qr(lA,i))return lA[i]},set({_:t},i,r){const{data:l,setupState:u,ctx:p}=t;return UK(u,i)?(u[i]=r,!0):l!==fa&&qr(l,i)?(l[i]=r,!0):qr(t.props,i)||i[0]==="$"&&i.slice(1)in t?!1:(p[i]=r,!0)},has({_:{data:t,setupState:i,accessCache:r,ctx:l,appContext:u,propsOptions:p}},y){let w;return!!r[y]||t!==fa&&qr(t,y)||UK(i,y)||(w=p[0])&&qr(w,y)||qr(l,y)||qr(QL,y)||qr(u.config.globalProperties,y)},defineProperty(t,i,r){return r.get!=null?t._.accessCache[i]=0:qr(r,"value")&&this.set(t,i,r.value,null),Reflect.defineProperty(t,i,r)}};function rz(t){return Ss(t)?t.reduce((i,r)=>(i[r]=null,i),{}):t}let Gj=!0;function WoA(t){const i=WZ(t),r=t.proxy,l=t.ctx;Gj=!1,i.beforeCreate&&az(i.beforeCreate,t,"bc");const{data:u,computed:p,methods:y,watch:w,provide:_,inject:k,created:F,beforeMount:j,mounted:lA,beforeUpdate:aA,updated:mA,activated:IA,deactivated:tA,beforeDestroy:MA,beforeUnmount:PA,destroyed:ge,unmounted:de,render:Ve,renderTracked:Be,renderTriggered:ct,errorCaptured:mt,serverPrefetch:Ke,expose:Dt,inheritAttrs:qt,components:It,directives:re,filters:qe}=i;if(k&&zoA(k,l,null),y)for(const Vt in y){const gi=y[Vt];Xs(gi)&&(l[Vt]=gi.bind(r))}if(u){const Vt=u.call(r,r);Ta(Vt)&&(t.data=WM(Vt))}if(Gj=!0,p)for(const Vt in p){const gi=p[Vt],Fi=Xs(gi)?gi.bind(r,r):Xs(gi.get)?gi.get.bind(r,r):CQ,_o=!Xs(gi)&&Xs(gi.set)?gi.set.bind(r):CQ,to=Lt({get:Fi,set:_o});Object.defineProperty(l,Vt,{enumerable:!0,configurable:!0,get:()=>to.value,set:uo=>to.value=uo})}if(w)for(const Vt in w)jZ(w[Vt],l,r,Vt);if(_){const Vt=Xs(_)?_.call(r):_;Reflect.ownKeys(Vt).forEach(gi=>{XE(gi,Vt[gi])})}F&&az(F,t,"c");function si(Vt,gi){Ss(gi)?gi.forEach(Fi=>Vt(Fi.bind(r))):gi&&Vt(gi.bind(r))}if(si(UoA,j),si(Cc,lA),si(FoA,aA),si(OoA,mA),si(boA,IA),si(koA,tA),si(VoA,mt),si(YoA,Be),si(xoA,ct),si(qZ,PA),si(qg,de),si(PoA,Ke),Ss(Dt))if(Dt.length){const Vt=t.exposed||(t.exposed={});Dt.forEach(gi=>{Object.defineProperty(Vt,gi,{get:()=>r[gi],set:Fi=>r[gi]=Fi})})}else t.exposed||(t.exposed={});Ve&&t.render===CQ&&(t.render=Ve),qt!=null&&(t.inheritAttrs=qt),It&&(t.components=It),re&&(t.directives=re),Ke&&JZ(t)}function zoA(t,i,r=CQ){Ss(t)&&(t=bj(t));for(const l in t){const u=t[l];let p;Ta(u)?"default"in u?p=kI(u.from||l,u.default,!0):p=kI(u.from||l):p=kI(u),Xl(p)?Object.defineProperty(i,l,{enumerable:!0,configurable:!0,get:()=>p.value,set:y=>p.value=y}):i[l]=p}}function az(t,i,r){Zh(Ss(t)?t.map(l=>l.bind(i.proxy)):t.bind(i.proxy),i,r)}function jZ(t,i,r,l){let u=l.includes(".")?r6(r,l):()=>r[l];if(mg(t)){const p=i[t];Xs(p)&&ia(u,p)}else if(Xs(t))ia(u,t.bind(r));else if(Ta(t))if(Ss(t))t.forEach(p=>jZ(p,i,r,l));else{const p=Xs(t.handler)?t.handler.bind(r):i[t.handler];Xs(p)&&ia(u,p,t)}}function WZ(t){const i=t.type,{mixins:r,extends:l}=i,{mixins:u,optionsCache:p,config:{optionMergeStrategies:y}}=t.appContext,w=p.get(i);let _;return w?_=w:!u.length&&!r&&!l?_=i:(_={},u.length&&u.forEach(k=>L1(_,k,y,!0)),L1(_,i,y)),Ta(i)&&p.set(i,_),_}function L1(t,i,r,l=!1){const{mixins:u,extends:p}=i;p&&L1(t,p,r,!0),u&&u.forEach(y=>L1(t,y,r,!0));for(const y in i)if(!(l&&y==="expose")){const w=ZoA[y]||r&&r[y];t[y]=w?w(t[y],i[y]):i[y]}return t}const ZoA={data:gz,props:cz,emits:cz,methods:Zk,computed:Zk,beforeCreate:sE,created:sE,beforeMount:sE,mounted:sE,beforeUpdate:sE,updated:sE,beforeDestroy:sE,beforeUnmount:sE,destroyed:sE,unmounted:sE,activated:sE,deactivated:sE,errorCaptured:sE,serverPrefetch:sE,components:Zk,directives:Zk,watch:$oA,provide:gz,inject:XoA};function gz(t,i){return i?t?function(){return $l(Xs(t)?t.call(this,this):t,Xs(i)?i.call(this,this):i)}:i:t}function XoA(t,i){return Zk(bj(t),bj(i))}function bj(t){if(Ss(t)){const i={};for(let r=0;r1)return r&&Xs(i)?i.call(l&&l.proxy):i}}const ZZ={},XZ=()=>Object.create(ZZ),$Z=t=>Object.getPrototypeOf(t)===ZZ;function tsA(t,i,r,l=!1){const u={},p=XZ();t.propsDefaults=Object.create(null),A6(t,i,u,p);for(const y in t.propsOptions[0])y in u||(u[y]=void 0);r?t.props=l?u:doA(u):t.type.props?t.props=u:t.props=p,t.attrs=p}function isA(t,i,r,l){const{props:u,attrs:p,vnode:{patchFlag:y}}=t,w=Tr(u),[_]=t.propsOptions;let k=!1;if((l||y>0)&&!(y&16)){if(y&8){const F=t.vnode.dynamicProps;for(let j=0;j{_=!0;const[lA,aA]=e6(j,i,!0);$l(y,lA),aA&&w.push(...aA)};!r&&i.mixins.length&&i.mixins.forEach(F),t.extends&&F(t.extends),t.mixins&&t.mixins.forEach(F)}if(!p&&!_)return Ta(t)&&l.set(t,f_),f_;if(Ss(p))for(let F=0;Ft[0]==="_"||t==="$stable",T3=t=>Ss(t)?t.map(IQ):[IQ(t)],ssA=(t,i,r)=>{if(i._n)return i;const l=Li((...u)=>T3(i(...u)),r);return l._c=!1,l},i6=(t,i,r)=>{const l=t._ctx;for(const u in t){if(t6(u))continue;const p=t[u];if(Xs(p))i[u]=ssA(u,p,l);else if(p!=null){const y=T3(p);i[u]=()=>y}}},o6=(t,i)=>{const r=T3(i);t.slots.default=()=>r},s6=(t,i,r)=>{for(const l in i)(r||l!=="_")&&(t[l]=i[l])},nsA=(t,i,r)=>{const l=t.slots=XZ();if(t.vnode.shapeFlag&32){const u=i._;u?(s6(l,i,r),r&&lZ(l,"_",u,!0)):i6(i,l)}else i&&o6(t,i)},rsA=(t,i,r)=>{const{vnode:l,slots:u}=t;let p=!0,y=fa;if(l.shapeFlag&32){const w=i._;w?r&&w===1?p=!1:s6(u,i,r):(p=!i.$stable,i6(i,u)),y=i}else i&&(o6(t,i),y={default:1});if(p)for(const w in u)!t6(w)&&y[w]==null&&delete u[w]},aE=msA;function asA(t){return gsA(t)}function gsA(t,i){const r=lY();r.__VUE__=!0;const{insert:l,remove:u,patchProp:p,createElement:y,createText:w,createComment:_,setText:k,setElementText:F,parentNode:j,nextSibling:lA,setScopeId:aA=CQ,insertStaticContent:mA}=t,IA=(qA,ce,Pe,kt=null,it=null,gt=null,Xt=void 0,$t=null,Ge=!!ce.dynamicChildren)=>{if(qA===ce)return;qA&&!JM(qA,ce)&&(kt=$i(qA),uo(qA,it,gt,!0),qA=null),ce.patchFlag===-2&&(Ge=!1,ce.dynamicChildren=null);const{type:je,ref:Mt,shapeFlag:Rt}=ce;switch(je){case BY:tA(qA,ce,Pe,kt);break;case lE:MA(qA,ce,Pe,kt);break;case OK:qA==null&&PA(ce,Pe,kt,Xt);break;case Kr:It(qA,ce,Pe,kt,it,gt,Xt,$t,Ge);break;default:Rt&1?Ve(qA,ce,Pe,kt,it,gt,Xt,$t,Ge):Rt&6?re(qA,ce,Pe,kt,it,gt,Xt,$t,Ge):(Rt&64||Rt&128)&&je.process(qA,ce,Pe,kt,it,gt,Xt,$t,Ge,bi)}Mt!=null&&it&&k1(Mt,qA&&qA.ref,gt,ce||qA,!ce)},tA=(qA,ce,Pe,kt)=>{if(qA==null)l(ce.el=w(ce.children),Pe,kt);else{const it=ce.el=qA.el;ce.children!==qA.children&&k(it,ce.children)}},MA=(qA,ce,Pe,kt)=>{qA==null?l(ce.el=_(ce.children||""),Pe,kt):ce.el=qA.el},PA=(qA,ce,Pe,kt)=>{[qA.el,qA.anchor]=mA(qA.children,ce,Pe,kt,qA.el,qA.anchor)},ge=({el:qA,anchor:ce},Pe,kt)=>{let it;for(;qA&&qA!==ce;)it=lA(qA),l(qA,Pe,kt),qA=it;l(ce,Pe,kt)},de=({el:qA,anchor:ce})=>{let Pe;for(;qA&&qA!==ce;)Pe=lA(qA),u(qA),qA=Pe;u(ce)},Ve=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{ce.type==="svg"?Xt="svg":ce.type==="math"&&(Xt="mathml"),qA==null?Be(ce,Pe,kt,it,gt,Xt,$t,Ge):Ke(qA,ce,it,gt,Xt,$t,Ge)},Be=(qA,ce,Pe,kt,it,gt,Xt,$t)=>{let Ge,je;const{props:Mt,shapeFlag:Rt,transition:Oi,dirs:Qo}=qA;if(Ge=qA.el=y(qA.type,gt,Mt&&Mt.is,Mt),Rt&8?F(Ge,qA.children):Rt&16&&mt(qA.children,Ge,null,kt,it,FK(qA,gt),Xt,$t),Qo&&LM(qA,null,kt,"created"),ct(Ge,qA,qA.scopeId,Xt,kt),Mt){for(const oo in Mt)oo!=="value"&&!dL(oo)&&p(Ge,oo,null,Mt[oo],gt,kt);"value"in Mt&&p(Ge,"value",null,Mt.value,gt),(je=Mt.onVnodeBeforeMount)&&aQ(je,kt,qA)}Qo&&LM(qA,null,kt,"beforeMount");const To=csA(it,Oi);To&&Oi.beforeEnter(Ge),l(Ge,ce,Pe),((je=Mt&&Mt.onVnodeMounted)||To||Qo)&&aE(()=>{je&&aQ(je,kt,qA),To&&Oi.enter(Ge),Qo&&LM(qA,null,kt,"mounted")},it)},ct=(qA,ce,Pe,kt,it)=>{if(Pe&&aA(qA,Pe),kt)for(let gt=0;gt{for(let je=Ge;je{const $t=ce.el=qA.el;let{patchFlag:Ge,dynamicChildren:je,dirs:Mt}=ce;Ge|=qA.patchFlag&16;const Rt=qA.props||fa,Oi=ce.props||fa;let Qo;if(Pe&&UM(Pe,!1),(Qo=Oi.onVnodeBeforeUpdate)&&aQ(Qo,Pe,ce,qA),Mt&&LM(ce,qA,Pe,"beforeUpdate"),Pe&&UM(Pe,!0),(Rt.innerHTML&&Oi.innerHTML==null||Rt.textContent&&Oi.textContent==null)&&F($t,""),je?Dt(qA.dynamicChildren,je,$t,Pe,kt,FK(ce,it),gt):Xt||gi(qA,ce,$t,null,Pe,kt,FK(ce,it),gt,!1),Ge>0){if(Ge&16)qt($t,Rt,Oi,Pe,it);else if(Ge&2&&Rt.class!==Oi.class&&p($t,"class",null,Oi.class,it),Ge&4&&p($t,"style",Rt.style,Oi.style,it),Ge&8){const To=ce.dynamicProps;for(let oo=0;oo{Qo&&aQ(Qo,Pe,ce,qA),Mt&&LM(ce,qA,Pe,"updated")},kt)},Dt=(qA,ce,Pe,kt,it,gt,Xt)=>{for(let $t=0;$t{if(ce!==Pe){if(ce!==fa)for(const gt in ce)!dL(gt)&&!(gt in Pe)&&p(qA,gt,ce[gt],null,it,kt);for(const gt in Pe){if(dL(gt))continue;const Xt=Pe[gt],$t=ce[gt];Xt!==$t&>!=="value"&&p(qA,gt,$t,Xt,it,kt)}"value"in Pe&&p(qA,"value",ce.value,Pe.value,it)}},It=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{const je=ce.el=qA?qA.el:w(""),Mt=ce.anchor=qA?qA.anchor:w("");let{patchFlag:Rt,dynamicChildren:Oi,slotScopeIds:Qo}=ce;Qo&&($t=$t?$t.concat(Qo):Qo),qA==null?(l(je,Pe,kt),l(Mt,Pe,kt),mt(ce.children||[],Pe,Mt,it,gt,Xt,$t,Ge)):Rt>0&&Rt&64&&Oi&&qA.dynamicChildren?(Dt(qA.dynamicChildren,Oi,Pe,it,gt,Xt,$t),(ce.key!=null||it&&ce===it.subTree)&&N3(qA,ce,!0)):gi(qA,ce,Pe,Mt,it,gt,Xt,$t,Ge)},re=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{ce.slotScopeIds=$t,qA==null?ce.shapeFlag&512?it.ctx.activate(ce,Pe,kt,Xt,Ge):qe(ce,Pe,kt,it,gt,Xt,Ge):ft(qA,ce,Ge)},qe=(qA,ce,Pe,kt,it,gt,Xt)=>{const $t=qA.component=vsA(qA,kt,it);if(dY(qA)&&($t.ctx.renderer=bi),wsA($t,!1,Xt),$t.asyncDep){if(it&&it.registerDep($t,si,Xt),!qA.el){const Ge=$t.subTree=Nt(lE);MA(null,Ge,ce,Pe)}}else si($t,qA,ce,Pe,it,gt,Xt)},ft=(qA,ce,Pe)=>{const kt=ce.component=qA.component;if(QsA(qA,ce,Pe))if(kt.asyncDep&&!kt.asyncResolved){Vt(kt,ce,Pe);return}else kt.next=ce,kt.update();else ce.el=qA.el,kt.vnode=ce},si=(qA,ce,Pe,kt,it,gt,Xt)=>{const $t=()=>{if(qA.isMounted){let{next:Rt,bu:Oi,u:Qo,parent:To,vnode:oo}=qA;{const an=n6(qA);if(an){Rt&&(Rt.el=oo.el,Vt(qA,Rt,Xt)),an.asyncDep.then(()=>{qA.isUnmounted||$t()});return}}let No=Rt,$s;UM(qA,!1),Rt?(Rt.el=oo.el,Vt(qA,Rt,Xt)):Rt=oo,Oi&&u1(Oi),($s=Rt.props&&Rt.props.onVnodeBeforeUpdate)&&aQ($s,To,Rt,oo),UM(qA,!0);const rn=uz(qA),us=qA.subTree;qA.subTree=rn,IA(us,rn,j(us.el),$i(us),qA,it,gt),Rt.el=rn.el,No===null&&psA(qA,rn.el),Qo&&aE(Qo,it),($s=Rt.props&&Rt.props.onVnodeUpdated)&&aE(()=>aQ($s,To,Rt,oo),it)}else{let Rt;const{el:Oi,props:Qo}=ce,{bm:To,m:oo,parent:No,root:$s,type:rn}=qA,us=M_(ce);UM(qA,!1),To&&u1(To),!us&&(Rt=Qo&&Qo.onVnodeBeforeMount)&&aQ(Rt,No,ce),UM(qA,!0);{$s.ce&&$s.ce._injectChildStyle(rn);const an=qA.subTree=uz(qA);IA(null,an,Pe,kt,qA,it,gt),ce.el=an.el}if(oo&&aE(oo,it),!us&&(Rt=Qo&&Qo.onVnodeMounted)){const an=ce;aE(()=>aQ(Rt,No,an),it)}(ce.shapeFlag&256||No&&M_(No.vnode)&&No.vnode.shapeFlag&256)&&qA.a&&aE(qA.a,it),qA.isMounted=!0,ce=Pe=kt=null}};qA.scope.on();const Ge=qA.effect=new dZ($t);qA.scope.off();const je=qA.update=Ge.run.bind(Ge),Mt=qA.job=Ge.runIfDirty.bind(Ge);Mt.i=qA,Mt.id=qA.uid,Ge.scheduler=()=>_3(Mt),UM(qA,!0),je()},Vt=(qA,ce,Pe)=>{ce.component=qA;const kt=qA.vnode.props;qA.vnode=ce,qA.next=null,isA(qA,ce.props,kt,Pe),rsA(qA,ce.children,Pe),Vy(),ez(qA),Jy()},gi=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge=!1)=>{const je=qA&&qA.children,Mt=qA?qA.shapeFlag:0,Rt=ce.children,{patchFlag:Oi,shapeFlag:Qo}=ce;if(Oi>0){if(Oi&128){_o(je,Rt,Pe,kt,it,gt,Xt,$t,Ge);return}else if(Oi&256){Fi(je,Rt,Pe,kt,it,gt,Xt,$t,Ge);return}}Qo&8?(Mt&16&&Ko(je,it,gt),Rt!==je&&F(Pe,Rt)):Mt&16?Qo&16?_o(je,Rt,Pe,kt,it,gt,Xt,$t,Ge):Ko(je,it,gt,!0):(Mt&8&&F(Pe,""),Qo&16&&mt(Rt,Pe,kt,it,gt,Xt,$t,Ge))},Fi=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{qA=qA||f_,ce=ce||f_;const je=qA.length,Mt=ce.length,Rt=Math.min(je,Mt);let Oi;for(Oi=0;OiMt?Ko(qA,it,gt,!0,!1,Rt):mt(ce,Pe,kt,it,gt,Xt,$t,Ge,Rt)},_o=(qA,ce,Pe,kt,it,gt,Xt,$t,Ge)=>{let je=0;const Mt=ce.length;let Rt=qA.length-1,Oi=Mt-1;for(;je<=Rt&&je<=Oi;){const Qo=qA[je],To=ce[je]=Ge?vy(ce[je]):IQ(ce[je]);if(JM(Qo,To))IA(Qo,To,Pe,null,it,gt,Xt,$t,Ge);else break;je++}for(;je<=Rt&&je<=Oi;){const Qo=qA[Rt],To=ce[Oi]=Ge?vy(ce[Oi]):IQ(ce[Oi]);if(JM(Qo,To))IA(Qo,To,Pe,null,it,gt,Xt,$t,Ge);else break;Rt--,Oi--}if(je>Rt){if(je<=Oi){const Qo=Oi+1,To=QoOi)for(;je<=Rt;)uo(qA[je],it,gt,!0),je++;else{const Qo=je,To=je,oo=new Map;for(je=To;je<=Oi;je++){const Jn=ce[je]=Ge?vy(ce[je]):IQ(ce[je]);Jn.key!=null&&oo.set(Jn.key,je)}let No,$s=0;const rn=Oi-To+1;let us=!1,an=0;const yo=new Array(rn);for(je=0;je=rn){uo(Jn,it,gt,!0);continue}let Br;if(Jn.key!=null)Br=oo.get(Jn.key);else for(No=To;No<=Oi;No++)if(yo[No-To]===0&&JM(Jn,ce[No])){Br=No;break}Br===void 0?uo(Jn,it,gt,!0):(yo[Br-To]=je+1,Br>=an?an=Br:us=!0,IA(Jn,ce[Br],Pe,null,it,gt,Xt,$t,Ge),$s++)}const pA=us?lsA(yo):f_;for(No=pA.length-1,je=rn-1;je>=0;je--){const Jn=To+je,Br=ce[Jn],Es=Jn+1{const{el:gt,type:Xt,transition:$t,children:Ge,shapeFlag:je}=qA;if(je&6){to(qA.component.subTree,ce,Pe,kt);return}if(je&128){qA.suspense.move(ce,Pe,kt);return}if(je&64){Xt.move(qA,ce,Pe,bi);return}if(Xt===Kr){l(gt,ce,Pe);for(let Rt=0;Rt$t.enter(gt),it);else{const{leave:Rt,delayLeave:Oi,afterLeave:Qo}=$t,To=()=>l(gt,ce,Pe),oo=()=>{Rt(gt,()=>{To(),Qo&&Qo()})};Oi?Oi(gt,To,oo):oo()}else l(gt,ce,Pe)},uo=(qA,ce,Pe,kt=!1,it=!1)=>{const{type:gt,props:Xt,ref:$t,children:Ge,dynamicChildren:je,shapeFlag:Mt,patchFlag:Rt,dirs:Oi,cacheIndex:Qo}=qA;if(Rt===-2&&(it=!1),$t!=null&&k1($t,null,Pe,qA,!0),Qo!=null&&(ce.renderCache[Qo]=void 0),Mt&256){ce.ctx.deactivate(qA);return}const To=Mt&1&&Oi,oo=!M_(qA);let No;if(oo&&(No=Xt&&Xt.onVnodeBeforeUnmount)&&aQ(No,ce,qA),Mt&6)os(qA.component,Pe,kt);else{if(Mt&128){qA.suspense.unmount(Pe,kt);return}To&&LM(qA,null,ce,"beforeUnmount"),Mt&64?qA.type.remove(qA,ce,Pe,bi,kt):je&&!je.hasOnce&&(gt!==Kr||Rt>0&&Rt&64)?Ko(je,ce,Pe,!1,!0):(gt===Kr&&Rt&384||!it&&Mt&16)&&Ko(Ge,ce,Pe),kt&&Ys(qA)}(oo&&(No=Xt&&Xt.onVnodeUnmounted)||To)&&aE(()=>{No&&aQ(No,ce,qA),To&&LM(qA,null,ce,"unmounted")},Pe)},Ys=qA=>{const{type:ce,el:Pe,anchor:kt,transition:it}=qA;if(ce===Kr){ki(Pe,kt);return}if(ce===OK){de(qA);return}const gt=()=>{u(Pe),it&&!it.persisted&&it.afterLeave&&it.afterLeave()};if(qA.shapeFlag&1&&it&&!it.persisted){const{leave:Xt,delayLeave:$t}=it,Ge=()=>Xt(Pe,gt);$t?$t(qA.el,gt,Ge):Ge()}else gt()},ki=(qA,ce)=>{let Pe;for(;qA!==ce;)Pe=lA(qA),u(qA),qA=Pe;u(ce)},os=(qA,ce,Pe)=>{const{bum:kt,scope:it,job:gt,subTree:Xt,um:$t,m:Ge,a:je}=qA;Iz(Ge),Iz(je),kt&&u1(kt),it.stop(),gt&&(gt.flags|=8,uo(Xt,qA,ce,Pe)),$t&&aE($t,ce),aE(()=>{qA.isUnmounted=!0},ce),ce&&ce.pendingBranch&&!ce.isUnmounted&&qA.asyncDep&&!qA.asyncResolved&&qA.suspenseId===ce.pendingId&&(ce.deps--,ce.deps===0&&ce.resolve())},Ko=(qA,ce,Pe,kt=!1,it=!1,gt=0)=>{for(let Xt=gt;Xt{if(qA.shapeFlag&6)return $i(qA.component.subTree);if(qA.shapeFlag&128)return qA.suspense.next();const ce=lA(qA.anchor||qA.el),Pe=ce&&ce[kZ];return Pe?lA(Pe):ce};let jt=!1;const io=(qA,ce,Pe)=>{qA==null?ce._vnode&&uo(ce._vnode,null,null,!0):IA(ce._vnode||null,qA,ce,null,null,null,Pe),ce._vnode=qA,jt||(jt=!0,ez(),GZ(),jt=!1)},bi={p:IA,um:uo,m:to,r:Ys,mt:qe,mc:mt,pc:gi,pbc:Dt,n:$i,o:t};return{render:io,hydrate:void 0,createApp:esA(io)}}function FK({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 UM({effect:t,job:i},r){r?(t.flags|=32,i.flags|=4):(t.flags&=-33,i.flags&=-5)}function csA(t,i){return(!t||t&&!t.pendingBranch)&&i&&!i.persisted}function N3(t,i,r=!1){const l=t.children,u=i.children;if(Ss(l)&&Ss(u))for(let p=0;p>1,t[r[w]]0&&(i[l]=r[p-1]),r[p]=l)}}for(p=r.length,y=r[p-1];p-- >0;)r[p]=y,y=i[y];return r}function n6(t){const i=t.subTree.component;if(i)return i.asyncDep&&!i.asyncResolved?i:n6(i)}function Iz(t){if(t)for(let i=0;ikI(IsA);function F_(t,i){return G3(t,null,i)}function ia(t,i,r){return G3(t,i,r)}function G3(t,i,r=fa){const{immediate:l,deep:u,flush:p,once:y}=r,w=$l({},r),_=i&&l||!i&&p!=="post";let k;if(xL){if(p==="sync"){const aA=usA();k=aA.__watcherHandles||(aA.__watcherHandles=[])}else if(!_){const aA=()=>{};return aA.stop=CQ,aA.resume=CQ,aA.pause=CQ,aA}}const F=bI;w.call=(aA,mA,IA)=>Zh(aA,F,mA,IA);let j=!1;p==="post"?w.scheduler=aA=>{aE(aA,F&&F.suspense)}:p!=="sync"&&(j=!0,w.scheduler=(aA,mA)=>{mA?aA():_3(aA)}),w.augmentJob=aA=>{i&&(aA.flags|=4),j&&(aA.flags|=2,F&&(aA.id=F.uid,aA.i=F))};const lA=SoA(t,i,w);return xL&&(k?k.push(lA):_&&lA()),lA}function EsA(t,i,r){const l=this.proxy,u=mg(t)?t.includes(".")?r6(l,t):()=>l[t]:t.bind(l,l);let p;Xs(i)?p=i:(p=i.handler,r=i);const y=AU(this),w=G3(u,p.bind(l),r);return y(),w}function r6(t,i){const r=i.split(".");return()=>{let l=t;for(let u=0;ui==="modelValue"||i==="model-value"?t.modelModifiers:t[`${i}Modifiers`]||t[`${KC(i)}Modifiers`]||t[`${Yy(i)}Modifiers`];function CsA(t,i,...r){if(t.isUnmounted)return;const l=t.vnode.props||fa;let u=r;const p=i.startsWith("update:"),y=p&&dsA(l,i.slice(7));y&&(y.trim&&(u=r.map(F=>mg(F)?F.trim():F)),y.number&&(u=r.map(Sj)));let w,_=l[w=_K(i)]||l[w=_K(KC(i))];!_&&p&&(_=l[w=_K(Yy(i))]),_&&Zh(_,t,6,u);const k=l[w+"Once"];if(k){if(!t.emitted)t.emitted={};else if(t.emitted[w])return;t.emitted[w]=!0,Zh(k,t,6,u)}}function a6(t,i,r=!1){const l=i.emitsCache,u=l.get(t);if(u!==void 0)return u;const p=t.emits;let y={},w=!1;if(!Xs(t)){const _=k=>{const F=a6(k,i,!0);F&&(w=!0,$l(y,F))};!r&&i.mixins.length&&i.mixins.forEach(_),t.extends&&_(t.extends),t.mixins&&t.mixins.forEach(_)}return!p&&!w?(Ta(t)&&l.set(t,null),null):(Ss(p)?p.forEach(_=>y[_]=null):$l(y,p),Ta(t)&&l.set(t,y),y)}function hY(t,i){return!t||!rY(i)?!1:(i=i.slice(2).replace(/Once$/,""),qr(t,i[0].toLowerCase()+i.slice(1))||qr(t,Yy(i))||qr(t,i))}function uz(t){const{type:i,vnode:r,proxy:l,withProxy:u,propsOptions:[p],slots:y,attrs:w,emit:_,render:k,renderCache:F,props:j,data:lA,setupState:aA,ctx:mA,inheritAttrs:IA}=t,tA=b1(t);let MA,PA;try{if(r.shapeFlag&4){const de=u||l,Ve=de;MA=IQ(k.call(Ve,de,F,j,aA,lA,mA)),PA=w}else{const de=i;MA=IQ(de.length>1?de(j,{attrs:w,slots:y,emit:_}):de(j,null)),PA=i.props?w:hsA(w)}}catch(de){pL.length=0,uY(de,t,1),MA=Nt(lE)}let ge=MA;if(PA&&IA!==!1){const de=Object.keys(PA),{shapeFlag:Ve}=ge;de.length&&Ve&7&&(p&&de.some(p3)&&(PA=BsA(PA,p)),ge=Uy(ge,PA,!1,!0))}return r.dirs&&(ge=Uy(ge,null,!1,!0),ge.dirs=ge.dirs?ge.dirs.concat(r.dirs):r.dirs),r.transition&&FL(ge,r.transition),MA=ge,b1(tA),MA}const hsA=t=>{let i;for(const r in t)(r==="class"||r==="style"||rY(r))&&((i||(i={}))[r]=t[r]);return i},BsA=(t,i)=>{const r={};for(const l in t)(!p3(l)||!(l.slice(9)in i))&&(r[l]=t[l]);return r};function QsA(t,i,r){const{props:l,children:u,component:p}=t,{props:y,children:w,patchFlag:_}=i,k=p.emitsOptions;if(i.dirs||i.transition)return!0;if(r&&_>=0){if(_&1024)return!0;if(_&16)return l?Ez(l,y,k):!!y;if(_&8){const F=i.dynamicProps;for(let j=0;jt.__isSuspense;function msA(t,i){i&&i.pendingBranch?Ss(t)?i.effects.push(...t):i.effects.push(t):RoA(t)}const Kr=Symbol.for("v-fgt"),BY=Symbol.for("v-txt"),lE=Symbol.for("v-cmt"),OK=Symbol.for("v-stc"),pL=[];let qd=null;function ae(t=!1){pL.push(qd=t?null:[])}function fsA(){pL.pop(),qd=pL[pL.length-1]||null}let OL=1;function dz(t,i=!1){OL+=t,t<0&&qd&&i&&(qd.hasOnce=!0)}function c6(t){return t.dynamicChildren=OL>0?qd||f_:null,fsA(),OL>0&&qd&&qd.push(t),t}function rt(t,i,r,l,u,p){return c6(Re(t,i,r,l,u,p,!0))}function Bi(t,i,r,l,u){return c6(Nt(t,i,r,l,u,!0))}function PL(t){return t?t.__v_isVNode===!0:!1}function JM(t,i){return t.type===i.type&&t.key===i.key}const l6=({key:t})=>t??null,d1=({ref:t,ref_key:i,ref_for:r})=>(typeof t=="number"&&(t=""+t),t!=null?mg(t)||Xl(t)||Xs(t)?{i:Zl,r:t,k:i,f:!!r}:t:null);function Re(t,i=null,r=null,l=0,u=null,p=t===Kr?0:1,y=!1,w=!1){const _={__v_isVNode:!0,__v_skip:!0,type:t,props:i,key:i&&l6(i),ref:i&&d1(i),scopeId:EY,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:p,patchFlag:l,dynamicProps:u,dynamicChildren:null,appContext:null,ctx:Zl};return w?(b3(_,r),p&128&&t.normalize(_)):r&&(_.shapeFlag|=mg(r)?8:16),OL>0&&!y&&qd&&(_.patchFlag>0||p&6)&&_.patchFlag!==32&&qd.push(_),_}const Nt=ysA;function ysA(t,i=null,r=null,l=0,u=null,p=!1){if((!t||t===qoA)&&(t=lE),PL(t)){const w=Uy(t,i,!0);return r&&b3(w,r),OL>0&&!p&&qd&&(w.shapeFlag&6?qd[qd.indexOf(t)]=w:qd.push(w)),w.patchFlag=-2,w}if(bsA(t)&&(t=t.__vccOpts),i){i=DsA(i);let{class:w,style:_}=i;w&&!mg(w)&&(i.class=Xi(w)),Ta(_)&&(w3(_)&&!Ss(_)&&(_=$l({},_)),i.style=hr(_))}const y=mg(t)?1:g6(t)?128:LZ(t)?64:Ta(t)?4:Xs(t)?2:0;return Re(t,i,r,l,u,y,p,!0)}function DsA(t){return t?w3(t)||$Z(t)?$l({},t):t:null}function Uy(t,i,r=!1,l=!1){const{props:u,ref:p,patchFlag:y,children:w,transition:_}=t,k=i?Lj(u||{},i):u,F={__v_isVNode:!0,__v_skip:!0,type:t.type,props:k,key:k&&l6(k),ref:i&&i.ref?r&&p?Ss(p)?p.concat(d1(i)):[p,d1(i)]:d1(i):p,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!==Kr?y===-1?16:y|16:y,dynamicProps:t.dynamicProps,dynamicChildren:t.dynamicChildren,appContext:t.appContext,dirs:t.dirs,transition:_,component:t.component,suspense:t.suspense,ssContent:t.ssContent&&Uy(t.ssContent),ssFallback:t.ssFallback&&Uy(t.ssFallback),el:t.el,anchor:t.anchor,ctx:t.ctx,ce:t.ce};return _&&l&&FL(F,_.clone(F)),F}function _a(t=" ",i=0){return Nt(BY,null,t,i)}function ri(t="",i=!1){return i?(ae(),Bi(lE,null,t)):Nt(lE,null,t)}function IQ(t){return t==null||typeof t=="boolean"?Nt(lE):Ss(t)?Nt(Kr,null,t.slice()):PL(t)?vy(t):Nt(BY,null,String(t))}function vy(t){return t.el===null&&t.patchFlag!==-1||t.memo?t:Uy(t)}function b3(t,i){let r=0;const{shapeFlag:l}=t;if(i==null)i=null;else if(Ss(i))r=16;else if(typeof i=="object")if(l&65){const u=i.default;u&&(u._c&&(u._d=!1),b3(t,u()),u._c&&(u._d=!0));return}else{r=32;const u=i._;!u&&!$Z(i)?i._ctx=Zl:u===3&&Zl&&(Zl.slots._===1?i._=1:(i._=2,t.patchFlag|=1024))}else Xs(i)?(i={default:i,_ctx:Zl},r=32):(i=String(i),l&64?(r=16,i=[_a(i)]):r=8);t.children=i,t.shapeFlag|=r}function Lj(...t){const i={};for(let r=0;rbI||Zl;let U1,Uj;{const t=lY(),i=(r,l)=>{let u;return(u=t[r])||(u=t[r]=[]),u.push(l),p=>{u.length>1?u.forEach(y=>y(p)):u[0](p)}};U1=i("__VUE_INSTANCE_SETTERS__",r=>bI=r),Uj=i("__VUE_SSR_SETTERS__",r=>xL=r)}const AU=t=>{const i=bI;return U1(t),t.scope.on(),()=>{t.scope.off(),U1(i)}},Cz=()=>{bI&&bI.scope.off(),U1(null)};function I6(t){return t.vnode.shapeFlag&4}let xL=!1;function wsA(t,i=!1,r=!1){i&&Uj(i);const{props:l,children:u}=t.vnode,p=I6(t);tsA(t,l,p,i),nsA(t,u,r);const y=p?_sA(t,i):void 0;return i&&Uj(!1),y}function _sA(t,i){const r=t.type;t.accessCache=Object.create(null),t.proxy=new Proxy(t.ctx,joA);const{setup:l}=r;if(l){Vy();const u=t.setupContext=l.length>1?NsA(t):null,p=AU(t),y=XL(l,t,0,[t.props,u]),w=aZ(y);if(Jy(),p(),(w||t.sp)&&!M_(t)&&JZ(t),w){if(y.then(Cz,Cz),i)return y.then(_=>{hz(t,_)}).catch(_=>{uY(_,t,0)});t.asyncDep=y}else hz(t,y)}else u6(t)}function hz(t,i,r){Xs(i)?t.type.__ssrInlineRender?t.ssrRender=i:t.render=i:Ta(i)&&(t.setupState=wZ(i)),u6(t)}function u6(t,i,r){const l=t.type;t.render||(t.render=l.render||CQ);{const u=AU(t);Vy();try{WoA(t)}finally{Jy(),u()}}}const TsA={get(t,i){return lu(t,"get",""),t[i]}};function NsA(t){const i=r=>{t.exposed=r||{}};return{attrs:new Proxy(t.attrs,TsA),slots:t.slots,emit:t.emit,expose:i}}function QY(t){return t.exposed?t.exposeProxy||(t.exposeProxy=new Proxy(wZ(CoA(t.exposed)),{get(i,r){if(r in i)return i[r];if(r in QL)return QL[r](t)},has(i,r){return r in i||r in QL}})):t.proxy}function GsA(t,i=!0){return Xs(t)?t.displayName||t.name:t.name||i&&t.__name}function bsA(t){return Xs(t)&&"__vccOpts"in t}const Lt=(t,i)=>yoA(t,i,xL);function ksA(t,i,r){const l=arguments.length;return l===2?Ta(i)&&!Ss(i)?PL(i)?Nt(t,null,[i]):Nt(t,i):Nt(t,null,i):(l>3?r=Array.prototype.slice.call(arguments,2):l===3&&PL(r)&&(r=[r]),Nt(t,i,r))}const Fj="3.5.13";/** +* @vue/runtime-dom v3.5.13 +* (c) 2018-present Yuxi (Evan) You and Vue contributors +* @license MIT +**/let Oj;const Bz=typeof window<"u"&&window.trustedTypes;if(Bz)try{Oj=Bz.createPolicy("vue",{createHTML:t=>t})}catch{}const E6=Oj?t=>Oj.createHTML(t):t=>t,LsA="http://www.w3.org/2000/svg",UsA="http://www.w3.org/1998/Math/MathML",Xp=typeof document<"u"?document:null,Qz=Xp&&Xp.createElement("template"),FsA={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 u=i==="svg"?Xp.createElementNS(LsA,t):i==="mathml"?Xp.createElementNS(UsA,t):r?Xp.createElement(t,{is:r}):Xp.createElement(t);return t==="select"&&l&&l.multiple!=null&&u.setAttribute("multiple",l.multiple),u},createText:t=>Xp.createTextNode(t),createComment:t=>Xp.createComment(t),setText:(t,i)=>{t.nodeValue=i},setElementText:(t,i)=>{t.textContent=i},parentNode:t=>t.parentNode,nextSibling:t=>t.nextSibling,querySelector:t=>Xp.querySelector(t),setScopeId(t,i){t.setAttribute(i,"")},insertStaticContent(t,i,r,l,u,p){const y=r?r.previousSibling:i.lastChild;if(u&&(u===p||u.nextSibling))for(;i.insertBefore(u.cloneNode(!0),r),!(u===p||!(u=u.nextSibling)););else{Qz.innerHTML=E6(l==="svg"?`${t}`:l==="mathml"?`${t}`:t);const w=Qz.content;if(l==="svg"||l==="mathml"){const _=w.firstChild;for(;_.firstChild;)w.appendChild(_.firstChild);w.removeChild(_)}i.insertBefore(w,r)}return[y?y.nextSibling:i.firstChild,r?r.previousSibling:i.lastChild]}},Qy="transition",Jk="animation",YL=Symbol("_vtc"),d6={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},OsA=$l({},OZ,d6),PsA=t=>(t.displayName="Transition",t.props=OsA,t),xsA=PsA((t,{slots:i})=>ksA(GoA,YsA(t),i)),FM=(t,i=[])=>{Ss(t)?t.forEach(r=>r(...i)):t&&t(...i)},pz=t=>t?Ss(t)?t.some(i=>i.length>1):t.length>1:!1;function YsA(t){const i={};for(const It in t)It in d6||(i[It]=t[It]);if(t.css===!1)return i;const{name:r="v",type:l,duration:u,enterFromClass:p=`${r}-enter-from`,enterActiveClass:y=`${r}-enter-active`,enterToClass:w=`${r}-enter-to`,appearFromClass:_=p,appearActiveClass:k=y,appearToClass:F=w,leaveFromClass:j=`${r}-leave-from`,leaveActiveClass:lA=`${r}-leave-active`,leaveToClass:aA=`${r}-leave-to`}=t,mA=VsA(u),IA=mA&&mA[0],tA=mA&&mA[1],{onBeforeEnter:MA,onEnter:PA,onEnterCancelled:ge,onLeave:de,onLeaveCancelled:Ve,onBeforeAppear:Be=MA,onAppear:ct=PA,onAppearCancelled:mt=ge}=i,Ke=(It,re,qe,ft)=>{It._enterCancelled=ft,OM(It,re?F:w),OM(It,re?k:y),qe&&qe()},Dt=(It,re)=>{It._isLeaving=!1,OM(It,j),OM(It,aA),OM(It,lA),re&&re()},qt=It=>(re,qe)=>{const ft=It?ct:PA,si=()=>Ke(re,It,qe);FM(ft,[re,si]),mz(()=>{OM(re,It?_:p),jp(re,It?F:w),pz(ft)||fz(re,l,IA,si)})};return $l(i,{onBeforeEnter(It){FM(MA,[It]),jp(It,p),jp(It,y)},onBeforeAppear(It){FM(Be,[It]),jp(It,_),jp(It,k)},onEnter:qt(!1),onAppear:qt(!0),onLeave(It,re){It._isLeaving=!0;const qe=()=>Dt(It,re);jp(It,j),It._enterCancelled?(jp(It,lA),Sz()):(Sz(),jp(It,lA)),mz(()=>{It._isLeaving&&(OM(It,j),jp(It,aA),pz(de)||fz(It,l,tA,qe))}),FM(de,[It,qe])},onEnterCancelled(It){Ke(It,!1,void 0,!0),FM(ge,[It])},onAppearCancelled(It){Ke(It,!0,void 0,!0),FM(mt,[It])},onLeaveCancelled(It){Dt(It),FM(Ve,[It])}})}function VsA(t){if(t==null)return null;if(Ta(t))return[PK(t.enter),PK(t.leave)];{const i=PK(t);return[i,i]}}function PK(t){return PiA(t)}function jp(t,i){i.split(/\s+/).forEach(r=>r&&t.classList.add(r)),(t[YL]||(t[YL]=new Set)).add(i)}function OM(t,i){i.split(/\s+/).forEach(l=>l&&t.classList.remove(l));const r=t[YL];r&&(r.delete(i),r.size||(t[YL]=void 0))}function mz(t){requestAnimationFrame(()=>{requestAnimationFrame(t)})}let JsA=0;function fz(t,i,r,l){const u=t._endId=++JsA,p=()=>{u===t._endId&&l()};if(r!=null)return setTimeout(p,r);const{type:y,timeout:w,propCount:_}=HsA(t,i);if(!y)return l();const k=y+"end";let F=0;const j=()=>{t.removeEventListener(k,lA),p()},lA=aA=>{aA.target===t&&++F>=_&&j()};setTimeout(()=>{F<_&&j()},w+1),t.addEventListener(k,lA)}function HsA(t,i){const r=window.getComputedStyle(t),l=mA=>(r[mA]||"").split(", "),u=l(`${Qy}Delay`),p=l(`${Qy}Duration`),y=yz(u,p),w=l(`${Jk}Delay`),_=l(`${Jk}Duration`),k=yz(w,_);let F=null,j=0,lA=0;i===Qy?y>0&&(F=Qy,j=y,lA=p.length):i===Jk?k>0&&(F=Jk,j=k,lA=_.length):(j=Math.max(y,k),F=j>0?y>k?Qy:Jk:null,lA=F?F===Qy?p.length:_.length:0);const aA=F===Qy&&/\b(transform|all)(,|$)/.test(l(`${Qy}Property`).toString());return{type:F,timeout:j,propCount:lA,hasTransform:aA}}function yz(t,i){for(;t.lengthDz(r)+Dz(t[l])))}function Dz(t){return t==="auto"?0:Number(t.slice(0,-1).replace(",","."))*1e3}function Sz(){return document.body.offsetHeight}function qsA(t,i,r){const l=t[YL];l&&(i=(i?[i,...l]:[...l]).join(" ")),i==null?t.removeAttribute("class"):r?t.setAttribute("class",i):t.className=i}const F1=Symbol("_vod"),C6=Symbol("_vsh"),qa={beforeMount(t,{value:i},{transition:r}){t[F1]=t.style.display==="none"?"":t.style.display,r&&i?r.beforeEnter(t):Hk(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),Hk(t,!0),l.enter(t)):l.leave(t,()=>{Hk(t,!1)}):Hk(t,i))},beforeUnmount(t,{value:i}){Hk(t,i)}};function Hk(t,i){t.style.display=i?t[F1]:"none",t[C6]=!i}const KsA=Symbol(""),jsA=/(^|;)\s*display\s*:/;function WsA(t,i,r){const l=t.style,u=mg(r);let p=!1;if(r&&!u){if(i)if(mg(i))for(const y of i.split(";")){const w=y.slice(0,y.indexOf(":")).trim();r[w]==null&&C1(l,w,"")}else for(const y in i)r[y]==null&&C1(l,y,"");for(const y in r)y==="display"&&(p=!0),C1(l,y,r[y])}else if(u){if(i!==r){const y=l[KsA];y&&(r+=";"+y),l.cssText=r,p=jsA.test(r)}}else i&&t.removeAttribute("style");F1 in t&&(t[F1]=p?l.display:"",t[C6]&&(l.display="none"))}const Mz=/\s*!important$/;function C1(t,i,r){if(Ss(r))r.forEach(l=>C1(t,i,l));else if(r==null&&(r=""),i.startsWith("--"))t.setProperty(i,r);else{const l=zsA(t,i);Mz.test(r)?t.setProperty(Yy(l),r.replace(Mz,""),"important"):t[l]=r}}const vz=["Webkit","Moz","ms"],xK={};function zsA(t,i){const r=xK[i];if(r)return r;let l=KC(i);if(l!=="filter"&&l in t)return xK[i]=l;l=cY(l);for(let u=0;uYK||(AnA.then(()=>YK=0),YK=Date.now());function tnA(t,i){const r=l=>{if(!l._vts)l._vts=Date.now();else if(l._vts<=r.attached)return;Zh(inA(l,r.value),i,5,[l])};return r.value=t,r.attached=enA(),r}function inA(t,i){if(Ss(i)){const r=t.stopImmediatePropagation;return t.stopImmediatePropagation=()=>{r.call(t),t._stopped=!0},i.map(l=>u=>!u._stopped&&l&&l(u))}else return i}const Gz=t=>t.charCodeAt(0)===111&&t.charCodeAt(1)===110&&t.charCodeAt(2)>96&&t.charCodeAt(2)<123,onA=(t,i,r,l,u,p)=>{const y=u==="svg";i==="class"?qsA(t,l,y):i==="style"?WsA(t,r,l):rY(i)?p3(i)||XsA(t,i,r,l,p):(i[0]==="."?(i=i.slice(1),!0):i[0]==="^"?(i=i.slice(1),!1):snA(t,i,l,y))?(_z(t,i,l),!t.tagName.includes("-")&&(i==="value"||i==="checked"||i==="selected")&&wz(t,i,l,y,p,i!=="value")):t._isVueCE&&(/[A-Z]/.test(i)||!mg(l))?_z(t,KC(i),l,p,i):(i==="true-value"?t._trueValue=l:i==="false-value"&&(t._falseValue=l),wz(t,i,l,y))};function snA(t,i,r,l){if(l)return!!(i==="innerHTML"||i==="textContent"||i in t&&Gz(i)&&Xs(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 u=t.tagName;if(u==="IMG"||u==="VIDEO"||u==="CANVAS"||u==="SOURCE")return!1}return Gz(i)&&mg(r)?!1:i in t}const bz=t=>{const i=t.props["onUpdate:modelValue"]||!1;return Ss(i)?r=>u1(i,r):i};function nnA(t){t.target.composing=!0}function kz(t){const i=t.target;i.composing&&(i.composing=!1,i.dispatchEvent(new Event("input")))}const VK=Symbol("_assign"),rnA={created(t,{modifiers:{lazy:i,trim:r,number:l}},u){t[VK]=bz(u);const p=l||u.props&&u.props.type==="number";n_(t,i?"change":"input",y=>{if(y.target.composing)return;let w=t.value;r&&(w=w.trim()),p&&(w=Sj(w)),t[VK](w)}),r&&n_(t,"change",()=>{t.value=t.value.trim()}),i||(n_(t,"compositionstart",nnA),n_(t,"compositionend",kz),n_(t,"change",kz))},mounted(t,{value:i}){t.value=i??""},beforeUpdate(t,{value:i,oldValue:r,modifiers:{lazy:l,trim:u,number:p}},y){if(t[VK]=bz(y),t.composing)return;const w=(p||t.type==="number")&&!/^0\d/.test(t.value)?Sj(t.value):t.value,_=i??"";w!==_&&(document.activeElement===t&&t.type!=="range"&&(l&&i===r||u&&t.value.trim()===_)||(t.value=_))}},anA=["ctrl","shift","alt","meta"],gnA={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)=>anA.some(r=>t[`${r}Key`]&&!i.includes(r))},$E=(t,i)=>{const r=t._withMods||(t._withMods={}),l=i.join(".");return r[l]||(r[l]=(u,...p)=>{for(let y=0;y{const r=t._withKeys||(t._withKeys={}),l=i.join(".");return r[l]||(r[l]=u=>{if(!("key"in u))return;const p=Yy(u.key);if(i.some(y=>y===p||cnA[y]===p))return t(u)})},lnA=$l({patchProp:onA},FsA);let Lz;function B6(){return Lz||(Lz=asA(lnA))}const Av=(...t)=>{B6().render(...t)},InA=(...t)=>{const i=B6().createApp(...t),{mount:r}=i;return i.mount=l=>{const u=EnA(l);if(!u)return;const p=i._component;!Xs(p)&&!p.render&&!p.template&&(p.template=u.innerHTML),u.nodeType===1&&(u.textContent="");const y=r(u,!1,unA(u));return u instanceof Element&&(u.removeAttribute("v-cloak"),u.setAttribute("data-v-app","")),y},i};function unA(t){if(t instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&t instanceof MathMLElement)return"mathml"}function EnA(t){return mg(t)?document.querySelector(t):t}function dnA(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 Xk={exports:{}},h1={exports:{}},CnA=h1.exports,Uz;function Q6(){return Uz||(Uz=1,function(t,i){(function(r,l){t.exports=l()})(CnA,function(){const r=Q=>Q===void 0,l=Q=>typeof Q=="string",u=Q=>{var h;return(h=Object.prototype.toString.call(Q).match(/^\[object (.*)\]$/))===null||h===void 0?void 0:h[1].toLowerCase()},p=Q=>typeof Array.isArray=="function"?Array.isArray(Q):u(Q)==="array",y=Q=>Q!==null&&typeof Q=="object",w=Q=>p(Q)||y(Q),_=Q=>{if(typeof Q!="string")return!1;const h=Q[0];return!/[^a-zA-Z0-9]/.test(h)},k=Q=>{if(typeof Q!="object"||Q===null)return!1;const h=Object.getPrototypeOf(Q);if(h===null)return!0;let v=h;for(;Object.getPrototypeOf(v)!==null;)v=Object.getPrototypeOf(v);return h===v};function F(Q=99999999){return Math.round(Math.random()*Q)}const j=(Q,h,v,N)=>{if(!w(Q)||!w(h))return 0;let O=0;const z=Object.keys(h);let X;for(let rA=0,DA=z.length;rA"u"&&typeof uni.requireNativePlugin=="function",to=It&&typeof wx.miniapp=="object",uo=typeof uni<"u",Ys=ft&&typeof tt.enterChat=="function",ki=It||qe||ft||Vt||gi||_o||Fi,os=typeof window>"u"&&!ki&&typeof pg<"u"&&pg.NativeScriptGlobals!==void 0,Ko=typeof pg<"u"&&(pg.nativeModuleProxy!==void 0||pg.ReactNative!==void 0),$i=typeof wx<"u"&&typeof wx.getAccountInfoSync=="function"&&!!wx.getAccountInfoSync().plugin,jt=typeof uni<"u"?!ki:typeof window<"u"&&!ki&&!Ko,io=qe?qq:ft?tt:Vt?swan:gi?my:It?wx:_o?uni:Fi?jd:{},bi=jt&&window&&window.navigator&&window.navigator.userAgent||"",Ms=/(micromessenger|webbrowser)/i.test(bi),qA=function(){let Q="WEB";return Ms?Q="WEB":qe?Q="QQ_MP":ft?Q="TT_MP":Vt?Q="BAIDU_MP":gi?Q="ALI_MP":It?Q=to?"DONUT_NATIVE_APP":"WX_MP":_o?Q="UNI_NATIVE_APP":os?Q="NS_NATIVE_APP":Ko&&(Q="RN_NATIVE_APP"),aA[Q]}(),ce=/iPad/i.test(bi),Pe=/iPhone/i.test(bi)&&!ce,kt=/iPod/i.test(bi),it=Pe||ce||kt,gt=function(){const Q=bi.match(/OS (\d+)_/i);return Q&&Q[1]?Q[1]:null}(),Xt=/Android/i.test(bi),$t=function(){const Q=bi.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i);if(!Q)return null;const h=Q[1]&&parseFloat(Q[1]),v=Q[2]&&parseFloat(Q[2]);return h&&v?parseFloat(`${Q[1]}.${Q[2]}`):h||null}(),Ge=/Firefox/i.test(bi),je=/Edge/i.test(bi),Mt=!je&&/Chrome/i.test(bi),Rt=/MSIE/.test(bi)||bi.indexOf("Trident")>-1&&bi.indexOf("rv:11.0")>-1,Oi=function(){const Q=/MSIE\s(\d+)\.\d/.exec(bi);let h=Q&&parseFloat(Q[1]);return!h&&/Trident\/7.0/i.test(bi)&&/rv:11.0/.test(bi)&&(h=11),h}(),Qo=/Safari/i.test(bi)&&!Mt&&!Xt&&!je,To=/Windows/i.test(bi),oo=/MAC OS X/i.test(bi),No=jt&&typeof Worker<"u"&&!Rt,$s=Xt||it,rn=function(){if(typeof window>"u"||window.navigator===void 0)return!1;const{standalone:Q}=window.navigator;return!(!it||Q||Qo)}();function us(){let Q="unknown";if(oo&&(Q="mac"),To&&(Q="windows"),it&&(Q="ios"),Xt&&(Q="android"),ki)try{const{platform:h}=io.getSystemInfoSync();h!==void 0&&(Q=h)}catch(h){console.error(h)}return Q}const an=typeof process<"u"&&process.versions!==void 0&&process.versions.node!==void 0&&typeof window>"u";function yo(Q,h){var v={};for(var N in Q)Object.prototype.hasOwnProperty.call(Q,N)&&h.indexOf(N)<0&&(v[N]=Q[N]);if(Q!=null&&typeof Object.getOwnPropertySymbols=="function"){var O=0;for(N=Object.getOwnPropertySymbols(Q);O{io.request({url:v,data:N,method:h,timeout:O,header:{"content-type":jr},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":${Br}}`))},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(h,v,!0),rA.setRequestHeader("Content-type",jr),rA.send(N||null)})})}function vs(Q){if(Q==null)return!0;if(typeof Q=="boolean")return!1;if(typeof Q=="number")return Q===0;if(typeof Q=="string"||typeof Q=="function"||Array.isArray(Q))return Q.length===0;if(Q instanceof Error)return Q.message==="";if(k(Q)){for(const h in Q)if(Object.prototype.hasOwnProperty.call(Q,h))return!1;return!0}return(Object.prototype.toString.call(Q)==="[object Map]"||Object.prototype.toString.call(Q)==="[object Set]"||Object.prototype.toString.call(Q)==="[object File]")&&Q.size===0}function ir(Q,h){if(Q===null||typeof Q!="object")return Q;const v=h||new WeakMap;if(v.has(Q))return v.get(Q);if(Q instanceof Date)return new Date(Q.getTime());if(Q instanceof RegExp)return new RegExp(Q.source,Q.flags);if(Q instanceof Map){const z=new Map;return v.set(Q,z),Q.forEach((X,rA)=>{z.set(ir(rA,v),ir(X,v))}),z}if(Q instanceof Set){const z=new Set;return v.set(Q,z),Q.forEach(X=>{z.add(ir(X,v))}),z}if(Array.isArray(Q)){const z=[];return v.set(Q,z),Q.forEach(X=>{z.push(ir(X,v))}),z}const N=Object.getPrototypeOf(Q),O=Object.create(N);return v.set(Q,O),[...Object.getOwnPropertyNames(Q),...Object.getOwnPropertySymbols(Q)].forEach(z=>{if(z==="__ob__"||z==="__v_skip"||z==="__v_isRef"||z==="__v_isReadonly")return;const X=Object.getOwnPropertyDescriptor(Q,z);X&&(X.get||X.set?Object.defineProperty(O,z,X):O[z]=ir(Q[z],v))}),O}function An(Q,h,v){const N=new WeakSet,O=(z,X)=>{if(h&&(X=h(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(Q,O,v)}catch(z){return console.error("Failed to stringify:",z),""}}function wn(){let Q,h;return{promise:new Promise((v,N)=>{Q=v,h=N}),resolve:Q,reject:h}}var Jt,fg=Object.freeze({__proto__:null,ANDROID_VERSION:$t,IE_VERSION:Oi,IN_ALIPAY_MINI_APP:gi,IN_BAIDU_MINI_APP:Vt,IN_BROWSER:jt,IN_DONUT_NATIVE_APP:to,IN_FEISHU_MINI_APP:Ys,IN_JD_MINI_APP:Fi,IN_MINI_APP:ki,IN_NODE:an,IN_NS_NATIVE_APP:os,IN_QQ_MINI_APP:qe,IN_RN_APP:Ko,IN_TT_MINI_APP:ft,IN_TT_MINI_GAME:si,IN_UNI_APP:uo,IN_UNI_NATIVE_APP:_o,IN_WX_MINI_APP:It,IN_WX_MINI_APP_DESK:qt,IN_WX_MINI_GAME:re,IN_WX_MINI_PLUGIN:$i,IOS_VERSION:gt,IS_ANDROID:Xt,IS_CHROME:Mt,IS_EDGE:je,IS_FIREFOX:Ge,IS_IE:Rt,IS_IOS:it,IS_IPAD:ce,IS_IPHONE:Pe,IS_IPOD:kt,IS_MAC:oo,IS_SAFARI:Qo,IS_WECHAT:Ms,IS_WIN:To,IS_WORKER_AVAILABLE:No,MINI_APP_NAMESPACE:io,USER_AGENT:bi,base16EncodeBinaryString:lA,deepCopyWithMethods:ir,deepMerge:j,generatePromise:wn,getPlatformType:us,getType:u,httpRequest:Pi,isArray:p,isArrayOrObject:w,isEmpty:vs,isH5:$s,isIOSWebView:rn,isNumber:Q=>Q!==null&&(typeof Q=="number"&&!Number.isNaN(Q-0)||typeof Q=="object"&&Q.constructor===Number),isObject:y,isPlainObject:k,isString:l,isUndefined:r,isUniIOSApp:function(){return _o&&uni.getDeviceInfo().platform.toLocaleLowerCase()==="ios"},isValidRequestKey:_,platform:qA,randomInt:F,randomString:function(){const Q="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";let h="";for(let v=32;v>0;--v)h+=Q[Math.floor(62*Math.random())];return h},safeStringify:An});class On{constructor(){this.listeners={}}on(h,v,N){this.listeners[h]||(this.listeners[h]=[]),this.listeners[h].push({fn:v,context:N})}off(h,v,N){var O;v&&(this.listeners[h]=(O=this.listeners[h])===null||O===void 0?void 0:O.filter(z=>{const X=z.fn===v,rA=!N||z.context===N;return!(X&&rA)}))}emit(h,...v){const N=this.listeners[h];N&&N.forEach(O=>{const{fn:z,context:X}=O;try{z.apply(X,v)}catch(rA){console.warn(`Error in event handler for ${h} error: ${An(rA)}`)}})}once(h,v,N){const O=(...z)=>{v.apply(N,z),this.off(h,O)};this.on(h,O)}}(function(Q){Q.BUSINESS_COMMAND="business_command",Q.C2C_REALTIME_MESSAGE="c2c_realtime_message",Q.C2C_MESSAGE_MODIFIED="c2c_message_modified",Q.C2C_REVOKED_MESSAGE="c2c_message_revoked",Q.GROUP_REALTIME_MESSAGE="group_realtime_message",Q.GROUP_MESSAGE_MODIFIED="group_message_modified",Q.GROUP_MESSAGE_REVOKED="group_message_revoked",Q.C2C_MESSAGE_READ_RECEIPT="c2c_message_read_receipt",Q.MESSAGE_REACTION_UPDATED="message_reaction_updated",Q.MESSAGE_REACTION_UPDATED_SYNC="message_reaction_updated_sync",Q.GROUP_AT_TIPS="group_at_tips",Q.USER_STATUS_UPDATE="user_status_update",Q.FRIEND_LIST_MODIFIED="friend_list_modified",Q.PROFILE_MODIFIED="profile_modified",Q.CONV_MODIFIED="conversation_modified",Q.GROUP_TIPS_NOTIFICATION="group_tips_notification",Q.GROUP_MESSAGE_READ_RECEIPT="group_message_read_receipt",Q.GROUP_MESSAGE_READ_SYNC="group_message_read_sync",Q.GROUP_SYSTEM_NOTIFICATION="group_system_notification",Q.C2C_MESSAGE_PEER_READ="c2c_message_peer_read",Q.C2C_MESSAGE_READ_SYNC="c2c_message_read_sync",Q.C2C_REMIND_TYPE_SYNC="c2c_remind_type_sync",Q.FOLLOW_LIST_UPDATED="follow_list_updated",Q.MESSAGE_EXTENSIONS_UPDATED="message_extensions_updated",Q.ALL_MESSAGE_READ="all_message_read",Q.CONVERSATION_MARK_UPDATED="conversation_mark_updated",Q.CONVERSATION_GROUP_ADD="conversation_group_add",Q.CONVERSATION_GROUP_DELETED="conversation_group_deleted",Q.CONVERSATION_GROUP_UPDATED="conversation_group_updated",Q.ALL_RECEIVE_MESSAGE_OPTION="all_receive_message_option",Q.TOPIC_AT_TIPS="topic_at_tips",Q.TOPIC_TIPS_NOTIFICATION="topic_tips_notification",Q.TOPIC_SYSTEM_NOTIFICATION="topic_system_notification",Q.TOPIC_MESSAGE_READ_SYNC="topic_message_read_sync",Q.TOPIC_LATEST_MESSAGE="topic_latest_message",Q.GROUP_MESSAGE_PINNED="group_message_pinned"})(Jt||(Jt={}));const Gn=[16,17];function Vs(Q){var h;const v=[];return(h=Q?.GroupTips)===null||h===void 0||h.forEach(N=>{var O;N.GroupInfo.MillionGroupFlag===2?v.push(Jt.TOPIC_TIPS_NOTIFICATION):Gn.includes((O=N?.MsgBody)===null||O===void 0?void 0:O.OpType)?v.push(Jt.GROUP_MESSAGE_PINNED):v.push(Jt.GROUP_TIPS_NOTIFICATION)}),v}const Qr=[{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(Q){var h;const v=[];return(h=Q?.C2cNotifyMsgArray)===null||h===void 0||h.forEach(N=>{N.WithdrawC2cMsgNotify&&v.push(Jt.C2C_REVOKED_MESSAGE),N.C2cReadedReceipt&&v.push(Jt.C2C_MESSAGE_PEER_READ),N.ReadC2cMsgNotify&&v.push(Jt.C2C_MESSAGE_READ_SYNC),N.MuteNotificationsSync&&v.push(Jt.C2C_REMIND_TYPE_SYNC)}),v}},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:4}],subTypeParser:Vs},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:5}],subTypeParser:function(Q){var h;const v=[];return(h=Q?.GroupTips)===null||h===void 0||h.forEach(N=>{Array.isArray(N.MsgBody.GroupWithdrawInfoArray)?v.push(Jt.GROUP_MESSAGE_REVOKED):Array.isArray(N.MsgBody.GroupMsgReceiptList)?v.push(Jt.GROUP_MESSAGE_READ_RECEIPT):Array.isArray(N.MsgBody.GroupReadInfoArray)?N.MsgBody.GroupReadInfoArray[0].TopicId?v.push(Jt.TOPIC_MESSAGE_READ_SYNC):v.push(Jt.GROUP_MESSAGE_READ_SYNC):N.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:Vs},{conditions:[{type:"hasKey",value:"GroupTips"},{type:"event",value:12}],subTypeParser:function(Q){var h;const v=[];return(h=Q?.GroupTips)===null||h===void 0||h.forEach(N=>{const{GroupAtTips:{TopicId:O}}=N;O?v.push(Jt.TOPIC_AT_TIPS):v.push(Jt.GROUP_AT_TIPS)}),v}},{conditions:[{type:"hasKey",value:"RecentContactMod"}],subTypeParser:function(Q){var h;const v=[];return(h=Q?.RecentContactMod)===null||h===void 0||h.forEach(N=>{switch(N.PushType){case Ke.CONV_MARK_UPDATED:v.push(Jt.CONVERSATION_MARK_UPDATED);break;case Ke.CONV_GROUP_ADDED:v.push(Jt.CONVERSATION_GROUP_ADD);break;case Ke.CONV_GROUP_DELETED:v.push(Jt.CONVERSATION_GROUP_DELETED);break;case Ke.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 Pn;function pr(Q){var h;const v=Array.isArray((h=Q?.body)===null||h===void 0?void 0:h.EventArray)?Q.body.EventArray:[],N=[];return v.forEach(O=>{O.Flag=Q.body.Flag;const z=Qr.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(Q){Q.SERVER_PUSH_MESSAGE="im_open_push.msg_push",Q.SERVER_PUSH_MESSAGE_MULTIPLE="im_open_push.multi_msg_push_ws",Q.ERROR="error"})(Pn||(Pn={}));const po={[Pn.SERVER_PUSH_MESSAGE]:pr,[Pn.SERVER_PUSH_MESSAGE_MULTIPLE]:pr,[Pn.ERROR]:function(Q){const{errorCode:h}=Q;return[{type:`error:${h}`,data:Q}]}},gn=new class{constructor(){this._outerEventEmitter=null,this._innerEventEmitter=null,this._filteredCallbackMap=new Map,this._outerEventEmitter=new On,this._innerEventEmitter=new On,this.InnerEventSubType=Jt}subscribeInnerEvent(Q,h,v,N,O){var z;let X,rA,DA,GA;["string","number"].includes(typeof h)?(DA=`${Q}:${h}`,GA=v,rA=N,X=O):(DA=Q,GA=h,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(Q,h){var v,N;if((v=this._innerEventEmitter)===null||v===void 0||v.emit(Q,h),Object.keys(po).includes(Q)){const O=(N=po[Q])===null||N===void 0?void 0:N.call(po,h);O?.forEach(z=>{var X;z&&((X=this._innerEventEmitter)===null||X===void 0||X.emit(z.type,z.data))})}}subscribeOuterEvent(Q,h,v){var N;(N=this._outerEventEmitter)===null||N===void 0||N.on(Q,h,v)}unSubscribeOuterEvent(Q,h,v){var N;(N=this._outerEventEmitter)===null||N===void 0||N.off(Q,h,v)}unSubscribeInnerEvent(Q,h,v,N){if(["string","number"].includes(typeof h)){const O=v,z=`${Q}:${h}`;this._unsubscribeEvent(z,O,N)}else{const O=h;this._unsubscribeEvent(Q,O,v)}}emitOuterEvent(Q,h){var v;(v=this._outerEventEmitter)===null||v===void 0||v.emit(Q,h)}getOuterEventEmitter(){return this._outerEventEmitter}rest(){this._outerEventEmitter=null,this._innerEventEmitter=null}_subscribeWithFilter(Q,h,v,N){var O;const z=X=>{N.call(v,X)&&h.call(v,X)};this._filteredCallbackMap.has(Q)||this._filteredCallbackMap.set(Q,[]),this._filteredCallbackMap.get(Q).push({originalCallback:h,filteredCallback:z,filter:N,context:v}),(O=this._innerEventEmitter)===null||O===void 0||O.on(Q,z,v)}_unsubscribeEvent(Q,h,v){var N,O;const z=this._filteredCallbackMap.get(Q);if(z){const X=z.findIndex(rA=>rA.originalCallback===h&&rA.context===v);if(X!==-1){const{filteredCallback:rA}=z[X];return(N=this._innerEventEmitter)===null||N===void 0||N.off(Q,rA,v),z.splice(X,1),void(z.length===0&&this._filteredCallbackMap.delete(Q))}}(O=this._innerEventEmitter)===null||O===void 0||O.off(Q,h,v)}};class fl{constructor(){this._socket=null}connectSocket(h){return this._socket=new WebSocket(h),this._socket}send(h){var v,N;try{(v=this._socket)===null||v===void 0||v.send(h)}catch(O){(N=this._onSendFail)===null||N===void 0||N.call(this,O)}}bindSocketHandlers(h){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=h;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(h){this._onError=h.onError}connectSocket(h){const v=this;return this._socket=io.connectSocket({url:h,header:{"content-type":"application/json"},complete:()=>{},fail:N=>v._onError(N)}),this._socket}send(h){var v;(v=this._socket)===null||v===void 0||v.send({data:h,fail:this._onSendFail})}bindSocketHandlers(h){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=h;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 mr="CONNECT",ks="SEND",Yc="DISCONNECT",ps="OPEN",rs="MESSAGE",Bu="CLOSE",ja="ERROR",ds="SEND_FAIL";class og{constructor(){this._worker=null,this._blobUrl=null}connectSocket(h){const v=new Blob([` + let _socket = null; + + self.onmessage = (event) => { + const { type, url, data } = event.data; + + switch (type) { + case 'CONNECT': + connectSocket(url); + break; + case 'SEND': + send(data); + break; + case 'DISCONNECT': + disconnect(); + break; + } + }; + + function connectSocket(url) { + _socket = new WebSocket(url); + _socket.binaryType = 'arraybuffer'; + bindSocketHandlers(); + return _socket; + } + + function send(packet) { + try { + _socket?.send(packet); + } catch (error) { + self.postMessage({ + type: 'SEND_FAIL', + error: { + message: error.message, + name: error.name, + }, + }); + } + } + + function bindSocketHandlers() { + if (_socket) { + _socket.onopen = (event) => { + self.postMessage({ + type: 'OPEN', + data: { + type: event.type, + timeStamp: event.timeStamp, + }, + }); + }; + + _socket.onmessage = (event) => { + self.postMessage({ + type: 'MESSAGE', + data: event.data, + }); + }; + + _socket.onclose = (event) => { + self.postMessage({ + type: 'CLOSE', + data: { + code: event.code, + reason: event.reason, + timeStamp: event.timeStamp, + }, + }); + }; + + _socket.onerror = (error) => { + self.postMessage({ + type: 'ERROR', + data: { + message: error.message, + name: error.name + }, + }); + }; + } + } + + function unbindSocketHandlers() { + if (_socket) { + _socket.onopen = null; + _socket.onmessage = null; + _socket.onclose = null; + _socket.onerror = null; + } + } + + function disconnect() { + if (_socket) { + _socket.close(); + _socket = null; + } + } +`],{type:"application/javascript"});this._worker=new Worker(URL.createObjectURL(v)),this._worker.postMessage({type:mr,url:h})}send(h){var v,N;try{(v=this._worker)===null||v===void 0||v.postMessage({type:ks,data:h})}catch(O){(N=this._onSendFail)===null||N===void 0||N.call(this,O)}}bindSocketHandlers(h){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=h;if(this._worker){const rA={[ps]:v,[rs]:N,[Bu]:O,[ja]:z,[ds]: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:Yc}),this._worker.terminate(),this._worker=null),this._blobUrl&&(URL.revokeObjectURL(this._blobUrl),this._blobUrl=null)}}class LI{}var Xo,Zi=new class{constructor(){this._store=new Map}get(Q){return this._store.get(Q)}getStorage(Q){return ki?gi?my.getStorageSync({key:Q}).data:io.getStorageSync(Q):this._canUseLocalStorage()?localStorage.getItem(Q):{}}set(Q,h){const v=this._store.get(Q)||{};h instanceof Map?this._store.set(Q,h):this._store.set(Q,Object.assign(Object.assign({},v),h))}setStorage(Q,h){ki?gi?my.setStorageSync({key:Q,data:JSON.stringify(h)}):io.setStorageSync(Q,JSON.stringify(h)):this._canUseLocalStorage()&&localStorage.setItem(Q,JSON.stringify(h))}clear(Q){typeof Q=="string"?this._store.set(Q,{}):this._store.clear()}clearLocalStorage(Q){this._canUseLocalStorage()&&(typeof Q=="string"?localStorage.setItem(Q,""):localStorage.clear())}reset(){this.clear()}_canUseLocalStorage(){return typeof window<"u"&&navigator&&navigator.cookieEnabled&&localStorage}};class Qc{connectSocket(h){return this._socket=io.connectSocket({url:h,header:{"content-type":"application/json"},multiple:!0,complete:()=>{}}),this._socket}send(h){var v;(v=this._socket)===null||v===void 0||v.send({data:h,fail:this._onSendFail})}bindSocketHandlers(h){const{onOpen:v,onMessage:N,onClose:O,onError:z,onSendFail:X}=h;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(Q){Q[Q.CONNECTED=0]="CONNECTED",Q[Q.CONNECTING=1]="CONNECTING",Q[Q.DISCONNECTED=2]="DISCONNECTED"})(Xo||(Xo={}));class sg{constructor(h){this._url="",this._readyState=Xo.DISCONNECTED,this._url=h,this._id=F(),this._emitter=new On,gi?this._socket=new Qc:It||_o||ft||qe||Fi||Vt?this._socket=new cn({onError:this._onError.bind(this)}):an?this._socket=new LI:this._canUseWebWorker()?this._socket=new og:this._socket=new fl,this.connect()}connect(){this.doOpen(),this._bindSocketHandlers()}doOpen(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this._readyState=Xo.CONNECTING,this._ws=this._socket.connectSocket(this._url))}send(h){this._readyState!==Xo.CONNECTED?this.reconnect():this._socket.send(h)}reconnect(){[Xo.CONNECTED,Xo.CONNECTING].includes(this._readyState)||(this.disconnect(),this.doOpen())}getId(){return this._id}on(h,v,N){this._emitter.on(h,v,N)}off(h,v,N){this._emitter.off(h,v,N)}isConnected(){return this._readyState===Xo.CONNECTED}disconnect(){this._readyState=Xo.DISCONNECTED,this._unbindSocketHandlers(),this._socket.disconnect()}_onOpen(h){this._readyState===Xo.CONNECTING&&(this._readyState=Xo.CONNECTED,this._emitter.emit("connect",{socketId:this._id,event:h}))}_onMessage(h){this._emitter.emit("message",h)}_onClose(h){this._readyState=Xo.DISCONNECTED,this._emitter.emit("close",{socketId:this._id,event:h})}_onError(h){this._readyState=Xo.DISCONNECTED,this._emitter.emit("error",{socketId:this._id,error:h})}_onSendFail(h){this._readyState=Xo.DISCONNECTED,this._emitter.emit("sendFail",{socketId:this._id,error:h})}_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 h=Zi.get("cloudConfig")||{};return(r(h.isWorkerEnabled)||h.isWorkerEnabled==="1")&&No}}const yg={[ct.SINGAPORE]:[[2e7,3e7],[172e7,173e7]],[ct.KOREA]:[[3e7,4e7],[173e7,174e7]],[ct.GERMANY]:[[4e7,5e7],[174e7,175e7]],[ct.IND]:[[5e7,6e7],[175e7,176e7]],[ct.JPN]:[[6e7,7e7],[176e7,177e7]],[ct.USA]:[[7e7,8e7],[177e7,178e7]],[ct.INDONESIA]:[[8e7,9e7],[178e7,179e7]],[ct.KSA]:[[9e7,1e8],[179e7,18e8]]};function la(Q){var h;if(!((h=Zi.get("instance"))===null||h===void 0)&&h.oversea)return ct.OVERSEA;for(const v of Object.keys(yg))for(const[N,O]of yg[v])if(Q>=N&&Q`${ee}=${JA[ee]}`).join("&"));var JA;return v?`${Q}/binfo?${GA}&compress=gzip`:`${Q}/info?${GA}`}function Js(Q){const h=Zi.get("instance"),{sdkAppId:v,testEnv:N,proxyServer:O}=h,z=la(v);if(N)return Hn(mt.TEST[z].DEFAULT,{isBinary:Q});if(!vs(O))return Hn(O,{isBinary:Q});const X=mt.PRODUCTION[z],rA=jt&&X.ANYCAST,DA=jt,GA=!!X.BACKUP_CN;return Hn({[Go.INITIAL]:()=>(wo=Go.DEFAULT,X.DEFAULT),[Go.DEFAULT]:()=>(wo=Go.IPV6,X.IPV6),[Go.IPV6]:()=>(wo=Go.BACKUP,X.BACKUP),[Go.BACKUP]:()=>DA?(wo=Go.BACKUP_WEB_ONLY,function(JA){const ee=Math.floor(10001*Math.random())+1e4;return JA.replace("*",String(ee))}(X.BACKUP_WEB_ONLY)):GA?(wo=Go.BACKUP_CN,X.BACKUP_CN):rA?(wo=Go.ANYCAST,X.ANYCAST):X.DEFAULT,[Go.BACKUP_WEB_ONLY]:()=>GA?(wo=Go.BACKUP_CN,X.BACKUP_CN):rA?(wo=Go.ANYCAST,X.ANYCAST):X.DEFAULT,[Go.BACKUP_CN]:()=>(wo=rA?Go.ANYCAST:Go.DEFAULT,X[wo]),[Go.ANYCAST]:()=>(wo=Go.DEFAULT,X.ANYCAST="",X.DEFAULT)}[wo](),{isBinary:Q})}var Dg=new class{constructor(){this._timeOffsetWithServer=0}getServerTimeMs(){return Date.now()+this._timeOffsetWithServer}getServerTimeSeconds(){return Math.floor(this.getServerTimeMs()/1e3)}getTimeOffsetWithServer(){return this._timeOffsetWithServer}calculateTimeOffsetWithServer(Q,h){const v=Date.now(),N=v-Q;this._timeOffsetWithServer=h+N-v}};const pc=16;var fn=new class{constructor(){this._tasks=[],this._timer=null,this._taskMap=new Map}_addTaskToScheduler(Q){const{id:h}=Q;this.removeTask(h),this._tasks.push(Q),this._taskMap.set(h,Q),this._sort(),this._scheduleNextTask()}_createTask(Q){const{id:h,callback:v,context:N,isOnce:O=!1,intervalMs:z=pc}=Q,X=Math.max(z,pc);return{id:h,nextExecuteTime:Date.now()+X,intervalMs:z,callback:v,context:N,isOnce:O}}addTask(Q){const h=this._createTask(Q);this._addTaskToScheduler(h)}addOnceTask(Q){const h=this._createTask(Object.assign(Object.assign({},Q),{isOnce:!0}));this._addTaskToScheduler(h)}removeTask(Q){const h=this._tasks.findIndex(v=>v.id===Q);h>-1&&(this._tasks.splice(h,1),this._taskMap.delete(Q),this._scheduleNextTask())}updateTaskInterval(Q,h){const v=this._taskMap.get(Q);v&&(v.intervalMs=h,v.nextExecuteTime=Date.now()+h,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((Q,h)=>Q.nextExecuteTime-h.nextExecuteTime)}_scheduleNextTask(){this._timer&&(clearTimeout(this._timer),this._timer=null);const Q=this._tasks[0];if(Q){const h=Math.max(0,Q.nextExecuteTime-Date.now());this._timer=setTimeout(()=>this._execute(),h)}}_execute(){const Q=Date.now();for(;this._tasks.length&&this._tasks[0].nextExecuteTime<=Q;){const h=this._tasks[0];try{h.context?h.callback.call(h.context):h.callback(),h.isOnce?this.removeTask(h.id):(h.nextExecuteTime=Q+h.intervalMs,this._sort())}catch(v){console.warn(`Task ${h.id} execution failed:`,v),h.isOnce&&this.removeTask(h.id)}}this._scheduleNextTask()}};function Na(Q){const h=[];for(let v=0;v=55296&&N<=56319){const O=Q.charCodeAt(++v)-56320+(N-55296<<10)+65536;h.push(240|O>>18,128|O>>12&63,128|O>>6&63,128|63&O)}else N<=127?h.push(N):N<=2047?h.push(192|N>>6,128|63&N):h.push(224|N>>12,128|N>>6&63,128|63&N)}return new Uint8Array(h)}function In(Q){const h=Array.isArray(Q)?[]:Object.create(null);for(const v in Q)Object.prototype.hasOwnProperty.call(Q,v)&&_(v)&&Q[v]!=null&&(Q[v]===null||typeof Q[v]!="object"?h[v]=Q[v]:h[v]=In(Q[v]));return h}function ms(Q,h){if(mA.includes(Q))return 0;const v=Na(JSON.stringify(h));let N=4294967295;const{length:O}=v;for(let z=0;z>>=1:N=N>>>1^3988292384}return(4294967295^N)>>>0}function Ia(Q){const{servcmd:h,data:v}=Q,N=function(z){const X=Zi.get("login")||{},rA=Zi.get("instance")||{};return{servcmd:z,ver:"v4",platform:qA,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:ya(),cs:0}}(h),O=In(v);return N.cs=ms(h,O),{head:N,body:O}}function yn(Q){const{servcmd:h,data:v}=Q,N=function(z){const X=Zi.get("login")||{},rA=Zi.get("instance")||{};return{servcmd:z,ver:"v4",platform:qA,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:ya(),cs:0}}(h),O=In(v);return N.cs=ms(h,O),{head:N,body:O}}let Ga=F();function ya(){return Ga=Ga<2415919103?Ga+1:F(),Ga}function $(){var Q;const h=Zi.get("login")||{},v=Zi.get("instance")||{};return{sdk_type:30,sdk_app_id:v.sdkAppId,sdk_version:"1.6.18",tiny_id:Number(h.tinyID),user_id:h.userId||((Q=Zi.get("webPush"))===null||Q===void 0?void 0:Q.userId),platform:qA,instance_id:v.instanceId,trace_id:new Date().getTime()}}var K,RA=Object.freeze({__proto__:null,calcBodyCRC:ms,filterProtocolDataInvalidFields:In,generateCosSpecifiedData:function(Q){const{servcmd:h,data:v}=Q,N=function(z){const X=Zi.get("login")||{},rA=Zi.get("instance")||{};return{servcmd:z,ver:"v4",platform:qA,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:ya(),cs:0}}(h),O=In(v);return N.cs=ms(h,O),{head:N,body:O}},generateProtocolData:Ia,generateSSOLogProtocolData:yn,generateSequence:ya,getCommonHead:$,getHostSite:la,taskScheduler:fn,timeManager:Dg});(function(Q){Q[Q.info=4]="info",Q[Q.warning=5]="warning",Q[Q.error=6]="error"})(K||(K={}));const KA={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(h){this.level=K.info,this._canSendLog=!0,this._logCreatedAt=Dg.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:JA=0}=h||{};this.eventType=N,this.method=v,this.message=O,this.costTime=z,this.moreMessage=`${DA} startTime:${JA}`,this.code=GA,X&&this.setError(X),vs(rA)||(this.uiPlatform=rA)}setMoreMessage(h){this.moreMessage=`${this.moreMessage} ${h}`}updateLogCreatedAtByTimeOffset(){this._logCreatedAt+=Dg.getTimeOffsetWithServer()}end(h=!1){this._canSendLog&&(this._canSendLog=!1,this.timestamp=Dg.getServerTimeMs(),this._ssoLogModule.pushToLogQueue(this._convertSSOLogDataKeyToServe()),h&&this._ssoLogModule.uploadSSOLogData())}setError(h){var v;return h instanceof Error?this._canSendLog?(!((v=Zi.get("netWorkMonitor"))===null||v===void 0)&&v.isNetworkOnline&&(h.errorCode&&(this.code=h.errorCode),h.errorMessage&&this.setMoreMessage(h.errorMessage)),this.level=K.error,this):this:(console.warn("SSOLogData.setError value not instanceof Error, please check!"),this)}setLogInfo(h){return Object.keys(h).forEach(v=>{Object.keys(KA).includes(v)&&(this[v]=h[v])}),this}setSSOLogModule(h){this._ssoLogModule=h}_convertSSOLogDataKeyToServe(){const h={};return Object.keys(this).forEach(v=>{const N=v;KA[N]&&(h[KA[N]]=this[N])}),h}_getUiPlatform(){var h;const v=(h=Zi.get("instance"))===null||h===void 0?void 0:h.scene;if(typeof v=="string"){const N=Number(v);return isNaN(N)?void 0:N}}_getSDKEdition(){var h;return(h=Zi.get("instance"))===null||h===void 0?void 0:h.sdkEdition}}var pe;(function(Q){Q.RECONNECTED="reconnected",Q.CLOUD_CONFIG_UPDATE="cloud_config_update",Q.SOCKET_DISCONNECTED="socket_disconnected"})(pe||(pe={}));var Fe=pe;const Ue=20,ot=6e4,ut=[4,5,6],St="report-logger";var Ot=new class{constructor(){this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._reportLevel=[4,5,6],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._lastReportAt=Date.now(),this._ssoLogMap=new Map,this._logLevel=IA.DEBUG,this._throttleConfig={global:{throttleTime:Ve,maxCount:Be},single:{throttleTime:ge,maxCount:de}},this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap=new Map,gn.subscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),fn.addTask({id:St,intervalMs:1e3,callback:this._checkAndReportIfDue,context:this}),this._logQueue=[],this._savePlatFormInfo()}_handleCloudConfigUpdate(Q){const{evt_rpt_threshold:h=Ue,evt_rpt_waiting:v=ot,evt_rpt_level:N=ut,evt_rpt_sdkappid_bl:O="",evt_rpt_tinyid_wl:z="",evt_rpt_global_throttle_time:X=Ve,evt_rpt_global_throttle_count:rA=Be,evt_rpt_single_throttle_time:DA=ge,evt_rpt_single_throttle_count:GA=de}=Q||{};this._sdkAppIdBlackList=O.split(",").map(JA=>Number(JA)),this._waitingTime=Number(v),this._minThreshold=h,this._reportLevel=N,this._tinyIdWhiteList=z.split(","),this._throttleConfig={global:{throttleTime:X,maxCount:rA},single:{throttleTime:DA,maxCount:GA}}}createSSOLogData(Q){const h=new Ae(Q);return h.setSSOLogModule(this),this._ssoLogMap.set(Q.method,h),h}getSSOLogData(Q){return this._ssoLogMap.get(Q)||{}}pushToLogQueue(Q){Q&&(this._logQueue.push(Q),this._shouldUploadImmediately()&&this.uploadSSOLogData())}setLogLevel(Q){[IA.DEBUG,IA.ERROR,IA.INFO,IA.NONE,IA.WARN].includes(Q)&&(this._logLevel=Q)}debug(Q,h="",v){this._log(IA.DEBUG,Q,h,v)}info(Q,h="",v){this._log(IA.INFO,Q,h,v)}warn(Q,h="",v){this._log(IA.WARN,Q,h,v)}error(Q,h="",v){this._log(IA.ERROR,Q,h,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 Q=this._logQueue.slice();this._logQueue=[];try{const h=this._filterLogs(Q);if(h.length===0)return void(this._lastReportAt=Date.now());const v={Header:$(),Event:h};vs(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 Dl.sendPacket(z,{requestId:X})}(v))}catch(h){this._requeueFailedLogs(Q),this.debug("uploadSSOLogData",An(h))}finally{this._lastReportAt=Date.now()}})}_requeueFailedLogs(Q){this._logQueue=Q.concat(this._logQueue);const h=this._logQueue.length-200;h>0&&(this._logQueue.splice(0,h),this.debug("uploadSSOLogData",`log queue overflow, dropped ${h} oldest logs`))}_savePlatFormInfo(){var Q,h;if(It){const v=(h=(Q=wx.getAccountInfoSync)===null||Q===void 0?void 0:Q.call(wx))===null||h===void 0?void 0:h.miniProgram;if(v){const{appId:N,envVersion:O}=v;Zi.set("instance",{appId:N,envVersion:O})}}else jt&&Zi.set("instance",{href:window.location.href})}_filterLogs(Q){const{tinyID:h}=Zi.get("login")||{},{sdkAppId:v}=Zi.get("instance")||{};return this._sdkAppIdBlackList.includes(v)&&!this._tinyIdWhiteList.includes(h)?[]:Q.filter(N=>this._reportLevel.includes(N.level))}_checkThrottle(Q){return!!this._checkGlobalThrottle()||this._checkSingleThrottle(Q)}_checkGlobalThrottle(){const Q=Date.now();if(Q-this._globalThrottle.startTime>=this._throttleConfig.global.throttleTime)this._globalThrottle.count=1,this._globalThrottle.startTime=Q;else if(this._globalThrottle.count++,this._globalThrottle.count>this._throttleConfig.global.maxCount)return!0;return!1}_checkSingleThrottle(Q){const h=Date.now(),v=this._singleThrottleMap.get(Q);return v?h-v.startTime>=this._throttleConfig.single.throttleTime?(v.count=1,v.startTime=h,!1):v.count>=this._throttleConfig.single.maxCount||(v.count++,!1):(this._singleThrottleMap.set(Q,{count:1,startTime:h}),!1)}_shouldLog(Q){return Q>=this._logLevel&&this._logLevel!==IA.NONE}_shouldReport(Q){return this._reportLevel.includes(PA[Q])}_formatLog(Q,h,v,N){const O=new Date,z=`${O.getHours()}:${O.getMinutes()}:${O.getSeconds()}:${O.getMilliseconds()}`,X=`<${IA[Q]}>`;return Rt||ki?[`${tA} [${z}] ${X} [${h}] ${v}`]:["%c%s%c%s","background:#0abf5b; padding:1px; border-radius:3px; color: #fff",tA,"",`[${z}] ${X} [${h}] ${v} params: ${An(N)}`]}_log(Q,h,v,N){if(this._shouldLog(Q)){const O=this._formatLog(Q,h,v,N);MA[Q].apply(console,O)}if(this._shouldReport(Q)){const O=this._getThrottleKey(h,v,N);this._checkThrottle(O)||this.createSSOLogData(Object.assign(Object.assign({message:v},N),{method:h})).end()}}_getThrottleKey(Q,h,v){const N=`${Q}${h}${An(Object.assign(Object.assign({},v),{costTime:""}))}`,O=Na(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(St),gn.unSubscribeInnerEvent(Fe.CLOUD_CONFIG_UPDATE,this._handleCloudConfigUpdate,this),this._lastReportAt=0,this.uploadSSOLogData(),this._sdkAppIdBlackList=[],this._tinyIdWhiteList=[],this._minThreshold=Ue,this._maxThreshold=100,this._waitingTime=ot,this._logQueue=[],this._logLevel=IA.DEBUG,this._globalThrottle={count:0,startTime:Date.now()},this._singleThrottleMap.clear()}};const li=15e3,nt="Channel",Ft="channel_schedule_task",Ji="channel_reconnect_task",qi="connected",Hs="connecting",Mi="disconnected",Wo=1e3,Sg="network_status_change",or="activity_status_change",fr="send_fail",xn="reconnect_failed",yl="socket_error",qs="socket_close";function tI(Q){return tI=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(h){return typeof h}:function(h){return h&&typeof Symbol=="function"&&h.constructor===Symbol&&h!==Symbol.prototype?"symbol":typeof h},tI(Q)}function jg(Q){throw new Error('Could not dynamically require "'+Q+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var mc,Qu={exports:{}},Da=(mc||(mc=1,function(Q){Q.exports=function h(v,N,O){function z(DA,GA){if(!N[DA]){if(!v[DA]){if(!GA&&jg)return jg(DA);if(X)return X(DA,!0);var JA=new Error("Cannot find module '"+DA+"'");throw JA.code="MODULE_NOT_FOUND",JA}var ee=N[DA]={exports:{}};v[DA][0].call(ee.exports,function(ue){return z(v[DA][1][ue]||ue)},ee,ee.exports,h,v,N,O)}return N[DA].exports}for(var X=jg,rA=0;rA>>6:(ue<65536?ee[st++]=224|ue>>>12:(ee[st++]=240|ue>>>18,ee[st++]=128|ue>>>12&63),ee[st++]=128|ue>>>6&63),ee[st++]=128|63&ue);return ee},N.buf2binstring=function(JA){return GA(JA,JA.length)},N.binstring2buf=function(JA){for(var ee=new O.Buf8(JA.length),ue=0,He=ee.length;ue>10&1023,xt[He++]=56320|1023&At)}return GA(xt,He)},N.utf8border=function(JA,ee){var ue;for((ee=ee||JA.length)>JA.length&&(ee=JA.length),ue=ee-1;0<=ue&&(192&JA[ue])==128;)ue--;return ue<0||ue===0?ee:ue+rA[JA[ue]]>ee?ue:ee}},{"./common":1}],3:[function(h,v,N){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 ee=DA;ee>>8^GA[255&(z^X[ee])];return-1^z}},{}],6:[function(h,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(h,v,N){v.exports=function(O,z){var X,rA,DA,GA,JA,ee,ue,He,At,st,Gt,xt,Ui,ao,zi,ui,Oo,$o,Qi,Ki,js,we,vt,FA,Wt;X=O.state,rA=O.next_in,FA=O.input,DA=rA+(O.avail_in-5),GA=O.next_out,Wt=O.output,JA=GA-(z-O.avail_out),ee=GA+(O.avail_out-257),ue=X.dmax,He=X.wsize,At=X.whave,st=X.wnext,Gt=X.window,xt=X.hold,Ui=X.bits,ao=X.lencode,zi=X.distcode,ui=(1<>>=Qi=$o>>>24,Ui-=Qi,(Qi=$o>>>16&255)==0)Wt[GA++]=65535&$o;else{if(!(16&Qi)){if(!(64&Qi)){$o=ao[(65535&$o)+(xt&(1<>>=Qi,Ui-=Qi),Ui<15&&(xt+=FA[rA++]<>>=Qi=$o>>>24,Ui-=Qi,!(16&(Qi=$o>>>16&255))){if(!(64&Qi)){$o=zi[(65535&$o)+(xt&(1<>>=Qi,Ui-=Qi,(Qi=GA-JA)>3,xt&=(1<<(Ui-=Ki<<3))-1,O.next_in=rA,O.next_out=GA,O.avail_in=rA>>24&255)+(we>>>8&65280)+((65280&we)<<8)+((255&we)<<24)}function xt(){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(we){var vt;return we&&we.state?(vt=we.state,we.total_in=we.total_out=vt.total=0,we.msg="",vt.wrap&&(we.adler=1&vt.wrap),vt.mode=He,vt.last=0,vt.havedict=0,vt.dmax=32768,vt.head=null,vt.hold=0,vt.bits=0,vt.lencode=vt.lendyn=new O.Buf32(At),vt.distcode=vt.distdyn=new O.Buf32(st),vt.sane=1,vt.back=-1,ee):ue}function ao(we){var vt;return we&&we.state?((vt=we.state).wsize=0,vt.whave=0,vt.wnext=0,Ui(we)):ue}function zi(we,vt){var FA,Wt;return we&&we.state?(Wt=we.state,vt<0?(FA=0,vt=-vt):(FA=1+(vt>>4),vt<48&&(vt&=15)),vt&&(vt<8||15=Zt.wsize?(O.arraySet(Zt.window,vt,FA-Zt.wsize,Zt.wsize,0),Zt.wnext=0,Zt.whave=Zt.wsize):(Wt<(En=Zt.wsize-Zt.wnext)&&(En=Wt),O.arraySet(Zt.window,vt,FA-Wt,En,Zt.wnext),(Wt-=En)?(O.arraySet(Zt.window,vt,FA-Wt,Wt,0),Zt.wnext=Wt,Zt.whave=Zt.wsize):(Zt.wnext+=En,Zt.wnext===Zt.wsize&&(Zt.wnext=0),Zt.whave>>8&255,FA.check=X(FA.check,Te,2,0),Ct=Et=0,FA.mode=2;break}if(FA.flags=0,FA.head&&(FA.head.done=!1),!(1&FA.wrap)||(((255&Et)<<8)+(Et>>8))%31){we.msg="incorrect header check",FA.mode=30;break}if((15&Et)!=8){we.msg="unknown compression method",FA.mode=30;break}if(Ct-=4,yA=8+(15&(Et>>>=4)),FA.wbits===0)FA.wbits=yA;else if(yA>FA.wbits){we.msg="invalid window size",FA.mode=30;break}FA.dmax=1<>8&1),512&FA.flags&&(Te[0]=255&Et,Te[1]=Et>>>8&255,FA.check=X(FA.check,Te,2,0)),Ct=Et=0,FA.mode=3;case 3:for(;Ct<32;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>8&255,Te[2]=Et>>>16&255,Te[3]=Et>>>24&255,FA.check=X(FA.check,Te,4,0)),Ct=Et=0,FA.mode=4;case 4:for(;Ct<16;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>8),512&FA.flags&&(Te[0]=255&Et,Te[1]=Et>>>8&255,FA.check=X(FA.check,Te,2,0)),Ct=Et=0,FA.mode=5;case 5:if(1024&FA.flags){for(;Ct<16;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>8&255,FA.check=X(FA.check,Te,2,0)),Ct=Et=0}else FA.head&&(FA.head.extra=null);FA.mode=6;case 6:if(1024&FA.flags&&(vi<(ji=FA.length)&&(ji=vi),ji&&(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,Wt,Zt,ji,yA)),512&FA.flags&&(FA.check=X(FA.check,Wt,ji,Zt)),vi-=ji,Zt+=ji,FA.length-=ji),FA.length))break A;FA.length=0,FA.mode=7;case 7:if(2048&FA.flags){if(vi===0)break A;for(ji=0;yA=Wt[Zt+ji++],FA.head&&yA&&FA.length<65536&&(FA.head.name+=String.fromCharCode(yA)),yA&&ji>9&1,FA.head.done=!0),we.adler=FA.check=0,FA.mode=12;break;case 10:for(;Ct<32;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>=7&Ct,Ct-=7&Ct,FA.mode=27;break}for(;Ct<3;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>=1)){case 0:FA.mode=14;break;case 1:if(Ki(FA),FA.mode=20,vt!==6)break;Et>>>=2,Ct-=2;break A;case 2:FA.mode=17;break;case 3:we.msg="invalid block type",FA.mode=30}Et>>>=2,Ct-=2;break;case 14:for(Et>>>=7&Ct,Ct-=7&Ct;Ct<32;){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>16^65535)){we.msg="invalid stored block lengths",FA.mode=30;break}if(FA.length=65535&Et,Ct=Et=0,FA.mode=15,vt===6)break A;case 15:FA.mode=16;case 16:if(ji=FA.length){if(vi>>=5,Ct-=5,FA.ndist=1+(31&Et),Et>>>=5,Ct-=5,FA.ncode=4+(15&Et),Et>>>=4,Ct-=4,286>>=3,Ct-=3}for(;FA.have<19;)FA.lens[ne[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){we.msg="invalid code lengths set",FA.mode=30;break}FA.have=0,FA.mode=19;case 19:for(;FA.have>>16&255,ha=65535&le,!((es=le>>>24)<=Ct);){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>=es,Ct-=es,FA.lens[FA.have++]=ha;else{if(ha===16){for(ve=es+2;Ct>>=es,Ct-=es,FA.have===0){we.msg="invalid bit length repeat",FA.mode=30;break}yA=FA.lens[FA.have-1],ji=3+(3&Et),Et>>>=2,Ct-=2}else if(ha===17){for(ve=es+3;Ct>>=es)),Et>>>=3,Ct-=3}else{for(ve=es+7;Ct>>=es)),Et>>>=7,Ct-=7}if(FA.have+ji>FA.nlen+FA.ndist){we.msg="invalid bit length repeat",FA.mode=30;break}for(;ji--;)FA.lens[FA.have++]=yA}}if(FA.mode===30)break;if(FA.lens[256]===0){we.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){we.msg="invalid literal/lengths set",FA.mode=30;break}if(FA.distbits=6,FA.distcode=FA.distdyn,zA={bits:FA.distbits},NA=DA(JA,FA.lens,FA.nlen,FA.ndist,FA.distcode,0,FA.work,zA),FA.distbits=zA.bits,NA){we.msg="invalid distances set",FA.mode=30;break}if(FA.mode=20,vt===6)break A;case 20:FA.mode=21;case 21:if(6<=vi&&258<=Co){we.next_out=Is,we.avail_out=Co,we.next_in=Zt,we.avail_in=vi,FA.hold=Et,FA.bits=Ct,rA(we,bs),Is=we.next_out,En=we.output,Co=we.avail_out,Zt=we.next_in,Wt=we.input,vi=we.avail_in,Et=FA.hold,Ct=FA.bits,FA.mode===12&&(FA.back=-1);break}for(FA.back=0;aa=(le=FA.lencode[Et&(1<>>16&255,ha=65535&le,!((es=le>>>24)<=Ct);){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>$r)])>>>16&255,ha=65535&le,!($r+(es=le>>>24)<=Ct);){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>=$r,Ct-=$r,FA.back+=$r}if(Et>>>=es,Ct-=es,FA.back+=es,FA.length=ha,aa===0){FA.mode=26;break}if(32&aa){FA.back=-1,FA.mode=12;break}if(64&aa){we.msg="invalid literal/length code",FA.mode=30;break}FA.extra=15&aa,FA.mode=22;case 22:if(FA.extra){for(ve=FA.extra;Ct>>=FA.extra,Ct-=FA.extra,FA.back+=FA.extra}FA.was=FA.length,FA.mode=23;case 23:for(;aa=(le=FA.distcode[Et&(1<>>16&255,ha=65535&le,!((es=le>>>24)<=Ct);){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>$r)])>>>16&255,ha=65535&le,!($r+(es=le>>>24)<=Ct);){if(vi===0)break A;vi--,Et+=Wt[Zt++]<>>=$r,Ct-=$r,FA.back+=$r}if(Et>>>=es,Ct-=es,FA.back+=es,64&aa){we.msg="invalid distance code",FA.mode=30;break}FA.offset=ha,FA.extra=15&aa,FA.mode=24;case 24:if(FA.extra){for(ve=FA.extra;Ct>>=FA.extra,Ct-=FA.extra,FA.back+=FA.extra}if(FA.offset>FA.dmax){we.msg="invalid distance too far back",FA.mode=30;break}FA.mode=25;case 25:if(Co===0)break A;if(ji=bs-Co,FA.offset>ji){if((ji=FA.offset-ji)>FA.whave&&FA.sane){we.msg="invalid distance too far back",FA.mode=30;break}ji>FA.wnext?(ji-=FA.wnext,Yr=FA.wsize-ji):Yr=FA.wnext-ji,ji>FA.length&&(ji=FA.length),ic=FA.window}else ic=En,Yr=Is-FA.offset,ji=FA.length;for(CoOo?(Qi=Yr[ic+st[vt]],Ki=Ct[Ig+st[vt]]):(Qi=96,Ki=0),xt=1<>Is)+(Ui-=xt)]=$o<<24|Qi<<16|Ki,Ui!==0;);for(xt=1<>=1;if(xt!==0?(Et&=xt-1,Et+=xt):Et=0,vt++,--bs[we]==0){if(we===Wt)break;we=JA[ee+st[vt]]}if(En{const rA=new Uint8Array(X).slice(4);let DA;try{DA=Da.inflate(rA,{to:"string"})}catch(GA){console.error("inflate error",GA)}return DA})(Q.data):function(X){const rA=new Uint8Array(X);let DA="",GA=0;const{length:JA}=rA;for(;GA0)for(let At=0;At{var N;const{uplinkData:O,canResend:z,resolve:X,reject:rA,timeout:DA}=h;if(z){this._pendingRequests.set(v,{resolve:X,reject:rA,timestamp:Date.now(),uplinkData:O,timeout:DA,canResend:z});const GA=this._isBinarySupported?Na(O).buffer:O;(N=this._socketAdapter)===null||N===void 0||N.send(GA)}else this._pendingRequests.delete(v)})}_onConnect(Q){const{socketId:h,event:v={}}=Q||{};this._connectionId=h,this._connectionEstablishedTime=Date.now();const N=Date.now()-this._connectionStartTime,O=`${nt}.onConnect cost:${N} ms. socketID:${h} res:${JSON.stringify(v)}`;if(this._ssoLog({method:"onConnect",message:O}),this._checkPendingRequestsAndResend(),this._sendHeartbeatIfReady(),this._isReconnecting){const z=`${nt}.reconnect success`;this._ssoLog({method:"reconnectSuccess",message:z}),gn.emitInnerEvent(Fe.RECONNECTED),this._isReconnecting=!1}this._resetReconnectDelay(),this._handleConnectStateChange({state:qi,shouldEmitEvent:!0,shouldAttemptReconnect:!1})}_sendAck(Q){const h=Ia({servcmd:"openim.ws_msg_push_ack",data:{SessionData:Q}});this.sendPacket(h)}_executeScheduledTaskIfReady(){return pA(this,void 0,void 0,function*(){this._clearTimeoutRequest(),this._sendHeartbeatIfReady()})}_canSendHeartbeat(){var Q;return((Q=this._socketAdapter)===null||Q===void 0?void 0:Q.isConnected())&&Date.now()>=this._nextHeartbeatAt&&!this._isHeartbeatInProgress}_sendHeartbeat(){return pA(this,void 0,void 0,function*(){var Q;const h=Ia({servcmd:"heartbeat.alive",data:{}});try{const v=`${h.head.seq}${h.head.servcmd}`;yield this.sendPacket(h,{requestId:v,timeout:3e3})}catch(v){const N=(Q=Zi.get("netWorkMonitor"))===null||Q===void 0?void 0:Q.isNetworkOnline,O=`${nt}.sendHeartbeat failed. isNetWorkOnline:${N} error: ${An(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=_o?Date.now()+5e3:Date.now()+1e4}_handleNetworkStatusChange(Q){const h=`${nt}.networkStatusChange ${JSON.stringify(Q)}`;this._ssoLog({method:"networkStatusChange",message:h});const{isNetworkOnline:v,networkType:N}=Q;v&&N!=="none"?this._handleConnectStateChange({state:qi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg}):this._handleConnectStateChange({state:Mi,shouldEmitEvent:!1,shouldAttemptReconnect:!0,reason:Sg})}isPrivateNetWork(){const Q=Zi.get("instance")||{};return Q.proxyServer&&!Q.fileDownloadProxy}_handleConnectStateChange(Q){const{state:h,shouldAttemptReconnect:v,shouldEmitEvent:N,reason:O}=Q,z=`${nt}._handleConnectStateChange currentConnectState: ${this._currentConnectState} shouldAttemptReconnect: ${v} shouldEmitEvent: ${N} reason: ${O}`;this._currentConnectState!==h&&(this._ssoLog({method:"handleConnectStateChange",message:z}),N&&(Ot.info("_handleConnectStateChange",` from ${this._currentConnectState} to ${h}`),gn.emitOuterEvent("netStateChange",{name:"netStateChange",data:{state:h}}),this._currentConnectState=h,h===Mi&&gn.emitInnerEvent(Fe.SOCKET_DISCONNECTED)),v&&(this._resetReconnectDelay(),fn.addTask({id:Ji,intervalMs:this._intendedDelay,callback:this._scheduleReconnectWithBackoff,context:this})))}_handleActivityStatusChange(Q){var h,v;const N=(v=(h=this._socketAdapter)===null||h===void 0?void 0:h._ws)===null||v===void 0?void 0:v.readyState,O=`${nt}.activityStatusChange ${JSON.stringify(Q)} readyState: ${N}`;Ot.debug("activityStatusChange",O),N===3&&this._handleConnectStateChange({state:Mi,shouldEmitEvent:!0,shouldAttemptReconnect:!0,reason:or})}_resetReconnectDelay(){var Q;Ot.debug(`${nt}._resetReconnectDelay`),fn.removeTask(Ji);const h=(Q=Zi.get("activityMonitor"))===null||Q===void 0?void 0:Q.isActive;this._intendedDelay=h?Wo:1e3}_scheduleReconnectWithBackoff(){var Q;const h=(Q=Zi.get("activityMonitor"))===null||Q===void 0?void 0:Q.isActive;this._intendedDelay=h?Math.min(5e3,Math.max(Wo,1.5*this._intendedDelay)):Math.min(3e5,Math.max(1e3,1.5*this._intendedDelay));const v=new Date().toTimeString().slice(0,8),N=`${nt}.scheduleReconnectWithBackoff timeStr: ${v} intendedDelay: ${this._intendedDelay}`;Ot.debug(N),this.reconnect(),fn.updateTaskInterval(Ji,this._intendedDelay)}_ssoLog(Q){const{method:h,message:v}=Q;Ot.info(h,v)}_diagnose(){this.isPrivateNetWork()||(this._lastDiagnoseAt=Date.now(),function(Q){pA(this,void 0,void 0,function*(){const h=Q.split("/")[2];if(!h.startsWith("ws"))return;const v=`https://${h}/v3/netcheck/getconninfo?${Q.slice(Q.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:v,data:{}})}catch(N){Ot.warn("diagnoseBySSO",`diagnoseBySSO failed. error:${N.message}`)}})}(this._url),function(Q){pA(this,void 0,void 0,function*(){const h=`https://boce-cdn.my-imcloud.com/v3/netcheck/getconninfo?${Q.slice(Q.indexOf("info?")+5)}&reqtime=${Date.now()}`;try{yield Pi({method:"GET",url:h,data:{}})}catch(v){Ot.warn(`diagnoseByCDN', 'diagnoseByCDN failed. error:${v.message}`)}})}(this._url),this._beforeSendInterceptors=[])}_clearTimeoutRequest(){for(const[Q,h]of this._pendingRequests.entries()){const{reject:v,timestamp:N,timeout:O}=h;Date.now()-N>=O&&(this._pendingRequests.delete(Q),Date.now()-this._lastDiagnoseAt>=3e4&&this._diagnose(),v({errorCode:Br,errorInfo:"NETWORK_TIMEOUT",data:{requestId:Q}}))}}_updateIsBinarySupported(){var Q;if(!((Q=Zi.get("instance"))===null||Q===void 0)&&Q.devMode)return void(this._isBinarySupported=!1);const h=us();if((gi||It&&h==="windows"||Ys)&&(this._isBinarySupported=!1),_o){const{uniRuntimeVersion:v=""}=io.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(Q){const h=new Uint8Array(Q);return h[0]===67&&h[1]===79&&h[2]===77&&h[3]===80}};const fe={init:function(Q){Zi.set("instance",Q),Dl.init()},destroy:function(){Dl.dispose(),Zi.clear(),fn.dispose()},notificationCenter:gn,channel:Dl,store:Zi,ssoLog:Ot,utils:fg,common:RA,constants:Dt},me=Q=>typeof Q=="function";function Mg(Q,h,v){const N=v||[];if(!Q||!h)return!1;const O=Object.keys(Q).filter(X=>!N.includes(X)),z=Object.keys(h).filter(X=>!N.includes(X));return O.length===z.length&&O.every(X=>!!h.hasOwnProperty(X)&&(typeof Q[X]=="object"&&Q[X]!==null?Mg(Q[X],h[X],v):Q[X]===h[X]))}var ng;(function(Q){Q.SDK_READY="sdkStateReady",Q.SDK_NOT_READY="sdkStateNotReady",Q.SDK_DESTROY="sdkDestroy",Q.MESSAGE_RECEIVED="onMessageReceived",Q.ROOM_CUSTOM_DATA_RECEIVED="onRoomCustomDataReceived",Q.MESSAGE_MODIFIED="onMessageModified",Q.MESSAGE_REVOKED="onMessageRevoked",Q.MESSAGE_READ_BY_PEER="onMessageReadByPeer",Q.MESSAGE_READ_RECEIPT_RECEIVED="onMessageReadReceiptReceived",Q.MESSAGE_EXTENSIONS_UPDATED="onMessageExtensionsUpdated",Q.MESSAGE_EXTENSIONS_DELETED="onMessageExtensionsDeleted",Q.MESSAGE_REACTIONS_UPDATED="onMessageReactionsUpdated",Q.CONVERSATION_LIST_UPDATED="onConversationListUpdated",Q.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED="onTotalUnreadMessageCountUpdated",Q.CONVERSATION_GROUP_LIST_UPDATED="onConversationGroupListUpdated",Q.CONVERSATION_IN_GROUP_UPDATED="onConversationInGroupUpdated",Q.GROUP_LIST_UPDATED="onGroupListUpdated",Q.GROUP_ATTRIBUTES_UPDATED="groupAttributesUpdated",Q.GROUP_COUNTER_UPDATED="onGroupCounterUpdated",Q.TOPIC_CREATED="onTopicCreated",Q.TOPIC_DELETED="onTopicDeleted",Q.TOPIC_UPDATED="onTopicUpdated",Q.PROFILE_UPDATED="onProfileUpdated",Q.USER_STATUS_UPDATED="onUserStatusUpdated",Q.BLACKLIST_UPDATED="blacklistUpdated",Q.FRIEND_LIST_UPDATED="onFriendListUpdated",Q.FRIEND_GROUP_LIST_UPDATED="onFriendGroupListUpdated",Q.FRIEND_APPLICATION_LIST_UPDATED="onFriendApplicationListUpdated",Q.MY_FOLLOWERS_LIST_UPDATED="onMyFollowersListUpdated",Q.MY_FOLLOWING_LIST_UPDATED="onMyFollowingListUpdated",Q.MUTUAL_FOLLOWERS_LIST_UPDATED="onMutualFollowersListUpdated",Q.KICKED_OUT="kickedOut",Q.ERROR="error",Q.NET_STATE_CHANGE="netStateChange",Q.ALL_RECEIVE_MESSAGE_OPT_UPDATED="onAllReceiveMessageOptUpdated",Q.SERVER_CONFIG_UPDATED="onServerConfigUpdated",Q.PINNED_GROUP_MESSAGE_UPDATED="onPinnedGroupMessageUpdated",Q.WEB_PUSH_MESSAGE_RECEIVED="onWebPushMessageReceived",Q.GROUP_ONLINE_MEMBER_COUNT_CHANGED="onGroupOnlineMemberCountChanged",Q.RICH_STATUS_CHANGED="onRichStatusChanged"})(ng||(ng={}));var vg,Dn=ng;(function(Q){Q.LOGOUT="logout",Q.DESTROY="destroy",Q.CLOUD_CONFIG_UPDATE="cloud_config_update",Q.PROFILE_UPDATE="profile_updated",Q.ERROR="error",Q.RECONNECTED="reconnected",Q.FORCE_OFFLINE="im_open_status.stat_forceoffline",Q.COMMERCIAL_CONFIG_PUSH="im_sdk_config_mgr.push_imsdk_purchase_bitsv2",Q.OVERLOAD_PUSH="OverLoadPush.notify2",Q.NEW_MESSAGE="new_message",Q.MESSAGE_PUSH="im_open_push.msg_push",Q.MESSAGE_DELETED="message_deleted",Q.MESSAGE_REVOKED="message_revoked",Q.MESSAGE_MODIFIED="message_modified",Q.SOCKET_DISCONNECTED="socket_disconnected",Q.CONVERSATION_UPDATED="conversation_updated",Q.TOPIC_MESSAGE_DELETED="topic_message_deleted",Q.TOPIC_MESSAGE_REVOKED="topic_message_revoked",Q.TOPIC_MESSAGE_MODIFIED="topic_message_modified",Q.TOPIC_NEW_MESSAGE="topic_new_message",Q.QUALITY_STAT="quality_stat",Q.SYNC_CONVERSATION_LIST="sync_conversation_list",Q.HISTORY_MESSAGE_FETCHED="history_message_fetched"})(vg||(vg={}));var yr,Ii=vg;(function(Q){Q.NEW_INVITATION_RECEIVED="newInvitationReceived",Q.INVITEE_ACCEPTED="ts_invitee_accepted",Q.INVITEE_REJECTED="ts_invitee_rejected",Q.INVITATION_CANCELLED="ts_invitation_cancelled",Q.INVITATION_TIMEOUT="ts_invitation_timeout",Q.INVITATION_MODIFIED="ts_invitation_modified"})(yr||(yr={}));var so=yr;const Jc=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 Rg;(function(Q){Q.UNSENT="unSend",Q.SUCCESS="success",Q.FAIL="fail"})(Rg||(Rg={}));const Or={modify:Ii.MESSAGE_MODIFIED,delete:Ii.MESSAGE_DELETED,revoke:Ii.MESSAGE_REVOKED};var fc;(function(Q){Q[Q.FORWARD=0]="FORWARD",Q[Q.BACKWARD=1]="BACKWARD"})(fc||(fc={}));const Hc=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:Rg,Direction:fc}),rg={[Or.modify]:Ii.TOPIC_MESSAGE_MODIFIED,[Or.delete]:Ii.TOPIC_MESSAGE_DELETED,[Or.revoke]:Ii.TOPIC_MESSAGE_REVOKED},pu={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"},uE=Object.assign({},pu),wg={CONV_C2C:"C2C",CONV_GROUP:"GROUP",CONV_TOPIC:"TOPIC",CONV_SYSTEM:"@TIM#SYSTEM"},ba=Object.assign(Object.assign(Object.assign(Object.assign({},wg),{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"}),yc=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"}),EE={GRP_WORK:"Private",GRP_PUBLIC:"Public",GRP_MEETING:"ChatRoom",GRP_AVCHATROOM:"AVChatRoom",GRP_COMMUNITY:"Community",GRP_ROOM:"Room",GRP_LIVE:"Live"},ka={COMMUNITY:"@TGS#_",TOPIC:"@TOPIC#_"},oa={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},_g=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},EE),{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:ka,GROUP_TIPS_OPERATION_TYPE:oa}),iI={IOS_OFFLINE_PUSH_NO_SOUND:"push.no_sound",IOS_OFFLINE_PUSH_DEFAULT_SOUND:"default"},Cs=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},Jc),Hc),uE),ba),yc),_g),iI),{NET_STATE_CONNECTING:"connecting",NET_STATE_DISCONNECTED:"disconnected",NET_STATE_CONNECTED:"connected"}),ko={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},ua={BASIC:"1",STANDARD:"2",PROFESSIONAL:"3",NODE:"4"},sr={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"},Pt={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"},Ht={[sr.SYNC_SERVER_INFO_AFTER_RE_ONLINE]:[{stepId:Pt.USER_STATUS_UPDATE},{stepId:Pt.GROUP_ATTRIBUTE_CACHE_CLEAR},{stepId:Pt.UNREAD_MESSAGE_SYNC,dependency:Pt.C2C_HISTORY_MESSAGE_RECOVER},{stepId:Pt.CONVERSATION_RECOVER},{stepId:Pt.HISTORY_MESSAGE_RECOVER,dependency:Pt.CONVERSATION_RECOVER},{stepId:Pt.BLACKLIST_RECOVER},{stepId:Pt.FRIEND_RECOVER},{stepId:Pt.FRIEND_APPLICATION_LIST_RECOVER},{stepId:Pt.GROUP_REVOKED_NOTICE_RECOVER,dependency:Pt.HISTORY_MESSAGE_RECOVER},{stepId:Pt.GROUP_TIPS_RECOVER,dependency:Pt.HISTORY_MESSAGE_RECOVER},{stepId:Pt.TOPIC_REQUEST_INFO_RESET},{stepId:Pt.HANDLE_C2C_REVOKED_MESSAGE_FROM_SYNC_UNREAD,dependency:Pt.UNREAD_MESSAGE_SYNC},{stepId:Pt.HANDLE_GROUP_TIPS_FROM_SYNC_UNREAD,dependency:Pt.UNREAD_MESSAGE_SYNC},{stepId:Pt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Pt.UNREAD_MESSAGE_SYNC,Pt.CONVERSATION_RECOVER]},{stepId:Pt.EMIT_C2C_MESSAGE_EVENT,dependency:[Pt.UNREAD_MESSAGE_SYNC,Pt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED],skipIfDependencyMissing:!1},{stepId:Pt.C2C_HISTORY_MESSAGE_RECOVER,dependency:Pt.CONVERSATION_RECOVER},{stepId:Pt.STREAM_MESSAGE_RECOVER}],[sr.SYNC_SERVER_INFO_AFTER_LOGIN]:[{stepId:Pt.COMMERCIAL_CONFIG_UPDATE},{stepId:Pt.CLOUD_CONFIG_SYNC},{stepId:Pt.USER_PROFILE_SYNC},{stepId:Pt.UNREAD_MESSAGE_SYNC},{stepId:Pt.FRIEND_AND_BLACKLIST_SYNC},{stepId:Pt.GROUP_LIST_SYNC},{stepId:Pt.CONVERSATION_LIST_SYNC},{stepId:Pt.SIGNALING_MESSAGE_RECOVER,dependency:Pt.UNREAD_MESSAGE_SYNC},{stepId:Pt.UPDATE_TOPIC_AFTER_UNREAD_SYNC_FINISHED,dependency:[Pt.UNREAD_MESSAGE_SYNC]},{stepId:Pt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Pt.UNREAD_MESSAGE_SYNC,Pt.CONVERSATION_LIST_SYNC]},{stepId:Pt.CONVERSATION_UPDATE_AFTER_GROUP_LIST_SYNC_FINISHED,dependency:[Pt.GROUP_LIST_SYNC,Pt.CONVERSATION_LIST_SYNC]},{stepId:Pt.CONVERSATION_GROUP_LIST_SYNC},{stepId:Pt.CONVERSATION_GROUP_UPDATE,dependency:[Pt.CONVERSATION_LIST_SYNC,Pt.CONVERSATION_GROUP_LIST_SYNC]},{stepId:Pt.QUALITY_REPORT}],[sr.RECEIVE_C2C_NEW_MESSAGE]:[{stepId:Pt.HANDLE_C2C_NEW_MESSAGE},{stepId:Pt.UNREAD_MESSAGE_SYNC},{stepId:Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Pt.HANDLE_C2C_NEW_MESSAGE},{stepId:Pt.EMIT_C2C_MESSAGE_EVENT,dependency:[Pt.HANDLE_C2C_NEW_MESSAGE,Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1},{stepId:Pt.CONVERSATION_UPDATE_AFTER_UNREAD_SYNC_FINISHED,dependency:[Pt.UNREAD_MESSAGE_SYNC]}],[sr.RECEIVE_GROUP_NEW_MESSAGE]:[{stepId:Pt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Pt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Pt.UPDATE_GROUP_NEXT_SEQUENCE,dependency:Pt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Pt.UPDATE_TOPIC_BY_RECEIVE_NEW_MESSAGE,dependency:Pt.HANDLE_GROUP_NEW_MESSAGE},{stepId:Pt.EMIT_GROUP_MESSAGE_EVENT,dependency:[Pt.HANDLE_GROUP_NEW_MESSAGE,Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE],skipIfDependencyMissing:!1}],[sr.RECEIVE_GROUP_TIPS_NOTIFICATION]:[{stepId:Pt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,dependency:Pt.HANDLE_GROUP_TIPS_NOTIFICATION},{stepId:Pt.EMIT_GROUP_TIPS_EVENT,dependency:[Pt.CREATE_OR_UPDATE_CONVERSATION_BY_RECEIVE_NEW_MESSAGE,Pt.HANDLE_GROUP_TIPS_NOTIFICATION],skipIfDependencyMissing:!1}]},Tg={MESSAGE_SEND_SUCCESS_RATE:"messageSendSuccessRate"},oI={TOTAL_COUNT:"sendMessageTotalCount",SUCCESS_COUNT:"sendMessageSuccessCount",FAILED_COUNT:"sendMessageFailedCount",SEND_COST:"sendMessageCost"},nr=["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 UI=Object.freeze({__proto__:null,ERROR_CODE:ko,InnerEvent:Ii,NEED_LOG_API:nr,OuterConstant:Cs,OuterEvent:Dn,PUSH:iI,QUALITY_METRICS:Tg,SDK_EDITION:ua,SDK_INFO:{VERSION:"1.7.3",APPID:537048168},SEND_MESSAGE_STAT:oI,SignalingEvent:so,WEB_PUSH_ACCOUNT_TYPE:1,WORKFLOW_DEFINITIONS:Ht,WORKFLOW_NAME:sr,WORKFLOW_STEP:Pt}),Wa,sa,un;(function(Q){Q[Q.USER_INITIATED=0]="USER_INITIATED",Q[Q.KICKED_OUT=1]="KICKED_OUT"})(Wa||(Wa={})),function(Q){Q[Q.multipleAccount=1]="multipleAccount",Q[Q.multipleDevice=2]="multipleDevice",Q[Q.restApi=3]="restApi"}(sa||(sa={})),function(Q){Q[Q.multipleDevice=3002]="multipleDevice",Q[Q.multipleAccount=3003]="multipleAccount",Q[Q.usersigExpired=70001]="usersigExpired",Q[Q.restApi=20002]="restApi"}(un||(un={}));const Sn={[sa.multipleAccount]:"multipleAccount",[sa.multipleDevice]:"multipleDevice",[sa.restApi]:"REST_API_Kick",[un.multipleAccount]:"multipleAccount",[un.multipleDevice]:"multipleDevice",[un.restApi]:"REST_API_Kick",[un.usersigExpired]:"userSigExpired"},mu="login_online_presence_task",{ERROR:Ng,DESTROY:La,FORCE_OFFLINE:qc}=Ii,{KICKED_OUT_MULT_ACCOUNT:FI,KICKED_OUT_MULT_DEVICE:dE,KICKED_OUT_REST_API:sI,ACCOUNT_A2KEY_EXPIRED:fu,MSG_A2KEY_EXPIRED:Sl}=ko;class Dc{init(){const{notificationCenter:h}=fe;h.subscribeInnerEvent(qc,this._handleForceOfflineFromServerPush,this),h.subscribeInnerEvent(Ng,Sl,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),h.subscribeInnerEvent(Ng,fu,this._handleForceOfflineFromResponse,this,this._isChatLoginEvent),h.subscribeInnerEvent(Ng,FI,this._handleForceOfflineFromResponse,this),h.subscribeInnerEvent(Ng,dE,this._handleForceOfflineFromResponse,this),h.subscribeInnerEvent(Ng,sI,this._handleForceOfflineFromResponse,this),h.subscribeInnerEvent(La,this._dispose,this)}_handleForceOfflineFromServerPush(h){var v;if(((v=fe.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)===!0){const{EventArray:N=[]}=h?.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(h){return h.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(h){const{errorCode:v}=h;this._processKickedOutReasonInfo({kickedOutReasonCode:v})}_processKickedOutReasonInfo(h){return pA(this,void 0,void 0,function*(){const{kickedOutReasonCode:v}=h,{ssoLog:N,utils:{safeStringify:O}}=fe;try{this._logKickedOutEvent(h),this._shouldLogoutAfterKickedOut(v)?yield fe.login.loginAction.logout(Wa.KICKED_OUT):fe.login.loginAction.handleLogoutCompleted()}catch(z){N.debug("_processKickedOutReasonInfo",` fail ${O(z)}`)}finally{fe.notificationCenter.emitOuterEvent(Dn.KICKED_OUT,{data:{type:Sn[v]},name:Dn.KICKED_OUT})}})}_logKickedOutEvent(h){const{kickedOutReasonCode:v,newInstanceInfo:N={}}=h,O=`type:${Sn[v]} newInstanceInfo: ${JSON.stringify(N)}`;fe.ssoLog.warn("kickedOut",O)}_isKickedOut(h){return[sa.multipleAccount,sa.multipleDevice,sa.restApi].includes(h)}_isChatLoginEvent(h){const{requestHead:v}=h||{};return v?.idtype!==1}_shouldLogoutAfterKickedOut(h){return![un.usersigExpired,sa.restApi].includes(h)}_isCurrentInstanceKickedOut(h){const{isLoggedIn:v,statusInstanceId:N}=fe.store.get("login")||{};return v===!0&&h===N}_dispose(){const{notificationCenter:h}=fe;h.unSubscribeInnerEvent(qc,this._handleForceOfflineFromServerPush,this),h.unSubscribeInnerEvent(Ng,fu,this._handleForceOfflineFromResponse,this),h.unSubscribeInnerEvent(Ng,Sl,this._handleForceOfflineFromResponse,this),h.unSubscribeInnerEvent(Ng,FI,this._handleForceOfflineFromResponse,this),h.unSubscribeInnerEvent(Ng,dE,this._handleForceOfflineFromResponse,this),h.unSubscribeInnerEvent(Ng,sI,this._handleForceOfflineFromResponse,this),h.unSubscribeInnerEvent(La,this._dispose,this)}}function yu(Q){return pA(this,void 0,void 0,function*(){const h="im_open_status.wslogin",v=fe.common.generateProtocolData({servcmd:h,data:{State:"Online",is_web_uniapp:0,InstType:0,CustomInfo:Q}}),N=`${v.head.seq}${h}`,O=yield fe.channel.sendPacket(v,{timeout:9e4,requestId:N});if(O){const{HelloInterval:z,InstId:X,TinyId:rA,TimeStamp:DA,CustomStatus:GA,PurchaseBits:JA,A2Key:ee,RichMsgAuthKey:ue,ErrorCode:He,ErrorInfo:At,ActionStatus:st}=O;return{helloInterval:z,instanceID:X,tinyID:rA,timeStamp:DA,customStatus:GA,purchaseBits:JA,a2Key:ee,authKey:ue,errorCode:He,errorInfo:At,actionStatus:st}}})}function Du(){const{store:Q}=fe;return la(Q.get("instance").sdkAppId)!==ct.CHINA}function Ml(Q){var h;try{const v=Zi.getStorage("errorMessage");if(!Q||!v)return"";const N=((h=JSON.parse(v))===null||h===void 0?void 0:h.errorMessage)||{},{code:O,replacement1:z="",replacement2:X=""}=Q;if(!O)return"";const rA=Du()?`${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 ss extends Error{constructor(h={}){h.code=h.code||h.errorCode;let{functionName:v="Unknown",code:N,message:O="",data:z="",moreMessage:X="",errorMessage:rA=""}=h;rA=(N?Ml(h):"")||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 as(Q,h){var v;if(Q&&((v=fe.store.get("login"))===null||v===void 0?void 0:v.isLoggedIn)!==!0)throw new ss({code:ko.USER_NOT_LOGGED_IN,functionName:h})}function td(Q,h,v){if(Array.isArray(Q))for(let N=0;N{return GA===(JA=N,Object.prototype.toString.call(JA).match(/^\[object (.*)\]$/)[1].toLowerCase());var JA})){for(let JA=0;JA{const{interceptor:O,context:z}=N;O.apply(z,[v])})}(Q)}function Dr(Q,h){rI.push({interceptor:Q,context:h})}function Sc(Q){const{params:h,auth:v}=Q;h&&typeof h=="object"&&Object.assign(id,h),v&&typeof v=="object"&&Object.assign(CE,v)}function Kc(Q){return fe.store.get("commercialConfig").get(Q)}class en{constructor(){this._handlers=new Map,this._activeWorkflows=new Map,this._stepStartTimes=new Map,this._logHandlers={start:(h,v)=>{const N=Date.now();v?(this._stepStartTimes.set(`${h}-${v}`,N),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${h}] Step ${v} started at ${new Date(N).toISOString()}`)):(this._workflowStartTimes.set(h,N),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${h}] started at ${new Date(N).toISOString()}`))},success:(h,v)=>{const N=Date.now();if(v){const O=this._stepStartTimes.get(`${h}-${v}`),z=O?N-O:0;this._stepStartTimes.delete(`${h}-${v}`),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${h}] Step ${v} completed successfully at ${new Date(N).toISOString()} (${z}ms)`)}else{const O=this._workflowStartTimes.get(h),z=O?N-O:0;this._workflowStartTimes.delete(h),fe.ssoLog.debug("_executeWorkflowStep",`[Workflow ${h}] completed successfully at ${new Date(N).toISOString()} (${z}ms)`)}},error:(h,v,N)=>{const{ssoLog:O,utils:{safeStringify:z}}=fe,X=Date.now();if(v){const rA=this._stepStartTimes.get(`${h}-${v}`),DA=rA?X-rA:0;this._stepStartTimes.delete(`${h}-${v}`),O.error("_executeWorkflowStep",`[Workflow ${h}] Step ${v} failed at ${new Date(X).toISOString()} (${DA}ms) ${z(N)}`,{error:N})}else{const rA=this._workflowStartTimes.get(h),DA=rA?X-rA:0;this._workflowStartTimes.delete(h),O.error("_executeWorkflowStep",`[Workflow ${h}] failed at ${new Date(X).toISOString()} (${DA}ms) ${z(N)}`,{error:N})}}}}static getInstance(){return en._instance||(en._instance=new en),en._instance}static setInstance(h){en._instance=h}init(){this._initializeWorkflows()}registerWorkflowStep(h,v,N,O){if(!this._handlers.has(h))return void fe.ssoLog.debug("registerWorkflowStep",`Workflow '${h}' not defined in core`);if(!Ht[h].find(X=>X.stepId===v))return void fe.ssoLog.debug("registerWorkflowStep",`Step '${v}' not defined in workflow '${h}'`);const z=this._handlers.get(h);z.has(v)||z.set(v,O?N.bind(O):N)}executeWorkflow(h,v){return pA(this,void 0,void 0,function*(){if(!this._validateWorkflow(h))return;fe.ssoLog.debug("executeWorkflow",`[Workflow ${h}] Started execution at ${new Date().toISOString()}`);const N=Ht[h],O={},z={cancelled:!1};this._activeWorkflows.set(h,{cancelToken:z});try{const X=new Map;N.forEach(DA=>{X.set(DA.stepId,DA)});const rA={workflowName:h,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 JA=()=>{if(z.cancelled)return void DA();this._getExecutableSteps({pendingSteps:rA.pendingSteps,completedSteps:rA.completedSteps,stepMap:rA.stepMap,workflowName:h}).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:h}).filter(ue=>!rA.runningSteps.has(ue)).length===0&&rA.runningSteps.size===0&&(fe.ssoLog.debug("executeWorkflow",`Workflow ${h} completed with some steps skipped due to dependency failures`),DA())},onError:GA,onStepComplete:JA})})};JA()}),fe.ssoLog.debug("executeWorkflow",`[Workflow ${h}] Completed execution at ${new Date().toISOString()}`)}catch(X){fe.ssoLog.error("executeWorkflow",`[Workflow ${h}] Failed execution at ${new Date().toISOString()}`,{error:X})}finally{this._activeWorkflows.delete(h)}})}_executeWorkflowStep(h,v,N){return pA(this,void 0,void 0,function*(){const{workflowName:O,runningSteps:z,stepMap:X,stepResults:rA,data:DA}=v;z.add(h),this._logWorkflowExecution(O,h,"start");try{const GA=X.get(h);let JA=null;GA?.dependency&&(l(GA.dependency)?JA=rA[GA.dependency]:Array.isArray(GA.dependency)&&(JA={},GA.dependency.forEach(ue=>{JA[ue]=rA[ue]})));const ee=this._handlers.get(O).get(h);if(ee){const ue=yield Promise.resolve(ee({data:DA,result:JA}));rA[h]=ue,this._logWorkflowExecution(O,h,"success")}v.completedSteps.add(h)}catch(GA){const JA=`[Workflow].${O}.${h}`,{errorCode:ee,errorInfo:ue=`${JA} failed`}=GA||{},He=new ss({functionName:JA,code:ee,message:ue});fe.ssoLog.error(JA,ue,{error:He}),this._logWorkflowExecution(O,h,"error",GA),N.onError(GA)}finally{z.delete(h),v.pendingSteps.delete(h),N.onStepComplete(),N.onComplete()}})}reset(){this._cancelAllWorkflows()}destroy(){this.reset(),this._handlers.clear()}_initializeWorkflows(){Object.keys(Ht).forEach(h=>{this._handlers.has(h)||this._handlers.set(h,new Map)})}_cancelWorkFlow(h){const v=this._activeWorkflows.get(h);if(!v)return;const{cancelToken:N}=v;N.cancelled=!0,this._activeWorkflows.delete(h)}_cancelAllWorkflows(){Object.keys(Ht).forEach(h=>{this._cancelWorkFlow(h)})}_validateWorkflow(h){return Ht[h]?!!this._handlers.get(h):!1}_getExecutableSteps(h){const{pendingSteps:v,completedSteps:N,stepMap:O,workflowName:z}=h;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(p(DA)){if(DA.filter(JA=>!this._isStepRegistered({workflowName:z,stepId:JA})).length>0&&GA)return!1;for(const JA of DA)if(!N.has(JA))return!1;return!0}return!1})}_isStepRegistered(h){var v;const{workflowName:N,stepId:O}=h;return(v=this._handlers.get(N))===null||v===void 0?void 0:v.has(O)}_logWorkflowExecution(h,v,N,O){this._logHandlers[N](h,v)}}const Rs=new Map,Ea=({type:Q,groupID:h})=>Q===Cs.GRP_COMMUNITY||`${h}`.startsWith(ka.COMMUNITY)&&!`${h}`.includes(ka.TOPIC),zr=(Q="")=>{const h=Q.startsWith("GROUP")?Q.replace("GROUP",""):Q;return h.startsWith(ka.COMMUNITY)&&`${h}`.includes(ka.TOPIC)},jc="openim",od="million_group_open_http_svc";function zg(Q){return pA(this,void 0,void 0,function*(){const{servcmd:h,data:v}=function(z){const{data:X}=z;return ag(X)||hE(X)}(Q)?function(z){let{servcmd:X,data:rA}=z;return hE(rA)?function(DA){const{servcmd:GA,data:JA}=DA;let{GroupId:ee=""}=JA;const ue=ee;return[ee]=ue.split(ka.TOPIC),{servcmd:Zg(GA),data:Object.assign(Object.assign({},JA),{GroupId:ee,TopicId:ue})}}(z):(ag(rA)&&(X=Zg(X)),{servcmd:X,data:rA})}(Q):Q,N=fe.common.generateProtocolData({servcmd:h,data:v}),O=`${N.head.seq}${h}`;return fe.channel.sendPacket(N,{requestId:O,timeout:Q.timeout})})}function ag(Q){const{Type:h,GroupId:v,GroupIdList:N=[]}=Q,O=v||N[0]||"";return Ea({type:h,groupID:O})}function hE(Q){const{GroupId:h=""}=Q;return zr(h)}function Zg(Q){if(Q.includes(jc))return Q;const h=Q.split(".")[1];return`${od}.${h}`}function qn(){var Q;return(Q=fe.store.get("login"))===null||Q===void 0?void 0:Q.userId}const Ar=Q=>p(Q)||y(Q),Ua=(Q,h,v,N)=>{if(!Ar(Q)||!Ar(h))return 0;let O=0;const z=Object.keys(h);let X;for(let rA=0,DA=z.length;rA{if(r(h))return"";if(Q===Cs.MSG_TEXT)return h.text||"";const v=Su[Q];return v?AC(v):""},Wc=[{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}],zc="im_sdk_config_mgr.fetch_config",PI="im_sdk_config_mgr.push_configv2",aI="cloud-config",Zc=2996,Xc=new class{init(Q){this.core=Q}};function Sa(Q){return pA(this,void 0,void 0,function*(){const{sdkAppId:h}=Xc.core.store.get("instance")||{},v=Xc.core.helper.generateProtocolData({servcmd:zc,data:{uint32_sdkappid:h,uint64_version:Q}}),N=`${v.head.seq}${zc}`;return Xc.core.channel.sendPacket(v,{requestId:N})})}var Gg=new class{constructor(){this._core=null,this._expirationTime=0,this._version=0,this._isFetching=!1,this._cmdFrequencyLimitMap=new Map,this._methodCallFrequencyMap=new Map}install(Q){this._core=Q;const{notificationCenter:h,InnerEvent:v,helper:N,constants:{WORKFLOW_NAME:O,WORKFLOW_STEP:z},channel:X}=Q;h.subscribeInnerEvent(PI,this._handlePushedConfig,this),N.registerWorkflowStep(O.SYNC_SERVER_INFO_AFTER_LOGIN,z.CLOUD_CONFIG_SYNC,this._handleLoginSuccess,this),h.subscribeInnerEvent(v.LOGOUT,this._reset,this),h.subscribeInnerEvent(v.DESTROY,this._dispose,this),N.registerExperimentalAPI("getServerConfig",this),this._updateCmdFreqLimitMap(Wc),X.registerBeforeSendInterceptor(this.checkMethodCallOverLimit,this)}getServerConfig(Q){return pA(this,void 0,void 0,function*(){var h;const v={code:0,data:""};return Q&&(v.data=((h=this._core.store.get("cloudConfig"))===null||h===void 0?void 0:h[Q])||""),v})}checkMethodCallOverLimit(Q){if(!this._cmdFrequencyLimitMap.has(Q))return;if(!this._methodCallFrequencyMap.has(Q))return void this._methodCallFrequencyMap.set(Q,{startTime:Date.now(),methodCallCounter:1});const{count:h,interval:v}=this._cmdFrequencyLimitMap.get(Q);let{startTime:N,methodCallCounter:O}=this._methodCallFrequencyMap.get(Q);if(Date.now()-N>1e3*v)this._methodCallFrequencyMap.set(Q,{startTime:Date.now(),methodCallCounter:1});else if(O+=1,this._methodCallFrequencyMap.set(Q,{startTime:N,methodCallCounter:O}),O>h)throw new this._core.helper.ChatError({code:Zc,replacement1:Q})}_handlePushedConfig(Q){return pA(this,void 0,void 0,function*(){const{ssoLog:h,utils:{safeStringify:v}}=this._core;h.info("_handlePushedConfig",v(Q)),yield this._updateCloudConfig(Q)})}_handleLoginSuccess(){return pA(this,void 0,void 0,function*(){const{ssoLog:Q,utils:{safeStringify:h}}=this._core;try{if(this._canFetch()){const v=yield Sa(this._version);Q.info("_fetchCloudConfigIfLogin",h(v)),yield this._updateCloudConfig(v)}this._core.helper.taskScheduler.addTask({id:aI,intervalMs:1e3,callback:this._fetchCloudConfigIfReady,context:this})}catch(v){Q.debug("_fetchCloudConfigIfLogin",h(v))}})}_fetchCloudConfigIfReady(){return pA(this,void 0,void 0,function*(){const{ssoLog:Q,utils:{safeStringify:h}}=this._core;if(this._canFetch())try{const v=yield Sa(this._version);Q.info("_fetchCloudConfigIfReady",h(v)),yield this._updateCloudConfig(v)}catch(v){Q.error("_fetchCloudConfigIfReady",h(v))}})}_updateCloudConfig(Q){return pA(this,void 0,void 0,function*(){const h=this._parseCloudConfig(Q);h&&(this._core.store.set("cloudConfig",h),yield this._parseCmdFreqLimit(),this._core.notificationCenter.emitInnerEvent(this._core.InnerEvent.CLOUD_CONFIG_UPDATE,h),this._core.notificationCenter.emitOuterEvent(this._core.OuterEvent.SERVER_CONFIG_UPDATED,{name:this._core.OuterEvent.SERVER_CONFIG_UPDATED,data:{config:h}}))})}_canFetch(){const{isLoggedIn:Q}=this._core.store.get("login")||{};return Q&&!this._isFetching&&Date.now()>=this._expirationTime}_parseCloudConfig(Q){const{int32_error_code:h,str_error_message:v,str_json_config:N,uint32_expired_time:O,uint32_sdkappid:z,uint64_version:X}=Q;let rA=null;if(h===0){if(this._version!==X)try{rA=JSON.parse(N),this._version=X}catch{}this._expirationTime=Date.now()+1e3*O}else this._expirationTime=h===void 0?Date.now()+36e5:Date.now()+12e4;return rA}_parseCmdFreqLimit(){return pA(this,void 0,void 0,function*(){var Q;let h=(Q=yield this.getServerConfig("cmd_frequency_limit"))===null||Q===void 0?void 0:Q.data;const{isEmpty:v}=this._core.utils;if(!v(h))try{h=JSON.parse(h),this._updateCmdFreqLimitMap(h)}catch(N){console.warn(N)}})}_updateCmdFreqLimitMap(Q){Q.forEach(h=>{this._cmdFrequencyLimitMap.set(h.cmd,{interval:h.interval,count:h.count})})}_reset(){this._core.helper.taskScheduler.removeTask(aI),this._core.store.clear("cloudConfig"),this._updateCmdFreqLimitMap(Wc),this._methodCallFrequencyMap.clear(),this._expirationTime=0,this._version=0,this._isFetching=!1}_dispose(){const{notificationCenter:Q,InnerEvent:h}=this._core;Q.unSubscribeInnerEvent(PI,this._handlePushedConfig,this),Q.unSubscribeInnerEvent(h.LOGOUT,this._reset,this),Q.unSubscribeInnerEvent(h.DESTROY,this._dispose,this),this._reset()}};class fs{constructor(h=0,v=0){this.high=h,this.low=v}equal(h){return h!==null&&this.low===h.low&&this.high===h.high}toString(){const h=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 h+v}}const Kn={SEARCH_GRP_SNS:new fs(0,Math.pow(2,1)).toString(),AV_HISTORY_MSG:new fs(0,Math.pow(2,2)).toString(),GRP_COMMUNITY:new fs(0,Math.pow(2,3)).toString(),MSG_TO_SPECIFIED_GRP_MBR:new fs(0,Math.pow(2,4)).toString(),AV_MBR_LIST:new fs(0,Math.pow(2,6)).toString(),USER_STATUS:new fs(0,Math.pow(2,7)).toString(),CONV_MARK:new fs(0,Math.pow(2,9)).toString(),CONV_GROUP:new fs(0,Math.pow(2,10)).toString(),AV_BAN_MBR:new fs(0,Math.pow(2,11)).toString(),MSG_EXT:new fs(0,Math.pow(2,13)).toString(),GRP_COUNTER:new fs(0,Math.pow(2,15)).toString(),PLUGIN_TRANSLATE:new fs(Math.pow(2,6)).toString(),PLUGIN_VOICE_TO_TEXT:new fs(Math.pow(2,7)).toString(),PLUGIN_CS:new fs(Math.pow(2,8)).toString(),PLUGIN_PUSH:new fs(Math.pow(2,9)).toString(),PLUGIN_BOT:new fs(Math.pow(2,10)).toString(),MSG_REACTION:new fs(Math.pow(2,16)).toString(),FOLLOW:new fs(Math.pow(2,20)).toString()},Mc="CommercialConfig",xI="commercial-config";var YI=new class{constructor(){this._core=null,this._expirationTime=0,this._isFetching=!1,this._featureMap=new Map,this._methodKeyMap=new Map,this._purchaseBits="0"}install(Q){this._core=Q;const{helper:h,notificationCenter:v,constants:{WORKFLOW_NAME:N,WORKFLOW_STEP:O,InnerEvent:z}}=Q;v.subscribeInnerEvent(z.COMMERCIAL_CONFIG_PUSH,this._handlePushedConfig,this),v.subscribeInnerEvent(z.LOGOUT,this._handleLogout,this),v.subscribeInnerEvent(z.DESTROY,this._dispose,this),h.registerWorkflowStep(N.SYNC_SERVER_INFO_AFTER_LOGIN,O.COMMERCIAL_CONFIG_UPDATE,this._syncCommercialConfig,this),Q.helper.registerExperimentalAPI("isCommercialAbilityEnabled",this),Q.helper.registerExperimentalAPI("queryCommercialAbility",this)}isCommercialAbilityEnabled(Q){return pA(this,void 0,void 0,function*(){const h=parseInt(Q,10).toString(2),{length:v}=h;let N,O=!0;for(let z=v-1,X=0;z>=0;z--,X++)if(h.charAt(z)==="1"&&(N=X<32?new fs(0,2**X).toString():new fs(2**(X-32),0).toString(),!this._featureMap.get(N))){O=!1;break}return this._core.ssoLog.debug("isFeatureEnabled",`${Mc}.isFeatureEnabled decimalNumber:${Q} key:${N} ret:${O}`),{code:0,data:{enabled:O}}})}queryCommercialAbility(){return this._purchaseBits}_fetchAndParseCommercialConfig(){return pA(this,void 0,void 0,function*(){var Q;const{ssoLog:h,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:(Q=this._core.store.get("instance"))===null||Q===void 0?void 0:Q.sdkAppId}});O&&(this._parseCommercialConfig(O),this._core.store.set("commercialConfig",this._methodKeyMap))}catch(O){h.error("_fetchAndParseCommercialConfig",v(O))}finally{this._isFetching=!1}})}_syncCommercialConfig(Q){return pA(this,void 0,void 0,function*(){const{purchaseBits:h}=Q?.data||{};h&&(this._parsePurchaseBits(h),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 Q;const h=(Q=this._core.store.get("login"))===null||Q===void 0?void 0:Q.isLoggedIn,v=Date.now()>=this._expirationTime;return h&&!this._isFetching&&v}_handlePushedConfig(Q){Q?.body&&(this._parseCommercialConfig(Q.body),this._core.store.set("commercialConfig",this._methodKeyMap))}_fetchCommercialConfigIfReady(){return pA(this,void 0,void 0,function*(){this._canFetch()&&(yield this._fetchAndParseCommercialConfig())})}_parseCommercialConfig(Q){const{ssoLog:h}=this._core;if(typeof Q!="object")return;const{int32_error_code:v,str_error_message:N,str_purchase_bits:O,uint32_expired_time:z}=Q;v===0?(this._parsePurchaseBits(O),this._expirationTime=Date.now()+1e3*z):v===void 0?(h.warn("_parseCommercialConfig",`${Mc}._parseCommercialConfig failed. Invalid message format:`,Q),this._expirationTime=Date.now()+36e5):(h.warn("_parseCommercialConfig",`${Mc}._parseCommercialConfig errorCode:${v} errorMessage:${N}`),this._expirationTime=Date.now()+12e4)}_isValidPurchaseBits(Q){return Q&&typeof Q=="string"&&Q.length>=1&&Q.length<=64&&/[01]{1,64}/.test(Q)}_parsePurchaseBits(Q){const{ssoLog:h,utils:{safeStringify:v}}=this._core;if(this._isValidPurchaseBits(Q)){this._purchaseBits=Q,this._featureMap.clear(),this._methodKeyMap.clear();let N=null;for(let O=Q.length-1,z=0;O>=0;O--,z++)if(N=z<32?new fs(0,2**z).toString():new fs(2**(z-32),0).toString(),Q[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 h.warn("_parsePurchaseBits",`${Mc}.parsePurchaseBits invalid purchases:${v(Q)}`)}_getKeyByValue(Q,h){const v=Object.entries(Q).find(([N,O])=>O===h);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(xI),this._core.store.set("commercialConfig",{}),this._expirationTime=0,this._isFetching=!1,this._featureMap.clear(),this._purchaseBits="0"}},BE=new class{constructor(){this._core=null,this._serverOverloadInfoMap=new Map}install(Q){this._core=Q;const{notificationCenter:h,InnerEvent:v,channel:N}=this._core;h.subscribeInnerEvent(v.OVERLOAD_PUSH,this._handleOverLoadPush,this),h.subscribeInnerEvent(v.LOGOUT,this._reset,this),h.subscribeInnerEvent(v.DESTROY,this._dispose,this),N.registerBeforeSendInterceptor(this.checkServerOverload,this)}checkServerOverload(Q){if(!this._serverOverloadInfoMap.has(Q))return;const{overloadStartTimestamp:h,delaySeconds:v}=this._serverOverloadInfoMap.get(Q);if(Date.now()-h<=1e3*v)throw new this._core.helper.ChatError({functionName:Q,message:"service is busy, please try again later"});this._serverOverloadInfoMap.delete(Q)}_handleOverLoadPush(Q){const{OverLoadServCmd:h,DelaySecs:v}=Q;this._serverOverloadInfoMap.set(h,{overloadStartTimestamp:Date.now(),delaySeconds:v})}_reset(){this._serverOverloadInfoMap.clear()}_dispose(){this._reset();const{notificationCenter:Q,InnerEvent:h}=this._core;Q.unSubscribeInnerEvent(h.OVERLOAD_PUSH,this._handleOverLoadPush,this),Q.unSubscribeInnerEvent(h.LOGOUT,this._reset,this),Q.unSubscribeInnerEvent(h.DESTROY,this._dispose,this)}},zC=new class{constructor(){this.name="ConfigCenter"}install(Q){Xc.init(Q),Gg.install(Q),YI.install(Q),BE.install(Q)}},eC=new class{constructor(){this.name="ErrorMessage",this._core=null}install(Q){return pA(this,void 0,void 0,function*(){if(this._core=Q,this._canFetch()){const h=yield this._fetchErrorMessage();if(!h)return;const v=this._parseResponse(h);this._saveErrorMessage(v)}})}_canFetch(){const Q=this._core.store.getStorage("errorMessage");return!Q||this._isExpired(Q)}_saveErrorMessage(Q){this._core.store.setStorage("errorMessage",{errorMessage:Q,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(Q){console.error(Q)}})}_isExpired(Q){if(!Q)return!0;const{errorMessageSavedTime:h}=Q;return h&&new Date().getTime()-h>=6048e5}_parseResponse(Q){if(typeof Q=="string"){const h=Q.split(`; +`),v={},N=new RegExp(/'/g);for(let O=0;O{var ao,zi,ui;const Oo=function($o,Qi){const{From_Account:Ki,From_AccountHeadurl:js,From_AccountNick:we,IsNeedReadReceipt:vt,MsgBody:FA,MsgClientTime:Wt,MsgRandom:En,MsgSeq:Zt,MsgTimeStamp:Is,SendMsgControl:vi,SupportMessageExtension:Co,To_Account:Et,TinyId:Ct,MsgCheckResult:Ig,CloudCustomData:bs,IsPeerRead:ji,MsgFlagBits:Yr,MsgVersion:ic,EventArray:es}=$o;return{from:Ki,avatar:js,nick:we,needReadReceipt:vt===1,readReceiptSentByPeer:ji,clientTime:Wt,messageFlagBits:Yr,random:En,sequence:Zt,time:Is,messageControlInfo:vi,isSupportExtension:Co,to:Et,tinyID:Ct,checkResult:Ig,cloudCustomData:bs,messageVersion:ic,eventArray:es,elements:Qi.message.messageHelper.parseServerPushMessageElement(FA)}}(Ui,st);if(!((ui=(zi=(ao=Ui?.EventArray)===null||ao===void 0?void 0:ao[0])===null||zi===void 0?void 0:zi.hasOwnProperty)===null||ui===void 0)&&ui.call(zi,"C2cNotifyMsgArray"))xt.push(...function($o){var Qi;const Ki=[];return(Qi=$o.EventArray)===null||Qi===void 0||Qi.forEach(js=>{var we,vt;const{C2cNotifyMsgArray:FA}=js,Wt=(vt=(we=FA?.[0])===null||we===void 0?void 0:we.WithdrawC2cMsgNotify)===null||vt===void 0?void 0:vt.C2cWithdrawInfoArray;Array.isArray(Wt)&&Ki.push(...Wt)}),Ki}(Ui));else{const $o=st.message.messageFactory.createMessage(Object.assign(Object.assign({},Oo),{conversationType:"C2C",flow:"in"})),{elements:Qi}=Oo;$o.setElement(Qi),Gt.push($o)}}),{unreadMessageList:Gt,revokedMessageList:xt}}(DA.MsgList,h);return{syncFlag:DA?.SyncFlag,unreadMessageList:ue,revokedMessageList:He,unreadCountList:GA,overflowUnreadCountList:JA,cookie:DA?.Cookie,groupTipList:ee}}catch(DA){console.warn(DA)}})}var $c,bg;(function(Q){Q[Q.START_SYNC=0]="START_SYNC",Q[Q.SYNCING=1]="SYNCING",Q[Q.SYNC_COMPLETE=2]="SYNC_COMPLETE"})($c||($c={})),function(Q){Q[Q.LOGIN_SUCCESS=0]="LOGIN_SUCCESS",Q[Q.NEW_MESSAGE_RECEIVED=1]="NEW_MESSAGE_RECEIVED"}(bg||(bg={}));var no=new class{constructor(){this.name="UnreadMessageSynchronizer",this._unreadDBMessageMap=new Map,this._cookie="",this._localConversationIDListBeforeDisconnect=[]}install(Q){this._core=Q;const{constants:h}=Q;Q.helper.registerWorkflowStep(h.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_RE_ONLINE,h.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterReOnline,this),Q.helper.registerWorkflowStep(h.WORKFLOW_NAME.RECEIVE_C2C_NEW_MESSAGE,h.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterNewMessageReceived,this),Q.helper.registerWorkflowStep(h.WORKFLOW_NAME.SYNC_SERVER_INFO_AFTER_LOGIN,h.WORKFLOW_STEP.UNREAD_MESSAGE_SYNC,this._syncUnreadDBMessageAfterLogin,this),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.SOCKET_DISCONNECTED,this._handleDisconnect,this),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.LOGOUT,this._reset,this),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.DESTROY,this._dispose,this)}_syncUnreadMessage(Q){return pA(this,void 0,void 0,function*(){const{isAfterReOnline:h=!1,isAfterNewMessageReceived:v=!1,isAfterLogin:N=!1}=Q||{};let O=$c.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?bg.NEW_MESSAGE_RECEIVED:bg.LOGIN_SUCCESS});if(!GA)break;const{unreadMessageList:JA=[],revokedMessageList:ee=[],overflowUnreadCountList:ue,unreadCountList:He,groupTipList:At}=GA;if(this._cookie=GA?.cookie||"",O=GA?.syncFlag,this._parseAndSaveUnreadMessageList(JA),rA.push(...ee),this._updateConversationUnreadOptions({unreadCountList:He,overflowUnreadCountList:ue,conversationUpdateFieldList:z}),Array.isArray(At)&&X.push(...At),h){const{messages:st}=this._handleNewMessageList(JA);DA.push(...st)}}return h?{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(Q){return pA(this,void 0,void 0,function*(){if(Q.data.Flag===1)return this._syncUnreadMessage({isAfterNewMessageReceived:!0})})}_updateConversationUnreadOptions(Q){const{unreadCountList:h,overflowUnreadCountList:v,conversationUpdateFieldList:N}=Q,{constants:{OuterConstant:{CONV_C2C:O,CONV_SYSTEM:z}}}=this._core;h?.forEach(X=>{const{From_Account:rA,UnreadCount:DA}=X;if(rA!==z){const GA=N.find(({conversationID:JA})=>JA===`${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(Q){var h;const{messageDataHandler:v}=this._core.message||{},N=(h=this._core.store.get("login"))===null||h===void 0?void 0:h.userId,{from:O,nick:z,avatar:X,conversationID:rA=""}=Q;if(O!==N){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}):(Q.nick=GA,Q.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(Q){const{messageDataHandler:h}=this._core.message||{},v=new Map,N=[];return Q.forEach(O=>{this._updateMessageProfile(O);let z=O.isModified===1;if(h.isMessageSentByCurrentInstance(O)?O.isModified=z:z=!1,O.isOnlineMessage())O._onlineOnlyFlag=!0,h.isMessageSentByCurrentInstance(O)||N.push(O);else if(this._shouldStoreUnreadMessage(O)){if(h.storeConversationMessage(O)){const{conversationID:X,conversationType:rA,conversationSubType:DA,flow:GA,_isExcludedFromUnreadCount:JA,_isExcludedFromLastMessage:ee}=O,ue=ee?"":O;v.has(X)?(v.get(X).lastMessage=ue,GA==="in"&&(JA||v.get(X).unreadCount++)):v.set(X,{conversationID:X,type:rA,subType:DA,unreadCount:JA||GA!=="in"?0:1,lastMessage:ue})}h.isMessageSentByCurrentInstance(O)&&!z||N.push(O)}}),{messages:N,conversationOptions:v}}_shouldStoreUnreadMessage(Q){var h;const{conversationID:v}=Q,{message:N,appStore:O,utils:{isEmpty:z}}=this._core||{},X=Array.from(((h=O.conversationStore.getConversationMap())===null||h===void 0?void 0:h.keys())||[]),rA=this._getLocalLastMessageTime(v);return!N.messageDataHandler.isInMessageList(Q)&&X.includes(v)&&this._localConversationIDListBeforeDisconnect.includes(v)&&!z(rA)}_fetchUnreadDBMessage(Q){return pA(this,void 0,void 0,function*(){const{ssoLog:h,utils:{safeStringify:v}}=this._core;try{h.debug("_fetchUnreadDBMessage",`unread-message-synchronizer._fetchUnreadDBMessage options:${v(Q)}`);const O=yield ZC(Q,this._core);if(!O)return null;const{syncFlag:z,unreadMessageList:X,revokedMessageList:rA,cookie:DA,unreadCountList:GA,overflowUnreadCountList:JA,groupTipList:ee}=O;return this._parseAndSaveUnreadMessageList(X),{syncFlag:z,cookie:DA,unreadMessageList:X,revokedMessageList:rA,unreadCountList:GA,overflowUnreadCountList:JA,groupTipList:ee}}catch(N){console.log(N)}})}_canContinueSync({cookie:Q,syncFlag:h}){var v;return h===$c.START_SYNC||h===$c.SYNCING&&!(!((v=this._core)===null||v===void 0)&&v.helper.isEmpty(Q))}_parseAndSaveUnreadMessageList(Q){Q.forEach(h=>{const{ID:v}=h;this._unreadDBMessageMap.set(v,h)})}_handleDisconnect(){var Q;const{appStore:h}=this._core;this._localConversationIDListBeforeDisconnect=Array.from(((Q=h.conversationStore.getConversationMap())===null||Q===void 0?void 0:Q.keys())||[])}_getLocalLastMessageTime(Q){const{message:h}=this._core,v=h.messageDataHandler.getLocalMessageList(Q),N=v[v.length-1];return N?.time}_reset(){this._cookie="",this._unreadDBMessageMap.clear()}_dispose(){var Q,h;(Q=this._core)===null||Q===void 0||Q.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.LOGOUT,this._reset,this),(h=this._core)===null||h===void 0||h.notificationCenter.unSubscribeInnerEvent(this._core.InnerEvent.DESTROY,this._dispose,this),this._reset()}},tC=new class{init(Q){var h;this._core=Q,this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.DESTROY,this._dispose,this),document?.addEventListener("visibilitychange",this._visibilityChangeHandler),(h=this._core)===null||h===void 0||h.store.set("activityMonitor",{isActive:!0})}_handleVisibilityChange(){var Q,h;const v=document?.visibilityState==="visible";(Q=this._core)===null||Q===void 0||Q.store.set("activityMonitor",{isActive:v}),(h=this._core)===null||h===void 0||h.notificationCenter.emitInnerEvent("activityStatusChange",{isActive:v})}_reset(){var Q;(Q=this._core)===null||Q===void 0||Q.store.clear("activityMonitor")}_dispose(){document?.removeEventListener("visibilitychange",this._visibilityChangeHandler);const{notificationCenter:Q,InnerEvent:h}=this._core;Q.unSubscribeInnerEvent(h.DESTROY,this._dispose,this),this._reset()}},QE=new class{init(Q){var h;this._core=Q,this._bindAppActivityEvent(),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.DESTROY,this._dispose,this),(h=this._core)===null||h===void 0||h.store.set("activityMonitor",{isActive:!0})}_bindAppActivityEvent(){var Q,h,v,N,O;const{MINI_APP_NAMESPACE:z,IN_TT_MINI_GAME:X,IN_WX_MINI_GAME:rA}=((Q=this._core)===null||Q===void 0?void 0:Q.utils)||{};X||rA?((h=z?.onShow)===null||h===void 0||h.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 Q;(Q=this._core)===null||Q===void 0||Q.store.clear("activityMonitor")}_dispose(){const{notificationCenter:Q,InnerEvent:h}=this._core;Q.unSubscribeInnerEvent(h.DESTROY,this._dispose,this),this._reset()}},pE=new class{init(Q){const{IN_MINI_APP:h,IN_WX_MINI_PLUGIN:v}=Q.helper;v||(h?QE.init(Q):tC.init(Q))}};const nd="none",mE="online";var Al=new class{init(Q){this._core=Q,this._activateNetworkMonitoring(),Q.notificationCenter.subscribeInnerEvent(Q.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(Q){var h,v;const{isConnected:N,networkType:O}=Q;(h=this._core)===null||h===void 0||h.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:mE})}_onOffline(){this._onNetworkStatusChange({isConnected:!1,networkType:nd})}_reset(){var Q;this._deactivateNetworkMonitoring(),(Q=this._core)===null||Q===void 0||Q.store.clear("netWorkMonitor")}_dispose(){var Q,h;(Q=this._core)===null||Q===void 0||Q.notificationCenter.unSubscribeInnerEvent((h=this._core)===null||h===void 0?void 0:h.InnerEvent.DESTROY,this._dispose,this),this._reset()}},gI=new class{init(Q){this._core=Q,this._activateNetworkMonitoring(),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.DESTROY,this._dispose,this)}_activateNetworkMonitoring(){return pA(this,void 0,void 0,function*(){try{const{utils:{MINI_APP_NAMESPACE:Q}}=this._core;this._mpNetworkStatusCallback=this._onNetworkStatusChange.bind(this),Q.onNetworkStatusChange(this._onNetworkStatusChange.bind(this))}catch(Q){console.error(Q)}})}_deactivateNetworkMonitoring(){if(this._mpNetworkStatusCallback!==null){const{utils:{MINI_APP_NAMESPACE:Q}}=this._core;Q.offNetworkStatusChange&&Q.offNetworkStatusChange(this._mpNetworkStatusCallback),this._mpNetworkStatusCallback=null}}_onNetworkStatusChange(Q){var h,v;const{isConnected:N,networkType:O}=Q;(h=this._core)===null||h===void 0||h.store.set("netWorkMonitor",{isNetworkOnline:N,networkType:O}),(v=this._core)===null||v===void 0||v.notificationCenter.emitInnerEvent("networkStatusChange",{isNetworkOnline:N,networkType:O})}_reset(){var Q;this._deactivateNetworkMonitoring(),(Q=this._core)===null||Q===void 0||Q.store.clear("netWorkMonitor")}_dispose(){var Q,h;(Q=this._core)===null||Q===void 0||Q.notificationCenter.unSubscribeInnerEvent((h=this._core)===null||h===void 0?void 0:h.InnerEvent.DESTROY,this._dispose,this),this._reset()}},Mu=new class{init(Q){const{IN_MINI_APP:h}=Q.utils;h?gI.init(Q):Al.init(Q)}},vu=new class{constructor(){this.name="SystemStateMonitor"}install(Q){pE.init(Q),Mu.init(Q)}};const iC=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.*"]),Mr="tui_room_svr.*";var gg=new class{constructor(){this.name="BusinessCommandTransfer",this._transferredCommands=iC}install(Q){this._core=Q;const{notificationCenter:h,InnerEvent:v,helper:N}=Q;h.subscribeInnerEvent(v.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),h.subscribeInnerEvent(v.LOGOUT,this._reset,this),h.subscribeInnerEvent(v.DESTROY,this._dispose,this),h.subscribeInnerEvent("im_open_push.msg_push",h.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this),N.registerExperimentalAPI("sendTRTCCustomData",this,"transferBusinessCommand"),N.registerExperimentalAPI("sendRoomCustomData",this,"transferBusinessCommand")}transferBusinessCommand(Q){return pA(this,void 0,void 0,function*(){const h="transferBusinessCommand";try{const{serviceCommand:v=Mr}=Q||{};if(!this._isValidTransferredCommand(v))throw new this._core.helper.ChatError({code:2995,functionName:h});return{code:0,data:(yield function(O,z){return pA(this,void 0,void 0,function*(){const{helper:X,channel:rA}=z,{serviceCommand:DA=Mr,data:GA}=O||{};let JA={};try{JA=typeof GA=="string"?JSON.parse(GA):GA}catch(He){console.warn(He)}const ee=X.generateProtocolData({servcmd:DA,data:JA}),ue=`${ee.head.seq}${DA}`;return rA.sendPacket(ee,{requestId:ue,shouldRejectOnError:!1})})}(Q,this._core))||{}}}catch(v){throw console.warn(v),new this._core.helper.ChatError({code:v?.errorCode,message:v?.errorInfo,data:{},functionName:h})}})}_onCloudConfigUpdate(Q={}){try{if(typeof Q.rtc_cmd!="string")return;const h=JSON.parse(Q.rtc_cmd);Array.isArray(h)&&(this._transferredCommands=new Set([...this._transferredCommands,...h]))}catch(h){console.log(h)}}_isValidTransferredCommand(Q=""){const h=`${Q?.split(".")[0]}.*`;return this._transferredCommands.has(h)}_onServerPushBusinessCommand(Q){const{OuterEvent:h,notificationCenter:v}=this._core,{MsgContent:N}=Q||{},{ROOM_CUSTOM_DATA_RECEIVED:O}=h;v.emitOuterEvent(O,{name:O,data:N})}_reset(){this._transferredCommands=iC}_dispose(){const{notificationCenter:Q,InnerEvent:h}=this._core;this._reset(),Q.unSubscribeInnerEvent(h.CLOUD_CONFIG_UPDATE,this._onCloudConfigUpdate,this),Q.unSubscribeInnerEvent(h.LOGOUT,this._reset,this),Q.unSubscribeInnerEvent(h.DESTROY,this._dispose,this),Q.unSubscribeInnerEvent("im_open_push.msg_push",Q.InnerEventSubType.BUSINESS_COMMAND,this._onServerPushBusinessCommand,this)}};const vc=new class{init(Q){this.core=Q}};function Ru(Q){return pA(this,void 0,void 0,function*(){var h;const{message:v,user:N,appStore:O,constants:{OuterConstant:z}}=vc.core,X=O.conversationStore.getConversationMap();if(X.has(Q)){const DA=(h=X.get(Q))===null||h===void 0?void 0:h.userProfile;if(DA&&Q.startsWith(z.CONV_C2C)){const{avatar:GA,nick:JA}=DA;vc.core.message.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:Q,latestAvatar:GA,latestNick:JA,isSentByMe:!1})}}const{data:rA}=(yield N.userProfile.getMyProfile())||{};if(rA){const{avatar:DA,nick:GA}=rA;v.messageDataHandler.updateNickAndAvatarOfSentMessage({conversationID:Q,latestAvatar:DA,latestNick:GA,isSentByMe:!0})}})}function Rl(Q){return pA(this,void 0,void 0,function*(){const h=Q.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=vc.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:JA})=>(rA[DA]={nick:GA||"",avatar:JA||""},rA),{}):null})}(h);v&&Q.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 rd=1,Zr=2,cI=20,_n=2500,oC=1,el=300;function ad(Q){return pA(this,void 0,void 0,function*(){var h,v;const{appStore:N,utils:{isEmpty:O},common:{getCurrentUserID:z},notificationCenter:X,OuterEvent:rA,OuterConstant:{CONV_C2C:DA}}=vc.core,{messageList:GA,conversationID:JA}=Q,ee=N.conversationStore.getConversationMap();let ue=(h=ee.get(JA))===null||h===void 0?void 0:h.peerReadTime;if(!ue){const At=JA.replace(DA,""),st=yield function(Gt){return pA(this,void 0,void 0,function*(){const xt={To_Account:Gt};return vc.core.common.buildAndSendPacket({servcmd:"openim.get_peer_read_time",data:xt})})}([At]);if(st){const{ReadTime:Gt}=st;ue=Gt?.[0],ee.has(JA)&&(ee.get(JA).peerReadTime=ue)}}if(ee.has(JA)){const At=(v=ee.get(JA))===null||v===void 0?void 0:v.lastMessage;O(At)||At.fromAccount===z()&&At.lastTime<=ue&&!At.isPeerRead&&(At.isPeerRead=!0,N.conversationStore.updateConversation(JA,{lastMessage:At}))}const He=[];GA.forEach(At=>{At.time<=ue&&!At.isPeerRead&&At.flow==="out"&&(At.isPeerRead=!0,He.push(At))}),He.length>0&&X.emitOuterEvent(rA.MESSAGE_READ_BY_PEER,{name:rA.MESSAGE_READ_BY_PEER,data:He})})}var lI=new class{init(Q){this._core=Q,Q.helper.registerApi({apiName:"getMessageList",context:this}),Q.helper.registerApi({apiName:"getMessageListHopping",context:this}),Q.helper.registerApi({apiName:"clearHistoryMessage",context:this})}getMessageList(Q){return pA(this,void 0,void 0,function*(){try{const{message:h,OuterConstant:{Direction:v,CONV_C2C:N,CONV_GROUP:O},InnerEvent:{HISTORY_MESSAGE_FETCHED:z},notificationCenter:X}=this._core,{conversationID:rA,nextReqMessageID:DA}=Q,GA=cI;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 ee=null;if(rA.startsWith(O)?ee=yield h.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:Number(DA),count:GA,direction:v.FORWARD,shouldMarkCompleted:!0}):rA.startsWith(N)&&(ee=yield h.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,messageID:DA,count:GA,direction:v.FORWARD,shouldMarkCompleted:!0})),ee){const{nextReqMessageIDFromServer:ue,hasNoMoreHistoryMessage:He,messageList:At}=ee,st=h.messageDataHandler.prependLocalMessageList({messageList:At,conversationID:rA});(function(zi){const{appStore:ui,message:Oo,OuterConstant:$o}=vc.core,Qi=ui.conversationStore.getConversation(zi),Ki=Oo.messageDataHandler.getLocalMessageList(zi);if(!Qi||Ki.length===0||zi===$o.CONV_SYSTEM)return;const js=[];for(let vt=0;vtFA.isRevoked).length;we=js.length-Qi.unreadCount-vt}else we=js.length-Qi.unreadCount;for(let vt=0;vtzi.isRevoked);yield Rl(xt),X.emitInnerEvent(z,st);const Ui={nextReqMessageID:He?"":String(ue),messageList:Gt,isCompleted:He},ao=Gt.map(zi=>zi.sequence);return{code:0,data:Ui,successLog:{message:`conversationID: ${rA} nextReqMessageID: ${DA} availableLocalMessagesCount: ${JA} sequenceList: ${JSON.stringify(ao)}`}}}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(h){const{code:v,message:N}=h||{};throw new this._core.helper.ChatError({code:v,message:N,moreMessage:`options: ${this._core.utils.safeStringify(Q)}`})}})}getMessageListHopping(Q){return pA(this,void 0,void 0,function*(){var h,v;const{OuterConstant:{Direction:N,CONV_C2C:O,CONV_GROUP:z},utils:{safeStringify:X}}=this._core,{conversationID:rA,sequence:DA,time:GA,direction:JA=N.FORWARD}=Q,{utils:{isEmpty:ee},message:ue,notificationCenter:He,InnerEvent:{HISTORY_MESSAGE_FETCHED:At}}=this._core;if(![N.BACKWARD,N.FORWARD].includes(JA))throw new this._core.helper.ChatError({message:"direction must be 0 or 1",moreMessage:`options: ${X(Q)}`});let{count:st=cI}=Q;st=st>cI?cI:st;let Gt=null;if(rA.startsWith(z)){if(Gt=yield ue.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:rA,sequence:DA,count:st,direction:JA}),Gt){const{nextReqMessageIDFromServer:xt,hasNoMoreHistoryMessage:Ui,messageList:ao,invisibleSequenceList:zi}=Gt;if(this._core.message.messageDataHandler.storeSparseMessageList(ao),He.emitInnerEvent(At,ao),JA===N.FORWARD){const ui=Ui&&xt<1;return{code:0,data:{messageList:ao,isCompleted:ui,nextMessageSeq:ui?"":xt}}}if(JA===N.BACKWARD){if(ee(ao)&&ee(zi))return{code:0,data:{messageList:[],isCompleted:!0,nextMessageSeq:""}};const ui=((h=ao?.[ao.length-1])===null||h===void 0?void 0:h.sequence)||0,Oo=((v=zi?.[zi.length-1])===null||v===void 0?void 0:v.sequence)||0;return{code:0,data:{messageList:ao.filter($o=>$o.sequence>=DA),isCompleted:!Ui,nextMessageSeq:Ui?Math.max(ui,Oo)+1:""}}}return{code:0,data:Gt}}}else if(rA.startsWith(O)&&(Gt=yield ue.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:rA,count:st+1,time:GA,direction:JA}),Gt)){const{messageList:xt,lastMessageTime:Ui,hasNoMoreHistoryMessage:ao}=Gt;return He.emitInnerEvent(At,xt),ao||(JA===N.FORWARD?xt.shift():xt.pop()),ue.messageDataHandler.storeSparseMessageList(xt),yield ad({messageList:xt,conversationID:rA}),{code:0,data:{messageList:xt,isCompleted:ao,nextMessageTime:ao?"":Ui}}}})}clearHistoryMessage(Q){return pA(this,void 0,void 0,function*(){var h;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(Q);if(!GA)throw new N({code:_n});const JA={fromAccount:O()},{type:ee}=GA;ee===z?(JA.type=rd,JA.toAccount=Q.replace(z,"")):ee===X&&(JA.type=Zr,JA.toGroupID=Q.replace(X,""));try{return yield(h=rA?.setMessageRead)===null||h===void 0?void 0:h.call(rA,{conversationID:Q}),(yield function(He){return pA(this,void 0,void 0,function*(){const{fromAccount:At,type:st,toAccount:Gt,toGroupID:xt}=He,Ui={From_Account:At,Type:st,To_Account:Gt,ToGroupid:xt};return vc.core.common.buildAndSendPacket({servcmd:"recentcontact.clear_msg",data:Ui})})}(JA))&&(DA.messageDataHandler.deleteConversationMessageList(Q),DA.messageHistory.completedHistoryConversations.delete(Q),DA.messageHistory.clearHistoryMessageListFetchAnchors(Q),this._updateConversationLastMessage(Q)),{code:0,data:{conversationID:Q},successLog:{message:`convID:${Q}`}}}catch(ue){const{errorCode:He}=ue;throw new this._core.helper.ChatError({functionName:"clearHistoryMessage",code:He,moreMessage:`convID:${Q}`})}})}_updateConversationLastMessage(Q){const{appStore:h}=this._core;h.conversationStore.updateConversation(Q,{lastMessage:this._generateLastMessage()},{needSort:!0})}_getAvailableLocalMessagesCount({conversationID:Q,nextReqMessageID:h}){const{OuterConstant:{CONV_C2C:v,CONV_GROUP:N}}=this._core,O=this._core.message.messageDataHandler.getLocalMessageList(Q),{length:z}=O;if(!h)return z;let X=-1;return Q?.startsWith(v)?X=O.findIndex(rA=>rA.ID===h):Q?.startsWith(N)&&(X=O.findIndex(rA=>h.includes("-")?rA.ID===h:String(rA.sequence)===h)),X===-1?0:X}_needFetchHistoryMessageList({conversationID:Q,availableLocalMessagesCount:h,targetCount:v}){const{message:N}=this._core;return hh.startsWith(O)?ue.ID===v:String(ue.sequence)===v),JA=ee>N?ee-N:0,DA=ee):JA=rA>N?rA-N:0,GA.messageList=X.slice(JA,ee),GA.isCompleted=DA<=N&&z.messageHistory.completedHistoryConversations.has(h),GA.isCompleted?GA.nextReqMessageID="":GA.nextReqMessageID=this._generateNextReqMessageID({conversationID:h,targetIndex:JA}),h.startsWith(O)&&(yield Ru(h),yield ad({messageList:GA.messageList,conversationID:h})),GA})}_generateNextReqMessageID({conversationID:Q,targetIndex:h}){const v=this._core.message.messageDataHandler.getLocalMessageList(Q);return Q.startsWith("C2C")?v[h].ID:String(v[h].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}}},Fa=new class{constructor(){this._lastMessageSequenceMapOnDisconnect=new Map,this._lastMessageTimeMapOnDisconnect=new Map}init(Q){this._core=Q;const{common:{workflowManager:h},constants:{WORKFLOW_NAME:v,WORKFLOW_STEP:N,InnerEvent:O}}=Q;h.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,N.HISTORY_MESSAGE_RECOVER,this._syncGroupOfflineMessage,this),h.registerWorkflowStep(v.SYNC_SERVER_INFO_AFTER_RE_ONLINE,N.C2C_HISTORY_MESSAGE_RECOVER,this._syncC2COfflineMessage,this),Q.notificationCenter.subscribeInnerEvent(O.SOCKET_DISCONNECTED,this._updateLastMessageSequenceMapOnDisconnect,this)}_syncGroupOfflineMessage(Q){const{conversationList:h}=Q?.result||{},{OuterConstant:v,utils:{isArray:N}}=this._core;if(N(h)){const O=h.filter(z=>z.type===v.CONV_GROUP&&z.groupProfile.type!==v.GRP_AVCHATROOM);return this._recoverGroupHistoryMessage(O)}}_recoverGroupHistoryMessage(Q){return pA(this,void 0,void 0,function*(){const{OuterConstant:h}=this._core,v=[],N=[];return yield Promise.all(Q?.map(O=>pA(this,void 0,void 0,function*(){const{groupProfile:{groupID:z}={},lastMessage:{lastSequence:X}={}}=O,rA=`${h.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(h.CONV_GROUP,""))}))),{recoverRevokeNoticeGroupIDList:v,groupTipList:N}})}_recoverGroupHistoryForConversation(Q){return pA(this,arguments,void 0,function*({conversationID:h,localLastMessageSequence:v,serverLastMessageSequence:N,groupTipList:O}){try{const{utils:{isArray:z,isObject:X,isEmpty:rA},OuterEvent:DA,OuterConstant:GA,notificationCenter:JA,message:ee,appStore:ue,common:{getMessagePreviewText:He,buildLastMessage:At}}=this._core,st=N-v,Gt=Math.min(20,st),xt={},Ui=yield ee.messageHistory.getGroupRoamingMessagesByAnchor({conversationID:h,sequence:v+Gt,direction:GA.Direction.FORWARD,count:Gt}),{nextReqMessageIDFromServer:ao,hasNoMoreHistoryMessage:zi,messageList:ui,serverGroupTipList:Oo}=Ui;z(Oo)&&O.push(...Oo);const $o=zi&&ao<0,Qi=[];if(z(ui)&&(ui.forEach(Ki=>{ee.messageReceiver.groupMessageReceiver.updateMessageProfile(Ki),Ki.from===GA.CONV_SYSTEM&&(Ki.isSystemMessage=!1),ee.messageDataHandler.storeConversationMessage(Ki)&&!rA(Ki.payload)&&(Qi.push(Ki),Ki._isExcludedFromLastMessage||(xt.lastMessage=At(Ki)))}),Qi.length>0&&JA.emitOuterEvent(DA.MESSAGE_RECEIVED,{name:DA.MESSAGE_RECEIVED,data:Qi})),!$o&&ui.length>0){const Ki=ui[ui.length-1].sequence;yield this._recoverGroupHistoryForConversation({conversationID:h,localLastMessageSequence:Ki,serverLastMessageSequence:N,groupTipList:O})}X(xt.lastMessage)&&(xt.lastMessage.messageForShow=He(xt.lastMessage.type,xt.lastMessage.payload),ue.conversationStore.updateConversation(h,xt))}catch(z){this._core.ssoLog.error("_recoverGroupHistoryForConversation",`Recovery failed for conversation:${h}`,{error:z})}})}_updateLastMessageSequenceMapOnDisconnect(){const{message:Q}=this._core,h=Q.messageDataHandler.getContinuousMessagesByConversation();for(const[v,N]of h){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(Q){const{message:h}=this._core;if(this._lastMessageSequenceMapOnDisconnect.has(Q))return this._lastMessageSequenceMapOnDisconnect.get(Q);const v=h.messageDataHandler.getLocalMessageList(Q),N=v[v.length-1];return N?.sequence}_shouldRecoverHistory(Q){const{localLastMessageSequence:h,serverLastMessageSequence:v}=Q;if(typeof h!="number"||typeof v!="number")return!1;const N=v-h;return v!==0&&h>0&&N>=oC&&N{z.type===v.CONV_C2C&&O.push(z)}),this._recoverC2CHistoryMessage(O)}}_recoverC2CHistoryMessage(Q){return pA(this,void 0,void 0,function*(){yield Promise.all(Q?.map(h=>pA(this,void 0,void 0,function*(){const{conversationID:v,lastMessage:{lastTime:N}={}}=h,O=this._getLocalLastMessageTime(v);this._shouldRecoverC2CHistory({localLastMessageTime:O,serverLastMessageTime:N})&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:O,serverLastMessageTime:N}))})))})}_shouldRecoverC2CHistory(Q){const{localLastMessageTime:h,serverLastMessageTime:v}=Q,N=v-h;return h>0&&N>=1&&N<=600}_recoverHistoryForC2CConversation(Q){return pA(this,void 0,void 0,function*(){var h;const{conversationID:v,localLastMessageTime:N,serverLastMessageTime:O}=Q,{utils:{isArray:z,isObject:X,isEmpty:rA,safeStringify:DA},OuterEvent:GA,OuterConstant:JA,notificationCenter:ee,message:ue,appStore:He,common:{getMessagePreviewText:At,buildLastMessage:st}}=this._core;try{const Gt={},xt=yield ue.messageHistory.getC2CRoamingMessagesByAnchor({conversationID:v,direction:JA.Direction.BACKWARD,time:N,count:20});if(rA(xt))return;const{hasNoMoreHistoryMessage:Ui,messageList:ao}=xt,zi=[];z(ao)&&(ao.forEach(Oo=>{ue.messageDataHandler.storeConversationMessage(Oo)&&!rA(Oo.payload)&&(zi.push(Oo),Oo._isExcludedFromLastMessage||(Gt.lastMessage=st(Oo)))}),zi.length>0&&ee.emitOuterEvent(GA.MESSAGE_RECEIVED,{name:GA.MESSAGE_RECEIVED,data:zi}));const ui=(h=ao[ao.length-1])===null||h===void 0?void 0:h.time;!Ui&&ui>O&&(yield this._recoverHistoryForC2CConversation({conversationID:v,localLastMessageTime:ui,serverLastMessageTime:O})),X(Gt.lastMessage)&&(Gt.lastMessage.messageForShow=At(Gt.lastMessage.type,Gt.lastMessage.payload),He.conversationStore.updateConversation(v,Gt))}catch(Gt){this._core.ssoLog.error("_recoverHistoryForC2CConversation",`Recovery failed for conversation:${v} error: ${DA(Gt)}`)}})}_getLocalLastMessageTime(Q){const{message:h}=this._core;if(this._lastMessageTimeMapOnDisconnect.has(Q))return this._lastMessageTimeMapOnDisconnect.get(Q);const v=h.messageDataHandler.getLocalMessageList(Q),N=v[v.length-1];return N?.time}reset(){this._lastMessageSequenceMapOnDisconnect.clear(),this._lastMessageTimeMapOnDisconnect.clear()}dispose(){this.reset()}},sC=new class{constructor(){this.name="HistoryMessage"}install(Q){this._core=Q,vc.init(Q),lI.init(Q),Fa.init(Q),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.LOGOUT,this._reset,this),Q.notificationCenter.subscribeInnerEvent(Q.InnerEvent.DESTROY,this.dispose,this)}dispose(){const{notificationCenter:Q,InnerEvent:h}=this._core;Q.unSubscribeInnerEvent(h.LOGOUT,this._reset,this),Q.unSubscribeInnerEvent(h.DESTROY,this.dispose,this),Fa.dispose()}_reset(){Fa.reset()}},Oa=new class{init(Q){this.core=Q}},Ir=new class{constructor(){this._reportedAtomicStoreIDs=new Set}init(Q){const{helper:{registerExperimentalAPI:h}}=Q;this._core=Q,h("reportModalView",this),h("reportTUIFeatureUsage",this),h("reportRoomEngineEvent",this)}reportModalView(Q){const{ssoLog:h,utils:{safeStringify:v,isString:N}}=this._core;try{if(!N(Q))throw new Error("reportModalView data is not a string");h.createSSOLogData({method:"reportModalView",message:Q,eventType:30}).end(!0)}catch(O){h.debug(`reportModalView Report failed: ${v(O)}`)}}reportTUIFeatureUsage(Q){const{ssoLog:h,utils:{safeStringify:v,isEmpty:N}}=this._core,{atomicStoreID:O}=Q;try{N(O)||this._reportedAtomicStoreIDs.has(O)||(this._core.ssoLog.info("reportTUIFeatureUsage",`atomicStoreID: ${Q.atomicStoreID}`,{method:"reportTUIFeatureUsage",eventType:31,code:O}),this._reportedAtomicStoreIDs.add(O))}catch(z){h.debug(`reportTUIFeatureUsage Report failed: ${v(z)}`)}}reportRoomEngineEvent(Q){const{utils:{safeStringify:h},ssoLog:v}=this._core;try{v.debug(`reportRoomEngineEvent Report: ${h(Q)}`);const{eventId:N,eventCode:O,eventResult:z,eventMessage:X,moreMessage:rA,extensionMessage:DA}=Q;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: ${h(N)}`)}}reset(){this._reportedAtomicStoreIDs.clear()}dispose(){this.reset()}},gd=new class{constructor(){this.name="DataReport"}install(Q){this._core=Q;const{notificationCenter:h,InnerEvent:{LOGOUT:v,DESTROY:N}}=Q;Oa.init(Q),Ir.init(Q),h.subscribeInnerEvent(v,this._reset,this),h.subscribeInnerEvent(N,this._dispose,this)}_reset(){Ir.reset()}_dispose(){const{notificationCenter:Q,InnerEvent:{LOGOUT:h,DESTROY:v}}=this._core;Q.unSubscribeInnerEvent(h,this._reset,this),Q.unSubscribeInnerEvent(v,this._dispose,this),Ir.dispose()}};let wu=ua.STANDARD,ur=[];wu=ua.BASIC,ur=[eC,zC,no,vu,gg,sC,gd];function Rc(Q,h){const{operationType:v,memberInfoList:N,operatorInfo:O}=Q||{};let z={};if(vs(N)?vs(O)||(z=O):v!==oa.JOINED&&v!==oa.KICKED&&v!==oa.ADMIN_SET&&v!==oa.ADMIN_CANCELED||(z=Object.assign({},N[0])),!vs(z)){const{nick:X="",avatar:rA=""}=z;h.nick=X,h.avatar=rA}}const tl=Q=>({lastTime:Q?.time||Q?.lastTime||0,lastSequence:Q?.sequence||Q?.lastSequence||0,fromAccount:Q?.from||Q?.fromAccount||"",messageForShow:OI(Q?.type,Q?.payload),payload:Q?.payload||null,type:Q?.type||"",isRevoked:Q?.isRevoked||!1,cloudCustomData:Q?.cloudCustomData||"",onlineOnlyFlag:Q?._onlineOnlyFlag||!1,nick:Q?.nick||"",nameCard:Q?.nameCard||"",version:Q?.version||0,isPeerRead:Q?.isPeerRead||!1,revoker:Q?.revoker||null});var kg=Object.freeze({__proto__:null,ChatError:ss,WorkflowManager:en,buildAndSendPacket:zg,buildLastMessage:tl,get builtInPlugins(){return ur},checkBusinessCapabilityBits:Kc,deepMerge:Ua,getCurrentUserID:qn,getErrorMessage:Ml,getMessagePreviewText:OI,isC2CConv:Q=>l(Q)&&Q.slice(0,3)===wg.CONV_C2C,isCommunity:Ea,isGroupConv:Q=>l(Q)&&Q.slice(0,5)===wg.CONV_GROUP,isInternational:Du,isTopic:zr,isUnlimitedAVChatRoom:function(){var Q;return!!(!((Q=fe.store.get("instance"))===null||Q===void 0)&&Q.unlimitedAVChatRoom)},liteChatInstanceMap:Rs,registerInterceptor:Dr,registerValidateConfig:Sc,requireAuth:as,get sdkEdition(){return wu},setGroupTipsUserInfo:Rc,t:AC,updateGroupAtInfo:(Q,h)=>{const{CONV_AT_ME:v,CONV_AT_ALL:N,CONV_AT_ALL_AT_ME:O}=Cs;if(function(rA,DA){const{CONV_AT_ME:GA,CONV_AT_ALL:JA,CONV_AT_ALL_AT_ME:ee}=Cs,{groupID:ue,sequence:He}=rA;let At=!1;return Ea({groupID:ue})&&DA.forEach(st=>{st.messageSequence===He&&(st.atTypeArray.includes(GA)&&rA.groupAtType.includes(JA)&&(st.atTypeArray=[ee]),st.atTypeArray.includes(JA)&&rA.groupAtType.includes(GA)&&(st.atTypeArray=[ee],st.__random=rA.__random,st.__sequence=rA.__sequence),At=!0)}),At}(Q,h))return;let z=[...Q.groupAtType];z.includes(v)&&z.includes(N)&&(z=[O]);const X={from:Q.from,groupID:Q.groupID,topicID:Q.topicID,messageSequence:Q.sequence,atTypeArray:z,__random:Q.__random,__sequence:Q.__sequence};h.push(X)},validateAndExecute:vl,validateParameters:td});class Fo{constructor(){this._builtInPlugins=new Set,this._externalPlugins=new Set}static getInstance(){return Fo._instance||(Fo._instance=new Fo),Fo._instance}static setInstance(h){Fo._instance=h}installBuiltInPlugin(h){h&&this._installPlugin(h,this._builtInPlugins)}installExternalPlugin(h){h&&this._installPlugin(h,this._externalPlugins)}clear(){this._builtInPlugins=new Set,this._externalPlugins=new Set}_installPlugin(h,v){let N=[];N=p(h)?h:[h];const O=N.findIndex(X=>X?.name==="AVChatRoom"),z=O>-1?N.splice(O,1):[];N.forEach(X=>{this._isPluginInstalled(X.name)||(X&&me(X.install)?(v.add(X.name),me(X.getInstalledSubPlugins)?(z?.forEach(rA=>v.add(rA?.name)),X.install(Ks.getInstance().exposeApiForPlugin(),z)):X.install(Ks.getInstance().exposeApiForPlugin()),me(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):me(X)?(v.add(X.name),X(Ks.getInstance().exposeApiForPlugin()),me(X.handleLoginSuccess)&&this._isLoggedIn()&&X.handleLoginSuccess()):console.warn('A plugin must either be a function or an object with an "install" function.'))})}_isPluginInstalled(h){return this._builtInPlugins.has(h)||this._externalPlugins.has(h)}_isLoggedIn(){var h;return((h=fe.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)===!0}}var Xg=new class{constructor(){this._conversationMap=new Map}getConversationMap(){return this._conversationMap}getConversation(Q){return this._conversationMap.get(Q)}updateConversation(Q,h,v){const{emit:N=!0,needSort:O=!1}=v||{},z=this._conversationMap.get(Q);z&&!vs(h)&&(Object.keys(h).forEach(X=>{z[X]=h[X]}),N&&fe.notificationCenter.emitInnerEvent(Ii.CONVERSATION_UPDATED,{needSort:O}))}deleteConversation(Q){this._conversationMap.has(Q)&&(this._conversationMap.delete(Q),fe.notificationCenter.emitInnerEvent(Ii.CONVERSATION_UPDATED))}},za=new class{constructor(){this._groupMap=new Map}getGroupMap(){return this._groupMap}getGroup(Q){return this._groupMap.get(Q)}updateGroup(Q,h){const v=this._groupMap.get(Q);v&&!vs(h)&&Object.keys(h).forEach(N=>{v[N]=h[N]})}},wl=new class{constructor(){this._messagesByConversation=new Map}updateMessage(Q,h,v){var N;const{operation:O,updateUnreadCount:z=!0}=v,X=yo(v,["operation","updateUnreadCount"]),rA=[];for(const DA of h){const GA=(N=this._messagesByConversation.get(Q))===null||N===void 0?void 0:N.get(DA);if(!GA)return!1;Object.keys(X).forEach(JA=>{GA[JA]=X[JA]}),rA.push(GA)}return this._emitMessageStoreOperationEvent(O,{conversationID:Q,messageList:rA,updateUnreadCount:z}),rA}getMessagesByConversation(Q){var h;return[...((h=this._messagesByConversation.get(Q))===null||h===void 0?void 0:h.values())||[]]}getMessages(){return this._messagesByConversation}_emitMessageStoreOperationEvent(Q,h){const{conversationID:v}=h;zr(v)?fe.notificationCenter.emitInnerEvent(rg[Q],h):fe.notificationCenter.emitInnerEvent(Q,h)}},Xr=new class{constructor(){this.userProfileMap=new Map,this.friendMap=new Map}getUserProfileMap(){return this.userProfileMap}getFriendMap(){return this.friendMap}getUserProfile(Q){return this.userProfileMap.get(Q)}getFriend(Q){return this.friendMap.get(Q)}},XC=Object.freeze({__proto__:null,conversationStore:Xg,groupStore:za,messageStore:wl,userStore:Xr});class Ks{static getInstance(){return Ks._instance||(Ks._instance=new Ks),Ks._instance}static setInstance(h){Ks._instance=h}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:Fo.getInstance().installExternalPlugin.bind(Fo.getInstance()),registerPlugin:this.registerPlugin.bind(this),setLogLevel:this.setLogLevel.bind(this)}}registerPlugin(h){fe.ssoLog.debug("registerPlugin",h)}statKeyFeatureUsage(h){fe.ssoLog.debug("statTUIKeyFeatures",h)}setLogLevel(h){fe.ssoLog.debug("setLogLevel",h),fe.ssoLog.setLogLevel(h)}setApplicationID(h){fe.store.set("instance",{applicationID:h})}getApiMap(){return this._apiMap}setApiMap(h){this._apiMap=h}registerApi(h){const{common:{timeManager:v},utils:{safeStringify:N}}=fe,{apiName:O,context:z,methodName:X=O,matcher:rA}=h;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),nr.includes(O)&&fe.ssoLog.debug(O,`${O} start params: ${N(DA)}`),vl(X,DA);const ee=this._apiHandlersMap[O];for(const ue of ee)if(!ue.matcher||ue.matcher(DA))try{const He=ue.context[ue.methodName].bind(ue.context)(...DA);return this._isPromiseLike(He)?this._handleAsyncResult(He,O,JA,GA):(this._reportApiSuccessLog({result:He,apiName:O,eventType:JA,startTime:GA}),He)}catch(He){throw fe.ssoLog.error(O,`${O} fail ${He?.message||He?.errorMessage})`,{error:He,costTime:v.getServerTimeMs()-GA,eventType:JA,method:O}),He}})}registerExperimentalAPI(h,v,N){const O=N||h;this._experimentalApiMap[h]=v[O].bind(v)}destroy(){return pA(this,void 0,void 0,function*(){var h,v;try{!((h=fe.store.get("login"))===null||h===void 0)&&h.isLogin&&(yield this._apiMap.logout()),fe.notificationCenter.emitInnerEvent(Ii.DESTROY)}catch(N){console.debug("destroy error: ",N)}finally{fe.notificationCenter.emitOuterEvent(Dn.SDK_DESTROY,{SDKAppID:(v=fe.store.get("instance"))===null||v===void 0?void 0:v.sdkAppId}),Rs.clear(),Fo.getInstance().clear(),en.getInstance().destroy(),fe.destroy()}})}exposeApiForClient(){return this._apiMap}exposeApiForPlugin(){return Object.assign(Object.assign({InnerEvent:Ii,InnerEventSubType:fe.notificationCenter.InnerEventSubType,OuterEvent:Dn,OuterConstant:Cs,SignalingEvent:so,helper:Object.assign(Object.assign(Object.assign({},fe.utils),fe.common),{registerApi:this.registerApi.bind(this),registerExperimentalAPI:this.registerExperimentalAPI.bind(this),registerInterceptor:Dr,registerValidateConfig:Sc,checkBusinessCapabilityBits:Kc,registerWorkflowStep:en.getInstance().registerWorkflowStep.bind(en.getInstance()),ChatError:ss}),apiMap:this._apiMap},fe),{constants:Object.assign(Object.assign({},UI),fe.constants),common:Object.assign(Object.assign(Object.assign({},kg),fe.common),{workflowManager:en.getInstance()}),utils:fe.utils,appStore:XC})}callExperimentalAPI(h,v){return fe.ssoLog.debug(`callExperimentalAPI.${h} start params: ${fe.utils.safeStringify(v)}`),this._experimentalApiMap[h]?this._experimentalApiMap[h](v):(fe.ssoLog.error("callExperimentalAPI",`callExperimentalAPI.${h} not found, params: ${fe.utils.safeStringify(v)}`),Promise.reject(new ss({code:ko.INVALID_OPERATION})))}_isPromiseLike(h){return h!==null&&typeof h=="object"&&typeof h.then=="function"}_handleAsyncResult(h,v,N,O){return h.then(z=>(this._reportApiSuccessLog({result:z,apiName:v,eventType:N,startTime:O}),z)).catch(z=>{throw fe.ssoLog.error(v,`${v} fail ${z?.message||z?.errorMessage})`,{error:z,costTime:fe.common.timeManager.getServerTimeMs()-O,eventType:N,method:v,startTime:O}),z})}_reportApiSuccessLog(h){let{result:v,apiName:N,startTime:O,eventType:z}=h;const{timeManager:X}=fe.common,{successLog:{message:rA,moreMessage:DA}={message:"",moreMessage:""}}=v||{},GA=X.getServerTimeMs();N==="login"&&(O+=X.getTimeOffsetWithServer()),nr.includes(N)&&fe.ssoLog.info(N,`${N} success ${rA} ${DA}`,{costTime:GA-O,eventType:z,message:rA,moreMessage:DA,startTime:O}),v?.successLog&&delete v.successLog}}class VI{constructor(){this._latestLoginAt=0,this._latestSendOnlinePresenceRequestTime=0,this._helloInterval=120,this._customLoginInfo=""}init(){const{notificationCenter:h,store:v}=fe;v.set("login",{isReady:!1}),Ks.getInstance().registerApi({apiName:"login",context:this}),Ks.getInstance().registerApi({apiName:"logout",context:this}),Ks.getInstance().registerApi({apiName:"getLoginUser",context:this}),Ks.getInstance().registerApi({apiName:"isReady",context:this}),Ks.getInstance().registerApi({apiName:"getServerTime",context:this}),Ks.getInstance().registerExperimentalAPI("setCustomLoginInfo",this),h.subscribeInnerEvent(Ii.RECONNECTED,this._reLogin,this),fe.notificationCenter.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}login(h){return pA(this,void 0,void 0,function*(){var v;const{sdkEdition:N}=fe.store.get("instance")||{};try{if(this._isLoginIn())return this._createRepeatLoginResponse();if(this._isLoginFrequencyExceeded())throw new ss({functionName:"login",code:ko.REPEAT_LOGIN});const O=yield this._performLogin(h);this._validateAfterLogin(O),this._handleLoginSuccess(O),yield this._ensureAsyncComplete(),this._updateAndEmitSDKReady(),this._latestLoginAt=0;const z=(v=fe.channel.getSocketAdapter())===null||v===void 0?void 0:v.getId(),{appId:X,href:rA}=fe.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!==ko.REPEAT_LOGIN&&(this._latestLoginAt=0);const X=new ss({functionName:"login",code:z});throw console.error(X),X}})}_reLogin(){return pA(this,void 0,void 0,function*(){var h;try{if(!this._isLoginIn())return;const v=yield yu(this._customLoginInfo);if(v){const{instanceID:N,customStatus:O}=v;fe.store.set("login",{statusInstanceId:N}),en.getInstance().executeWorkflow(sr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,{customStatus:O,statusType:pu.USER_STATUS_ONLINE});const z=(h=fe.channel.getSocketAdapter())===null||h===void 0?void 0:h.getId();fe.ssoLog.info("reLogin",`socketId:${z} instanceId:${N}`)}}catch(v){console.warn(v)}})}logout(){return pA(this,arguments,void 0,function*(h=Wa.USER_INITIATED){const{ssoLog:v}=fe;v.debug("logout",`logout start logoutReason: ${h}`);try{yield this._performLogout(h),v.info("logout","logout success"),fe.ssoLog.uploadSSOLogData()}catch(N){const{errorCode:O}=N;throw new ss({functionName:"logout",code:O})}finally{this.handleLogoutCompleted()}return{code:0,data:{}}})}getLoginUser(){return this._isLoginIn()?qn():""}isReady(){var h;return(h=fe.store.get("login"))===null||h===void 0?void 0:h.isReady}setCustomLoginInfo(h=""){this._customLoginInfo=h}handleLogoutCompleted(){this._updateAndEmitSDKNotReady(),this._reset(),en.getInstance().reset(),fe.notificationCenter.emitInnerEvent("logout")}getServerTime(){const{timeManager:h}=fe.common;return h.getServerTimeMs()}_updateAndEmitSDKReady(){fe.store.set("login",{isReady:!0}),setTimeout(()=>{fe.notificationCenter.emitOuterEvent(Dn.SDK_READY,{name:Dn.SDK_READY})},1)}_updateAndEmitSDKNotReady(){fe.store.set("login",{isReady:!1}),fe.notificationCenter.emitOuterEvent(Dn.SDK_NOT_READY,{name:Dn.SDK_NOT_READY})}_validateAfterLogin(h){const v="login";if(!h)throw new ss({functionName:v,message:"login response is empty"});const{tinyID:N,a2Key:O}=h||{};if(!N)throw new ss({functionName:v,code:ko.NO_TINYID});if(!O)throw new ss({functionName:v,code:ko.NO_A2KEY})}_createRepeatLoginResponse(){var h;return{code:0,data:{actionStatus:"OK",errorCode:0,errorInfo:Ml({code:"RepeatLogin",replacement1:(h=fe.store.get("login"))===null||h===void 0?void 0:h.userId}),repeatLogin:!0}}}_performLogin(h){return pA(this,void 0,void 0,function*(){const{userID:v,userSig:N}=h;return fe.store.set("login",{userId:v,userSig:N}),this._latestLoginAt=Date.now(),yu(this._customLoginInfo)})}_ensureAsyncComplete(){return pA(this,void 0,void 0,function*(){yield new Promise(h=>{setTimeout(()=>h(null),1)})})}_handleLoginSuccess(h){const{timeManager:v}=fe.common,{helloInterval:N,timeStamp:O,customStatus:z,purchaseBits:X}=h,rA=1e3*O;v.calculateTimeOffsetWithServer(this._latestLoginAt,rA),this._helloInterval=N||120,this._updateLoginStore(h),fe.user.userStatus.setCustomStatus(z),en.getInstance().executeWorkflow(sr.SYNC_SERVER_INFO_AFTER_LOGIN,{purchaseBits:X}),fe.common.taskScheduler.addTask({id:mu,intervalMs:1e3*this._helloInterval,callback:this._sendOnlinePresenceRequest,context:this})}_performLogout(h){return function(v){return pA(this,void 0,void 0,function*(){const{logoutReason:N}=v,O="im_open_status.wslogout",z=fe.common.generateProtocolData({servcmd:O,data:{wslogout_type:N,isWebUniapp:0}}),X=`${z.head.seq}${O}`;return yield fe.channel.sendPacket(z,{requestId:X})})}({logoutReason:h})}_updateLoginStore(h){const{a2Key:v,tinyID:N,instanceID:O,authKey:z}=h;fe.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 h="im_open_status.wshello",v=fe.common.generateProtocolData({servcmd:h,data:{isWebUniapp:0}}),N=`${v.head.seq}${h}`;return fe.channel.sendPacket(v,{requestId:N})}()}catch(h){fe.ssoLog.warn("_sendOnlinePresenceRequest",` error:${h.message}`)}})}_isLoginIn(){var h;return((h=fe.store.get("login"))===null||h===void 0?void 0:h.isLoggedIn)===!0}_isLoginFrequencyExceeded(){return Date.now()-this._latestLoginAt<=15e3}_reset(){fe.common.taskScheduler.removeTask(mu),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:h}=fe;h.unSubscribeInnerEvent(Ii.RECONNECTED,this._reLogin,this),h.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this)}}const Ls={login:{userID:{required:!0,rules:["string"],allowEmpty:!1},userSig:{required:!0,rules:["string"],allowEmpty:!1}}},wc={logout:!0};class $g{constructor(){this.loginAction=new VI,this.kickedOutHandler=new Dc,this.loginAction.init(),this.kickedOutHandler.init(),Sc({auth:wc,params:Ls})}}var Er,Pr,Za;(function(Q){Q.CONV_C2C="C2C",Q.CONV_GROUP="GROUP",Q.CONV_TOPIC="TOPIC",Q.CONV_SYSTEM="@TIM#SYSTEM"})(Er||(Er={})),function(Q){Q.MSG_PRIORITY_HIGH="High",Q.MSG_PRIORITY_NORMAL="Normal",Q.MSG_PRIORITY_LOW="Low",Q.MSG_PRIORITY_LOWEST="Lowest"}(Pr||(Pr={})),function(Q){Q.MSG_TEXT="TIMTextElem",Q.MSG_CUSTOM="TIMCustomElem",Q.MSG_LOCATION="TIMLocationElem",Q.MSG_FACE="TIMFaceElem",Q.MSG_IMAGE="TIMImageElem",Q.MSG_AUDIO="TIMSoundElem",Q.MSG_FILE="TIMFileElem",Q.MSG_VIDEO="TIMVideoFileElem",Q.MSG_GRP_TIP="TIMGroupTipElem",Q.MSG_GRP_SYS_NOTICE="TIMGroupSystemNoticeElem",Q.MSG_MERGER="TIMRelayElem"}(Za||(Za={}));const fE={1:Pr.MSG_PRIORITY_HIGH,2:Pr.MSG_PRIORITY_NORMAL,3:Pr.MSG_PRIORITY_LOW,4:Pr.MSG_PRIORITY_LOWEST},nC=0,$C=1;var ro;(function(Q){Q.IN="in",Q.OUT="out"})(ro||(ro={}));const _c=2,_l={};function rC(Q){if(!Q)return 0;if(_l[Q]===void 0){const h=new Date,v=`3${h.getHours()}`.slice(-2),N=`0${h.getMinutes()}`.slice(-2),O=`0${h.getSeconds()}`.slice(-2);_l[Q]=parseInt([v,N,O,"0001"].join(""),10),console.log(`autoIncrementIndex start index:${_l[Q]}`)}else _l[Q]+=1;return _l[Q]}class aC{constructor(h){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=Pr.MSG_PRIORITY_NORMAL,this._relayFlag=!1;const{clientTime:v=fe.common.timeManager.getServerTimeSeconds()||0,senderTinyID:N,currentUser:O,needReadReceipt:z,isSupportExtension:X,customModerationConfigurationId:rA,to:DA,from:GA,nick:JA="",avatar:ee="",time:ue,messageControlInfo:He,tinyID:At,cloudCustomData:st="",messageLifeTime:Gt,messageVersion:xt=0,conversationType:Ui,sequence:ao,checkResult:zi=0,isPlaceMessage:ui=0,messageFlagBits:Oo,receiverList:$o,isSystemMessage:Qi=!1,status:Ki=Rg.SUCCESS,revokeReason:js="",conversationSubType:we,clientSequence:vt,protocol:FA="JSON",revokerInfo:Wt={userID:"",nick:"",avatar:""},readReceiptInfo:En={readCount:void 0,unreadCount:void 0,isPeerRead:void 0,timestamp:0},random:Zt,groupProfile:Is,atUserList:vi,flow:Co,isRead:Et=!1,priority:Ct=Pr.MSG_PRIORITY_NORMAL,onlineOnlyFlag:Ig=!1,nameCard:bs="",quoteInfo:ji}=h;var Yr;this.clientTime=v,this.senderTinyID=N||At,this.needReadReceipt=z===!0||z===1,this.isSupportExtension=X===!0||X===1,this._cmConfigID=rA,this.to=DA,this.nick=JA,this.avatar=ee,this.protocol=FA,this.random=Zt===void 0?(Yr=Yr||99999999,Math.round(Math.random()*Yr)):Zt,this.time=ue||Math.ceil(Date.now()/1e3),this._isExcludedFromLastMessage=!!He?.excludedFromLastMessage,this._isExcludedFromUnreadCount=!!He?.excludedFromUnreadCount,this.isModified=!!xt,this.cloudCustomData=st,this.messageLifeTime=Gt,this.from=GA||null,this.sequence=ao||0,this.conversationType=Ui||Er.CONV_C2C,this.hasRiskContent=zi>1,this.version=xt,this.isPlaceMessage=ui,this.isRevoked=ui===2||Oo===8,this.isSystemMessage=Qi,this.readReceiptInfo=En,this.revokeReason=js,this.revokerInfo=Wt,this._receiverList=$o,this.conversationSubType=we,this.revoker=Wt?.revoker||"",this.clientSequence=vt||ao||0,this.status=Ki,this.atUserList=vi||[],this.flow=Co,this.isRead=Et,this.priority=Ct,this._onlineOnlyFlag=Ig,this.nameCard=bs,this.quoteInfo=ji,this.reInitialize(O),this._initC2CReadReceiptInfo(h),this._extractGroupInfo(Is)}getElements(){return this._elements}isOnlineMessage(){return this.messageLifeTime===0}setElement(h){Array.isArray(h)?this._elements=h:this._elements=[h],this._updatePayloadAndType()}transformElementsToServerFormat(){return this._elements?Array.isArray(this._elements)?this._elements.map(h=>h.transformToServerFormat()):this._elements.transformToServerFormat():null}setRelayFlag(h){this._relayFlag=h}validateBeforeSend(){var h,v,N;return this._relayFlag?{isValid:!0}:((h=this._elements)===null||h===void 0?void 0:h.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(h){const{readReceiptSentByPeer:v,timestamp:N=0}=h;this.conversationType===Er.CONV_C2C&&this.needReadReceipt===!0&&(this.readReceiptInfo.isPeerRead=v===1,this.readReceiptInfo.timestamp=N)}_extractGroupInfo(h){if(!h)return;const{From_AccountNick:v,From_AccountHeadurl:N,MsgFrom_AccountExtraInfo:O,GroupType:z}=h,{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(h){h===this.from&&(this.isRead=!0),this._initSequence(h),this._concatConversationID(h),this.generateMessageID()}_concatConversationID(h){let v="";const N=this.conversationType;N!==Er.CONV_SYSTEM?(v=N===Er.CONV_C2C?h===this.from?this.to:this.from:this.to,this.conversationID=v?`${N}${v}`:null):this.conversationID=Er.CONV_SYSTEM}_initSequence(h){this.clientSequence===0&&h&&(this.clientSequence=rC(h)),this.sequence===0&&this.conversationType===Er.CONV_C2C&&(this.sequence=this.clientSequence)}generateMessageID(){this.from===Er.CONV_SYSTEM&&(this.senderTinyID="144115198244471703"),this.ID=`${this.senderTinyID}-${this.clientTime}-${this.random}`}setIsRead(h){this.isRead=h}}class Tl{static parseServerPushElement(h){const{MsgContent:v={}}=h,{Data:N,Ext:O,Desc:z}=v;return new Tl({data:N,description:z,extension:O})}constructor(h){this.type=Za.MSG_CUSTOM;const{data:v="",description:N="",extension:O=""}=h;this.content={data:v,description:N,extension:O}}transformToServerFormat(h){const{isMergerMessage:v=!1}=h||{},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:h}=fe.utils,v=[this.content.data,this.content.description,this.content.extension].some(N=>!h(N));return{isValid:v,error:v?null:{message:"content can not be empty"}}}}class JI{static parseServerPushElement(h){const{MsgContent:v={Text:""}}=h,{Text:N}=v;return new JI({text:N})}constructor(h){this.type=Wg.MSG_TEXT,this.content={text:h.text||""}}validateBeforeSend(){var h,v;return((v=(h=this.content)===null||h===void 0?void 0:h.text)===null||v===void 0?void 0:v.length)>0?{isValid:!0}:{isValid:!1,error:{message:"content can not be empty"}}}transformToServerFormat(h){const{isMergerMessage:v=!1}=h||{},N=v?this.payload:this.content,{text:O}=N;return{MsgType:this.type,MsgContent:{Text:O}}}}var II=new class{constructor(){this._elementClassMap={[Za.MSG_CUSTOM]:Tl,[Za.MSG_TEXT]:JI}}init(){Ks.getInstance().registerApi({apiName:"createCustomMessage",context:this}),Ks.getInstance().registerApi({apiName:"createTextMessage",context:this})}registerElementClass(Q,h){var v;(v=h).prototype!==void 0&&"constructor"in v.prototype&&(this._elementClassMap[Q]=h)}getElementClass(Q){return this._elementClassMap[Q]}createMessage(Q){const{from:h,flow:v=ro.OUT}=Q,{userId:N}=fe.store.get("login")||{};this._isSendByCurrentInstance({from:h,flow:v,currentUser:N})?this._updateWithSenderInfo(Q):this._isMultiEndpointSyncMessage({from:h,flow:v,currentUser:N})&&(Q.flow=ro.OUT);const O=Object.assign(Object.assign({},Q),{currentUser:N});return new aC(O)}createCustomMessage(Q){const h=qn(),v=this.createMessage(Object.assign(Object.assign({},Q),{from:h})),N=this._elementClassMap[Za.MSG_CUSTOM];if(!v)return null;if(N){const O=new N(Q.payload);v.setElement(O)}return v}createTextMessage(Q){var h;if(!Q)return null;const v=typeof Q.payload=="string"?Q.payload:((h=Q?.payload)===null||h===void 0?void 0:h.text)||"",N=new JI({text:v}),O=qn(),z=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},Q),{from:O}));return z.setElement(N),z}_updateWithSenderInfo(Q){var h,v;const{nick:N,avatar:O,conversationType:z,to:X}=Q,{userId:rA,tinyID:DA}=fe.store.get("login")||{},GA=Xr.getUserProfile(rA);return Q.nick=N||GA?.nick||"",Q.avatar=O||GA?.avatar||"",Q.tinyID=Q.tinyID||DA||"",Q.from=rA,Q.status=Rg.UNSENT,Q.flow=ro.OUT,z===wg.CONV_GROUP&&(Q.nameCard=(v=(h=za.getGroup(X))===null||h===void 0?void 0:h.selfInfo)===null||v===void 0?void 0:v.nameCard),Q}_isMultiEndpointSyncMessage(Q){const{from:h,flow:v,currentUser:N}=Q;return h===N&&v===ro.IN}_isSendByCurrentInstance(Q){const{from:h,flow:v,currentUser:N}=Q;return h===N&&v===ro.OUT}};const uI={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}},yE={HonorImportance:{range:["LOW","NORMAL"],defaultValue:void 0},MeizuNotifyType:{range:[0,1],defaultValue:void 0}},Nl={enableIOSBackgroundNotification:{range:[!0,!1],defaultValue:!1},interruptionLevel:{range:["passive","active","time-sensitive","critical"],defaultValue:"active"}};function Gl(Q,h){return Object.keys(h).forEach(v=>{const{range:N,defaultValue:O}=h[v];Q[v]=N.includes(Q[v])?Q[v]:O}),Q}function Lg(Q){const h=Q.lastIndexOf(".");return h===-1?Q:Q.slice(0,h)}function Ac(Q){const{androidInfo:h={},androidOPPOChannelID:v=""}=Q,N=h.OPPOChannelID||v,O=Gl(h,yE),{sound:z="",FCMChannelID:X=""}=O,rA=yo(O,["sound","FCMChannelID"]);return Object.assign(Object.assign({},rA),{Sound:Lg(z),OPPOChannelID:N,GoogleChannelID:X})}function cd(Q){const{apnsInfo:h={},ignoreIOSBadge:v=!1,disableVoipPush:N}=Q,O=Gl(h,Nl),{ignoreIOSBadge:z,disableVoipPush:X,enableIOSBackgroundNotification:rA}=O,DA=yo(O,["ignoreIOSBadge","disableVoipPush","enableIOSBackgroundNotification"]),GA=z===!0||v===!0?1:0;let JA;return r(N)||(JA=N===!1?1:0),r(X)||(JA=X===!1?1:0),Object.assign(Object.assign({},DA),{BadgeMode:GA,IsVoipPush:JA,ContentAvailable:rA?1:0})}function DE(Q){return fe.utils.isPlainObject(Q)?{PushFlag:Q.disablePush===!0?1:0,Title:Q.title||"",Desc:Q.description||"",Ext:Q.extension||"",ApnsInfo:cd(Q),AndroidInfo:Ac(Q)}:uI}function Tc(Q){const{From_AccountHeadurl:h,From_AccountNick:v,IsNeedReadReceipt:N,IsPeerRead:O,IsSyncMsg:z,MsgBody:X,MsgClientTime:rA,MsgLifeTime:DA,MsgRandom:GA,MsgSeq:JA,MsgTimeStamp:ee,SendMsgControl:ue,SupportMessageExtension:He,TinyId:At,MsgCheckResult:st,CloudCustomData:Gt,MsgVersion:xt,MsgFlagBits:Ui,RevokerInfo:ao,InnerSdkCustomData:zi}=Q;let ui,{From_Account:Oo,To_Account:$o}=Q;if(z===1){const Qi=$o;$o=Oo,Oo=Qi}if(ao){const{Reason:Qi,Revoker_Account:Ki,Revoker_FromUin:js}=ao;ui={reason:Qi,revoker:Ki,revokerFromUin:js,userID:Ki}}return{from:Oo,avatar:h,nick:v,needReadReceipt:N===1,isSyncMessage:z,clientTime:rA,messageLifeTime:DA,random:GA,sequence:JA,time:ee,messageControlInfo:{excludedFromLastMessage:ue?.NoLastMsg===1,excludedFromUnreadCount:ue?.NoUnread===1},isSupportExtension:He,to:$o,tinyID:At,checkResult:st,cloudCustomData:Gt,revokerInfo:ui,messageVersion:xt,messageFlagBits:Ui,readReceiptSentByPeer:O,elements:Xa(X),onlineOnlyFlag:DA===0,quoteInfo:_u(zi)}}function HI(Q){const{From_Account:h,MsgBody:v,MsgClientTime:N,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,To_Account:rA,MsgVersion:DA,CloudCustomData:GA,MsgCheckResult:JA}=Q;return{from:h,clientTime:N,random:O,sequence:z,time:X,to:rA,elements:Xa(v),messageVersion:DA,cloudCustomData:GA,checkResult:JA}}function co(Q){const{ClientSeq:h,From_Account:v,GroupInfo:N,MsgBody:O,MsgClientTime:z,MsgRandom:X,MsgSeq:rA,MsgTimeStamp:DA,SendMsgControl:GA,SupportMessageExtension:JA,TinyId:ee,CloudCustomData:ue,MsgVersion:He,MsgCheckResult:At,NeedReadReceipt:st,IsPlaceMsg:Gt,RevokerInfo:xt,GroupAtInfo:Ui,OnlineOnlyFlag:ao,InnerSdkCustomData:zi}=Q;let ui,Oo=Pr.MSG_PRIORITY_NORMAL;if(Object.keys(fE).includes(String(Q.MsgPriority))&&(Oo=fE[Q.MsgPriority]),xt){const{Reason:Qi,Revoker_Account:Ki,Revoker_FromUin:js}=xt;ui={reason:Qi,revoker:Ki,revokerFromUin:js,userID:Ki}}const $o=function(Qi){const Ki=[];return Array.isArray(Qi)&&Qi.forEach(js=>{js.GroupAtAllFlag===nC?Ki.push(js.GroupAt_Account):js.GroupAtAllFlag===$C&&Ki.push(Cs.MSG_AT_ALL)}),Ki}(Ui);return{clientSequence:h,from:v,groupProfile:N,clientTime:z,priority:Oo,random:X,sequence:rA,time:DA,messageControlInfo:{excludedFromLastMessage:GA?.NoLastMsg===1,excludedFromUnreadCount:GA?.NoUnread===1},isSupportExtension:JA,tinyID:ee,cloudCustomData:ue,messageVersion:He,checkResult:At,needReadReceipt:st,isPlaceMessage:Gt,revokerInfo:ui,atUserList:$o,elements:Xa(O),to:SE(Q),onlineOnlyFlag:ao===1,quoteInfo:_u(zi)}}function SE(Q){const{utils:{isEmpty:h},constants:{IS_TOPIC_MESSAGE:v}}=fe,{ToGroupId:N,GroupInfo:{MillionGroupFlag:O=0,TopicId:z}={}}=Q;return O!==v||h(z)?N:z}function Xa(Q){if(!Q)return null;if(Array.isArray(Q))return Q.map(v=>{const N=fe.message.messageFactory.getElementClass(v.MsgType);return N?.parseServerPushElement(v)});const h=fe.message.messageFactory.getElementClass(Q.MsgType);return h?.parseServerPushElement(Q)}function qI(Q){const{From_Account:h,MsgBody:v,MsgClientTime:N,MsgRandom:O,MsgSeq:z,MsgTimeStamp:X,GroupId:rA,TopicId:DA,MsgVersion:GA,CloudCustomData:JA,MsgCheckResult:ee}=Q;return{from:h,clientTime:N,random:O,sequence:z,time:X,groupID:rA,topicID:DA,elements:Xa(v),messageVersion:GA,cloudCustomData:JA,checkResult:ee}}function _u(Q){const{utils:{isString:h,safeStringify:v},ssoLog:N}=fe;if(!h(Q))return null;try{const{messageID:O,messageTime:z,messageSequence:X}=JSON.parse(Q).businessQuote;return{msgID:O,messageTime:z,messageSequence:X}}catch(O){return N.debug("_parseServerQuoteInfo",v(O)),null}}function Nc({conversationUpdateFields:Q,message:h}){const{conversationID:v,conversationType:N,conversationSubType:O,flow:z,_isExcludedFromUnreadCount:X,_isExcludedFromLastMessage:rA}=h,DA=rA?"":tl(h),GA=!X&&z===ro.IN;Q.has(v)?(Q.get(v).lastMessage=DA,GA&&Q.get(v).unreadCount++):Q.set(v,{conversationID:v,type:N,subType:O,unreadCount:GA?1:0,lastMessage:DA})}function EI(Q){return Q.filter(h=>{const v=!vs(h?._elements),N=h?.isPlaceMessage===1;return v||fe.ssoLog.error("emptyMessageBody",`from:${h.from} to:${h.to} sequence:${h.sequence}`),v&&!N})}function il(Q){const{messageDataHandler:h}=fe.message;return!h.isInMessageList(Q)&&!h.isMessageSentByCurrentInstance(Q)}var ol=Object.freeze({__proto__:null,autoIncrementIndex:rC,createAndroidPushInfo:Ac,createApnsPushInfo:cd,createOfflinePushInfo:DE,filterValidMessages:EI,getAndroidSoundName:Lg,parseServerGroupMessage:co,parseServerPushC2CModifyMessage:HI,parseServerPushGroupModifyMessage:qI,parseServerPushMessage:Tc,parseServerPushMessageElement:Xa,shouldStoreMessage:il,updateConversationFields:Nc});const{isPlainObject:Pa}=fe.utils;function ME(Q,h={}){const{onlineUserOnly:v,messageControlInfo:N}=h;let{offlinePushInfo:O}=h;Q.conversationType===Er.CONV_C2C&&v===!0&&(O?O.disablePush=!0:O={disablePush:!0});let z="";typeof Q.cloudCustomData=="string"&&Q.cloudCustomData.length>0&&(z=Q.cloudCustomData);const X=[];if(N&&Pa(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 na(Q){const{webhookInfo:{disableCloudMessagePreHook:h=!1,disableCloudMessagePostHook:v=!1}={}}=Q||{};if(!h&&!v)return;const N=[];return h&&N.push("ForbidBeforeSendMsgCallback"),v&&N.push("ForbidAfterSendMsgCallback"),N}function Mn(Q,h){return pA(this,void 0,void 0,function*(){const v=Q.conversationType===Er.CONV_GROUP?function(O,z){var X;const rA=ME(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:JA,offlinePushInfo:ee}=rA,ue=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));let He;return p(O._receiverList)&&O._receiverList.length>0&&(He=O._receiverList,O._receiverList.length>50&&(He=O._receiverList.slice(0,50),console.warn("ReceiverListLimit"))),{servcmd:"group_open_http_svc.send_group_msg",data:{From_Account:(X=fe.store.get("login"))===null||X===void 0?void 0:X.userId,GroupId:O.to,MsgBody:ue,CloudCustomData:GA,Random:O.random,MsgPriority:O.priority,ClientSeq:O.clientSequence,GroupAtInfo:O._groupAtInfoList,OnlineOnlyFlag:DA?1:0,MsgClientTime:O.clientTime,OfflinePushInfo:DE(ee),SendMsgControl:DA?void 0:JA,NeedReadReceipt:O.needReadReceipt===!0?1:0,To_Account:He,SupportMessageExtension:O.isSupportExtension===!0?1:0,IsRelayMsg:O._relayFlag===!0?1:0,CustomModerationConfigID:O._cmConfigID,ForbidCallbackControl:na(z),InnerSdkCustomData:vE(O)}}}(Q,h):function(O,z){var X;const rA=ME(O,z),{onlineUserOnly:DA,cloudCustomData:GA,messageControlInfo:JA,offlinePushInfo:ee}=rA,ue=DA===!0?0:void 0,He=JSON.parse(JSON.stringify(O.transformElementsToServerFormat()));return{servcmd:"openim.sendmsg",data:{From_Account:(X=fe.store.get("login"))===null||X===void 0?void 0:X.userId,To_Account:O.to,MsgBody:He,CloudCustomData:GA,MsgSeq:O.sequence,MsgRandom:O.random,MsgLifeTime:ue,From_AccountNick:O.nick,From_AccountHeadurl:O.avatar,SendMsgControl:ue!==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:DE(ee),ForbidCallbackControl:na(z),InnerSdkCustomData:vE(O)}}}(Q,h),N=yield zg(v);return N?{time:N.MsgTime,messageDropReason:N.MsgDropReason,sequence:N.MsgSeq}:null})}function Nr(Q){return pA(this,void 0,void 0,function*(){const{from:h,to:v,version:N=0,sequence:O,random:z,time:X,type:rA,cloudCustomData:DA}=Q,GA={From_Account:h,To_Account:v,MsgVersion:N,MsgSeq:O,MsgRandom:z,MsgTime:X,MsgType:rA,MsgBody:Q.transformElementsToServerFormat(),CloudCustomData:DA},JA=yield zg({servcmd:"openim.modify_c2c_msg",data:GA});if(JA){const{MsgBody:ee,MsgVersion:ue,CloudCustomData:He}=JA;return{elements:Xa(ee),messageVersion:ue,cloudCustomData:He}}})}function sl(Q){return pA(this,void 0,void 0,function*(){const{to:h,version:v=0,sequence:N,cloudCustomData:O}=Q,z={GroupId:h,MsgVersion:v,MsgSeq:N,MsgBody:Q.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:Xa(rA),messageVersion:DA,cloudCustomData:GA}}})}function bl(Q){return pA(this,void 0,void 0,function*(){const{groupID:h,count:v,messageSequence:N,messageSequenceList:O,getType:z}=Q,X={GroupId:h,ReqMsgNumber:v,WithRecalledMsg:1,Version:1,GetType:z};return N&&(X.ReqMsgSeq=N),p(O)&&O.length>0&&(X.ReqMsgSeqList=O),yield zg({servcmd:"group_open_http_svc.group_msg_get",data:X})})}function Gc(Q){return pA(this,void 0,void 0,function*(){const{peerAccount:h,count:v,lastMessageTime:N,messageKey:O,direction:z}=Q;return zg({servcmd:"openim.getroammsg",data:{Peer_Account:h,MaxCnt:v,WithRecalledMsg:1,LastMsgTime:N,MsgKey:O,GetDirection:z}})})}function vE(Q){if(fe.utils.isObject(Q.quoteInfo)){const{msgID:h,messageSequence:v,messageTime:N}=Q.quoteInfo;return JSON.stringify({businessQuote:{messageID:h,messageSequence:v,messageTime:N}})}}var bc=Object.freeze({__proto__:null,createMessagePackOptions:ME,generateForbidCallbackControl:na,getC2CRoamingMessagesByAnchor:Gc,getGroupRoamingMessagesByAnchor:bl,getRoamingMessages:function(Q){return pA(this,void 0,void 0,function*(){const{peerAccount:h,count:v,lastMessageTime:N,messageKey:O}=Q;return(yield zg({servcmd:"openim.getroammsg",data:{Peer_Account:h,MaxCnt:v||15,LastMsgTime:N||0,MsgKey:O,GetDirection:0,WithRecalledMsg:1}}))||[]})},modifyC2CMessage:Nr,modifyGroupMessage:sl,sendMessage:Mn});const{isPlainObject:Tu}=fe.utils,{MSG_AUDIO:gC,MSG_FILE:KI,MSG_IMAGE:Ah,MSG_VIDEO:Nu,MSG_MERGER:dI}=Cs;class nl{constructor(){this._sendProtocolMap=new Map}init(){Ks.getInstance().registerApi({apiName:"sendMessage",context:this,matcher:h=>![gC,KI,Ah,Nu,dI].includes(h[0].type)})}registerSendProtocol(h,v,N){this._sendProtocolMap.set(h,v.bind(N))}sendMessage(h,v){return pA(this,void 0,void 0,function*(){const{TOTAL_COUNT:N,SEND_COST:O,SUCCESS_COUNT:z,FAILED_COUNT:X}=oI;if(!(h instanceof aC))throw new ss({code:ko.MSG_INSTANCE_REQUIRED});const rA=h.validateBeforeSend();if(!rA.isValid){const{code:JA,message:ee=""}=rA.error||{};throw new ss({code:JA,message:ee})}this._reportMessageSendQuality({name:N,message:h});let DA=!1;const{messageDataHandler:GA}=fe.message||{};try{const{messageControlInfo:JA}=v||{};let ee=null;GA.addRandomOfSentMessage(h.random);const ue=Date.now(),He=this._getSendProtocol(h);if(h.conversationType===Er.CONV_C2C?(DA=v?.onlineUserOnly===!0,ee=yield He(h,v)):h.conversationType===Er.CONV_GROUP&&(yield this._validateBeforeSendGroupMessage(h),ee=yield He(h,v)),ee){const{messageDropReason:At,sequence:st,time:Gt}=ee;if(this._updateNickAndAvatarOfSentMessageByMe(h),At&&this._logRateLimitInfo(h,st,At),this._reportMessageSendQuality({name:z,message:h}),this._reportMessageSendQuality({name:O,message:h,startTs:ue}),h.isResend===!0){const xt=GA.findMessage(h.ID);xt&&(fe.ssoLog.debug("sendMessage",`sendMessage resend ok. ID:${xt.ID}`),GA.deleteConversationMessage(xt))}return h.status=Rg.SUCCESS,h.time=Gt,h.conversationType===Er.CONV_GROUP&&(h.sequence=st),DA?h._onlineOnlyFlag=!0:(GA.storeConversationMessage(h),this._applySentMessageControlInfo(h,JA),this._emitOnlineMessageSent(h)),h.type===Wg.MSG_STREAM?{code:0,data:{message:h,streamMessageID:ee.streamMessageID}}:{code:0,data:{message:h}}}}catch(JA){h.status=Rg.FAIL,GA.removeRandomOfSentMessage(h.random);let{errorCode:ee}=JA||{},ue=JA?.errorInfo||JA?.message||"";throw this._hasRiskContent(ee)&&(h.hasRiskContent=!0),DA||this._isRejectedByRestApi(ee)||GA.storeConversationMessage(h),this._reportMessageSendQuality({name:X,message:h,error:JA}),new ss({code:ee,message:ue,data:{message:h},moreMessage:`type:${h.type} from:${h.from} to:${h.to}`})}})}_hasRiskContent(h){return h===80001||h===80004}_isRejectedByRestApi(h){return h>=10100&&h<=10200||h>=120001&&h<=13e4}_emitOnlineMessageSent(h){const v=h._isExcludedFromLastMessage?"":h,{conversationID:N,conversationType:O}=h,z=zr(N)?Ii.TOPIC_NEW_MESSAGE:Ii.NEW_MESSAGE;fe.notificationCenter.emitInnerEvent(z,{result:{conversationUpdateFieldList:[{conversationID:N,type:O,message:h,lastMessage:v,unreadCount:0}]}})}_applySentMessageControlInfo(h,v){v&&Tu(v)&&(v.excludedFromLastMessage===!0&&(h._isExcludedFromLastMessage=!0),v.excludedFromUnreadCount===!0&&(h._isExcludedFromUnreadCount=!0))}_logRateLimitInfo(h,v,N){const O=`from:${h.from} to:${h.to} sequence:${v} messageDropReason:${N}`;fe.ssoLog.warn("messageDropReason",O)}_updateNickAndAvatarOfSentMessageByMe(h){const{messageDataHandler:v}=fe.message||{};let N=!1;const{conversationID:O}=h,z=v.getLatestMsgSentByMe(O);if(z){const{nick:X,avatar:rA}=z;X===h.nick&&rA===h.avatar||(N=!0),N&&v.updateNickAndAvatarOfSentMessage({conversationID:O,latestNick:h.nick,latestAvatar:h.avatar,isSentByMe:!0})}}_validateBeforeSendGroupMessage(h){return pA(this,void 0,void 0,function*(){var v,N,O;const{to:z,from:X}=h;let rA=z,DA=za.getGroup(rA);if(Ea({groupID:rA})&&DA?.isSupportTopic)throw new ss({code:ko.MSG_SEND_GRP_WITH_TOPIC_FAIL});if(zr(z)&&([rA]=z.split(ka.TOPIC),DA=za.getGroup(rA)),!DA&&typeof((v=Ks.getInstance().getApiMap())===null||v===void 0?void 0:v.getGroupProfile)=="function"){const GA=yield Ks.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)===Cs.GRP_AVCHATROOM){const JA=Ml({code:ko.MSG_SEND_FAIL_NOT_IN_AV,replacement1:X,replacement2:rA});throw new ss({code:ko.MSG_SEND_FAIL_NOT_IN_AV,message:JA})}}return!0})}_reportMessageSendQuality(h){fe.notificationCenter.emitInnerEvent(Ii.QUALITY_STAT,{label:Tg.MESSAGE_SEND_SUCCESS_RATE,data:h})}_getSendProtocol(h){return this._sendProtocolMap.get(h.type)||Mn}}var cC=new class{constructor(){this._sparseMessagesByConversation=new Map,this._latestMessageSentByPeerMap=new Map,this._latestMessageSentByMeMap=new Map,this._randomOfSentMessageList=new Set}init(){fe.notificationCenter.subscribeInnerEvent(Ii.LOGOUT,this._reset,this),fe.notificationCenter.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}get _messagesByConversation(){return wl.getMessages()}storeConversationMessage(Q,h=!1){if(an)return!0;const{conversationID:v}=Q;if(!v||(this._messagesByConversation.has(v)||this._messagesByConversation.set(v,new Map),this._shouldSkipStoreMessage(Q,h)))return!1;const N=this._getUniqueIdOfMessage(Q);return this._messagesByConversation.get(v).set(N,Q),this._updateLatestMessageMap(Q),!0}_updateLatestMessageMap(Q){const{conversationID:h}=Q;Q.flow==="out"?this._setLatestMsgSentByMe(h,Q):h.startsWith("C2C")&&this._setLatestMsgSentByPeer(h,Q)}_shouldSkipStoreMessage(Q,h){const v=this._getUniqueIdOfMessage(Q),N=this._messagesByConversation.get(Q.conversationID);if(N?.has(v)){const O=N?.get(v);if(!h||O?.isModified===!0)return!0}return!1}deleteConversationMessage(Q){var h;const{conversationID:v=""}=Q,N=this._getUniqueIdOfMessage(Q);this._messagesByConversation.has(v)&&((h=this._messagesByConversation.get(v))===null||h===void 0||h.delete(N))}modifyConversationMessage(Q,h){var v;if(!this._messagesByConversation.has(Q)&&!this._sparseMessagesByConversation.has(Q))return{isUpdated:!1,message:null};const N=this._getUniqueIdOfMessage(h),O=this._getMessageFromLocalMessage(Q,N);if(O){const{messageVersion:z,elements:X,cloudCustomData:rA,checkResult:DA=0}=h,GA=DA>1;if(fe.ssoLog.debug("modifyConversationMessage",`conversationToMessageMap modifyConversationMessage localVersion:${O.version} remoteVersion:${z}`),O.versionO.ID===Q)||null,h)break;if(!h){const N=Array.from(this._sparseMessagesByConversation.values());for(const O of N)if(h=O.get(Q)||null,h)break}return h}deleteConversationMessageList(Q){this._messagesByConversation.has(Q)&&(this._messagesByConversation.delete(Q),this._latestMessageSentByMeMap.delete(Q),this._latestMessageSentByPeerMap.delete(Q)),this._sparseMessagesByConversation.has(Q)&&this._sparseMessagesByConversation.delete(Q)}revokeMessage({conversationID:Q,sequence:h,random:v,revoker:N}){const O=this._messagesByConversation.get(Q);let z=null;if(O){const X=Array.from(O.values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:h}),z){const rA=this._getUniqueIdOfMessage(z);return wl.updateMessage(Q,[rA],{isRevoked:!0,revoker:N,operation:Or.revoke}),z}}if(this._sparseMessagesByConversation.has(Q)){const X=Array.from(this._sparseMessagesByConversation.get(Q).values());if(z=this._findMessageBySequenceAndRandom({messageList:X,random:v,sequence:h}),z)return z.isRevoked=!0,z.revoker=N,z}}_findMessageBySequenceAndRandom({messageList:Q,sequence:h,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(Q){if(Q.length===0)return;const{conversationID:h}=Q[0],v=Q.length;this._sparseMessagesByConversation.has(h)||this._sparseMessagesByConversation.set(h,new Map);const N=this._sparseMessagesByConversation.get(h);for(let O=0;O=0;N--)if(v[N].flow==="out"){this._setLatestMsgSentByMe(Q,v[N]);break}}}_updateLatestMessageSentByPeer(Q){var h;const v=Array.from(((h=this._messagesByConversation.get(Q))===null||h===void 0?void 0:h.values())||[]);if(v.length!==0&&Q.startsWith("C2C")){for(let N=v.length-1;N>=0;N--)if(v[N].flow==="in"){this._setLatestMsgSentByPeer(Q,v[N]);break}}}_getUniqueIdOfMessage(Q){const{from:h,to:v,random:N,sequence:O,time:z}=Q;return`${h}-${v}-${N}-${O}-${z}`}_setLatestMsgSentByPeer(Q,h){this._latestMessageSentByPeerMap.set(Q,h)}_setLatestMsgSentByMe(Q,h){this._latestMessageSentByMeMap.set(Q,h)}getLatestMsgSentByPeer(Q){return this._latestMessageSentByPeerMap.get(Q)}getLatestMsgSentByMe(Q){return this._latestMessageSentByMeMap.get(Q)}addRandomOfSentMessage(Q){this._randomOfSentMessageList.add(Q)}removeRandomOfSentMessage(Q){this._randomOfSentMessageList.delete(Q)}updateNickAndAvatarOfSentMessage(Q){const{conversationID:h="",latestAvatar:v,latestNick:N,isSentByMe:O=!0}=Q,z=this._messagesByConversation.get(h);if(!z)return;const X=Array.from(z.values()),rA=O?"out":"in";X.forEach(DA=>{const{nick:GA,avatar:JA,flow:ee}=DA;ee===rA&&(GA!==N&&(DA.nick=N),JA!==v&&(DA.avatar=v))})}isInMessageList(Q){var h;const{conversationID:v}=Q;if(!v||!this._messagesByConversation.has(v))return!1;const N=this._getUniqueIdOfMessage(Q);return(h=this._messagesByConversation.get(v))===null||h===void 0?void 0:h.has(N)}isMessageSentByCurrentInstance(Q){const{random:h}=Q;return this._randomOfSentMessageList.has(h)}getContinuousMessagesByConversation(){return this._messagesByConversation}getLocalMessageList(Q){const h=this._messagesByConversation.get(Q);return h?[...h.values()]:[]}getSparseMessageList(Q){const h=this._sparseMessagesByConversation.get(Q);return h?[...h.values()]:[]}_reset(){this._messagesByConversation.clear(),this._latestMessageSentByPeerMap.clear(),this._latestMessageSentByMeMap.clear(),this._randomOfSentMessageList.clear()}_dispose(){this._reset(),fe.notificationCenter.unSubscribeInnerEvent(Ii.LOGOUT,this._reset,this),fe.notificationCenter.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this)}};function ra(Q,h){const v=Xg.getConversation(Q);if(v?.lastMessage){const{lastMessage:N}=v,{lastTime:O,lastSequence:z,version:X}=N,{time:rA,sequence:DA,messageVersion:GA,elements:JA,cloudCustomData:ee}=h;O===rA&&z===DA&&X!==GA&&(N.type=JA[0].type,N.payload=JA[0].content,N.messageForShow=OI(N.type,N.payload),N.cloudCustomData=ee,N.version=GA,Xg.updateConversation(Q,{lastMessage:N}))}}class ec{init(){Ks.getInstance().registerApi({apiName:"modifyMessage",context:this})}modifyMessage(h){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}=h;if(this._canModifyMessageElement(GA)){const JA=h?._elements||[];JA.length>=1&&(JA[0].type=GA,JA[0].content=N)}try{let JA=null,ee=null;if(z===Er.CONV_C2C?JA=yield Nr(h):z===Er.CONV_GROUP&&(JA=yield sl(h)),JA){let ue=`${z}${v}`;return v===qn()&&z===Er.CONV_C2C&&(ue=`${z}${DA}`),ee={conversationType:z,from:DA,to:v,time:rA,random:X,sequence:O,elements:JA?.elements,cloudCustomData:JA?.cloudCustomData,messageVersion:JA?.messageVersion,conversationID:ue},this._handleModifyMessageSuccess(ee),{code:0,data:{message:h},successLog:{message:`to:${v}`}}}}catch(JA){const{errorCode:ee}=JA||{};throw new ss({functionName:"modifyMessage",code:ee,moreMessage:`to:${v}`})}})}_handleModifyMessageSuccess(h){const{conversationID:v}=h,{isUpdated:N,message:O}=fe.message.messageDataHandler.modifyConversationMessage(v,h);N===!0&&fe.notificationCenter.emitOuterEvent(Dn.MESSAGE_MODIFIED,{name:Dn.MESSAGE_MODIFIED,data:[O]}),fe.notificationCenter.emitInnerEvent(Ii.MESSAGE_MODIFIED,{conversationID:v,message:O}),ra(v,h)}_canModifyMessageElement(h){return[Za.MSG_TEXT,Za.MSG_CUSTOM,Za.MSG_LOCATION,Za.MSG_FACE].includes(h)}}class cg{init(){const{notificationCenter:h}=fe,{InnerEventSubType:v}=h;en.getInstance().registerWorkflowStep(sr.RECEIVE_C2C_NEW_MESSAGE,Pt.HANDLE_C2C_NEW_MESSAGE,this._handleC2CMessagePush,this),en.getInstance().registerWorkflowStep(sr.RECEIVE_C2C_NEW_MESSAGE,Pt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterReceiveNewMessage,this),en.getInstance().registerWorkflowStep(sr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Pt.EMIT_C2C_MESSAGE_EVENT,this._emitMessageEventsAfterSyncUnreadMessage,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),h.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(h){en.getInstance().executeWorkflow(sr.RECEIVE_C2C_NEW_MESSAGE,h)}_handleC2CMessagePush(h){const v=h.data||{},{messageDataHandler:N}=fe.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):il(rA)&&(N.storeConversationMessage(rA)&&Nc({conversationUpdateFields:z,message:rA}),N.isMessageSentByCurrentInstance(rA)&&!DA||O.push(rA))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEventsAfterReceiveNewMessage(h){var v;const{messages:N=[]}=((v=h.result)===null||v===void 0?void 0:v[Pt.HANDLE_C2C_NEW_MESSAGE])||{};this._emitMessageEvents(N)}_emitMessageEventsAfterSyncUnreadMessage(h){var v;const{messages:N=[]}=((v=h.result)===null||v===void 0?void 0:v[Pt.UNREAD_MESSAGE_SYNC])||{};this._emitMessageEvents(N)}_emitMessageEvents(h){const v=h?.filter(O=>O?.isModified===!0)||[];v.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:v});const N=h?.filter(O=>!O?.isModified);N.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:N})}_generateC2CMessage(h){const v=Er.CONV_C2C,N=Tc(h),O=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:ro.IN})),{elements:z}=N;return O.setElement(z),O}_updateMessageProfile(h){var v;const{messageDataHandler:N}=fe.message||{},O=(v=fe.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA=""}=h;if(z!==O){const GA=N.getLatestMsgSentByPeer(DA);if(GA){const{nick:JA,avatar:ee}=GA;r(X)||r(rA)?(h.nick=l(JA)?JA:h.nick,h.avatar=l(ee)?ee:h.avatar):X===JA&&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(h){const{conversationID:v,nick:N,avatar:O}=h,z=Xg.getConversation(v),{userProfile:X={}}=z||{};X.avatar===O&&X.nick===N||Xg.updateConversation(v,{userProfile:Object.assign(Object.assign({},X),{nick:N,avatar:O})})}_updateMessageListDueToModify(h){const{conversationID:v}=h,{isUpdated:N,message:O}=fe.message.messageDataHandler.modifyConversationMessage(v,h);N===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),fe.notificationCenter.emitInnerEvent("ModifyMessageSuccess",h),ra(v,h)}_handleC2CMessageModify(h){h.C2cMsgModNotifys.forEach(v=>{var N;const O=Er.CONV_C2C;let z=HI(v);const{to:X,from:rA}=z;let DA=`${O}${X}`;X===((N=fe.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:h}=fe,{InnerEventSubType:v}=h;fe.notificationCenter.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,v.C2C_REALTIME_MESSAGE,this._handleC2CMessagePush,this),fe.notificationCenter.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,v.C2C_MESSAGE_MODIFIED,this._handleC2CMessageModify,this),fe.notificationCenter.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this)}}class CI{init(){const{notificationCenter:h}=fe,{InnerEventSubType:v}=h;en.getInstance().registerWorkflowStep(sr.RECEIVE_GROUP_NEW_MESSAGE,Pt.HANDLE_GROUP_NEW_MESSAGE,this._handleGroupMessagePush,this),en.getInstance().registerWorkflowStep(sr.RECEIVE_GROUP_NEW_MESSAGE,Pt.EMIT_GROUP_MESSAGE_EVENT,this._emitMessageEvents,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,v.GROUP_REALTIME_MESSAGE,this._executeReceiverNewMessageWorkFlow,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,v.GROUP_MESSAGE_MODIFIED,this._handleGroupMessageModify,this),h.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}_executeReceiverNewMessageWorkFlow(h){this._canExecuteReceiverNewMessageWorkFlow(h)&&en.getInstance().executeWorkflow(sr.RECEIVE_GROUP_NEW_MESSAGE,h)}_handleGroupMessagePush(h){const v=h.data||{},{messageDataHandler:N}=fe.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):il(DA)&&N.storeConversationMessage(DA)&&(O.push(DA),Nc({conversationUpdateFields:z,message:DA}))}),{conversationUpdateFieldList:[...z.values()],messages:O}}_emitMessageEvents(h){var v;const{messages:N}=((v=h.result)===null||v===void 0?void 0:v[Pt.HANDLE_GROUP_NEW_MESSAGE])||{},O=N?.filter(X=>X?.isModified===!0)||[];O.length>0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:O});const z=N?.filter(X=>!X?.isModified)||[];z.length>0&&fe.notificationCenter.emitOuterEvent("onMessageReceived",{name:"onMessageReceived",data:z})}_generateGroupMessage(h){const v=Er.CONV_GROUP,N=co(h),O=fe.message.messageFactory.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:ro.IN})),{elements:z}=N;return O.setElement(z),O}updateMessageProfile(h){var v;const{messageDataHandler:N}=fe.message||{},O=(v=fe.store.get("login"))===null||v===void 0?void 0:v.userId,{from:z,nick:X,avatar:rA,conversationID:DA="",_elements:GA}=h;if(z===O){const JA=N.getLatestMsgSentByMe(DA);!JA||X===JA.nick&&rA===JA.avatar||N.updateNickAndAvatarOfSentMessage({conversationID:DA,latestNick:X,latestAvatar:rA,isSentByMe:!0})}else if(z===Cs.CONV_SYSTEM){const{operationType:JA,memberInfoList:ee,operatorInfo:ue}=GA;let He={};if(vs(ee)?vs(ue)||(He=ue):[oa.JOINED,oa.KICKED,oa.ADMIN_SET,oa.ADMIN_CANCELED].includes(JA)&&(He=Object.assign({},ee[0])),!vs(He)){const{nick:At="",avatar:st=""}=He;h.nick=At,h.avatar=st}}}_updateMessageListDueToModify(h){const{conversationID:v}=h,{isUpdated:N,message:O}=fe.message.messageDataHandler.modifyConversationMessage(v,h);N===!0&&fe.notificationCenter.emitOuterEvent("onMessageModified",{name:"onMessageModified",data:[O]}),ra(v,h)}_handleGroupMessageModify(h){h.GroupMsgModNotifys.forEach(v=>{const N=Er.CONV_GROUP;let O=qI(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:h}=fe,{InnerEventSubType:{GROUP_REALTIME_MESSAGE:v,GROUP_MESSAGE_MODIFIED:N}}=h;h.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,v,this._handleGroupMessagePush,this),h.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,N,this._handleGroupMessageModify,this),h.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this)}_canExecuteReceiverNewMessageWorkFlow(h){var v,N;const{GroupId:O,GroupType:z}=((N=(v=h?.GroupMsgArray)===null||v===void 0?void 0:v[0])===null||N===void 0?void 0:N.GroupInfo)||{},X=z===EE.GRP_AVCHATROOM;return!(!za.getGroup(O)&&X)}}var RE=new class{constructor(){this.c2cMessageReceiver=new cg,this.groupMessageReceiver=new CI}init(){this.c2cMessageReceiver.init(),this.groupMessageReceiver.init()}};const Gu={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:Q=>!(!Q.startsWith("C2C")&&!Q.startsWith("GROUP"))||"conversationType is invalid."},payload:{required:!0,rules:["object"],allowEmpty:!1,customValidator:Q=>function(h){var v;return typeof h?.text!="string"||typeof h.text=="string"&&((v=h?.text)===null||v===void 0?void 0:v.length)===0?"payload.text must be a string":!0}(Q)}}},bu={createCustomMessage:!0,sendMessage:!0,modifyMessage:!0};var hI=new class{constructor(){this._historyMessageListFetchAnchors=new Map,this.completedHistoryConversations=new Set}getGroupRoamingMessagesByAnchor(Q){return pA(this,void 0,void 0,function*(){try{const{conversationID:h,count:v,direction:N,sequence:O,messageSequenceList:z,shouldMarkCompleted:X=!1,getType:rA}=Q,DA=h.replace(wg.CONV_GROUP,""),GA=[];let JA=O;if(N===fc.BACKWARD){if(typeof O!="number")return{messageList:[],hasNoMoreHistoryMessage:!1,nextReqMessageIDFromServer:""};JA=O+v-1}const ee=yield bl({groupID:DA,count:v,messageSequence:JA,messageSequenceList:z,getType:rA});if(ee){const{RspMsgList:ue=[],NextReqMsgSeq:He=0,IsFinished:At,InvisibleMsgSeq:st}=ee,Gt=`groupID:${DA} sequence:${O} reqSeq:${JA} direction:${N} complete:${At} nextSequence:${He} remoteMsgCount:${ue.length} invisibleSequenceList:${st}`,xt=[];for(let zi=0;zi=O),Ui&&X&&this.completedHistoryConversations.add(h);const ao=EI(xt);return fe.ssoLog.info("getGroupRoamingMessagesByAnchor",Gt),{messageList:ao,invisibleSequenceList:st,nextReqMessageIDFromServer:He,hasNoMoreHistoryMessage:Ui,serverGroupTipList:GA}}}catch(h){const{errorCode:v,errorInfo:N}=h||{};throw new ss({code:v,message:N})}})}clearHistoryMessageListFetchAnchors(Q){this._historyMessageListFetchAnchors.delete(Q)}isHistoryMessageFetchCompleted(Q){return this.completedHistoryConversations.has(Q)}_parseMessage(Q){var h;const v=wg.CONV_GROUP;Q.Event===4&&(Q.MsgBody.MsgType=Cs.MSG_GRP_TIP);const N=co(Q),O=II.createMessage(Object.assign(Object.assign({},N),{conversationType:v,flow:"in"}));return Rc(((h=N.elements)===null||h===void 0?void 0:h.content)||{},O),O.setElement(N.elements),O}getC2CRoamingMessagesByAnchor(Q){return pA(this,void 0,void 0,function*(){var h;try{const{conversationID:v,count:N,messageID:O,time:z,direction:X,shouldMarkCompleted:rA=!1}=Q;let DA=z,GA="";if(!z){const ue=O?fe.message.messageDataHandler.findMessage(O):null;if(DA=ue?.time||0,O&&this._historyMessageListFetchAnchors.has(v)){const He=this._historyMessageListFetchAnchors.get(v);DA=He.lastMessageTime,GA=He.messageKey}}const JA=v.replace(wg.CONV_C2C,""),ee=yield Gc({count:N,lastMessageTime:DA,messageKey:GA,peerAccount:JA,direction:X});if(ee){const{MsgList:ue=[],Complete:He,MsgKey:At,LastMsgTime:st}=ee;this._historyMessageListFetchAnchors.set(v,{messageKey:At,lastMessageTime:st});const Gt=[];for(let zi=0;zi{const{tag:O,value:z}=N;O&&O.indexOf(lg)>-1?v.profileCustomField.push({key:O,value:z}):kl.has(O)&&(v[kl.get(O)]=z)}),Object.assign(Object.assign({},xa),v)}parseProfileItem(Q=[]){const h=[];return Q.forEach(v=>{h.push({tag:v.Tag,value:v.Value})}),h}parseProfileList(Q=[]){const h=[];return Q.forEach(v=>{h.push({tag:v.Tag,value:v.ValueBytes})}),h}convertParamsToProfile(Q){const h=[];return Object.keys(Q).forEach(v=>{v!==rr&&h.push({tag:br[v.toUpperCase()],value:Q[v]})}),Q.profileCustomField&&p(Q.profileCustomField)&&Q.profileCustomField.forEach(v=>{h.push({tag:v.key,value:v.value})}),h}normalizeProfileFields(Q){const h={},v=[];return Q.forEach(N=>{const{tag:O,value:z}=N;if(O&&O.indexOf(lg)>-1&&v.push({key:O,value:z}),kl.has(O)&&z!==void 0){const X=kl.get(O);h[X]=z}}),v.length>0&&(h.profileCustomField=v),h}};const{generateProtocolData:BI}=fe.common;function jI(Q){return pA(this,void 0,void 0,function*(){const h="profile.portrait_get_all",v={From_Account:qn(),UserItem:[]};Q.forEach(X=>{v.UserItem.push({CustomSequence:0,StandardSequence:0,To_Account:X})});const N=BI({servcmd:h,data:v}),O=`${N.head.seq}${h}`,z=yield fe.channel.sendPacket(N,{requestId:O});if(z)return function(X){const{ActionStatus:rA,ErrorCode:DA,ErrorDisplay:GA,ErrorInfo:JA,UserProfileItem:ee}=X,ue=[];return ee.map(He=>{const{To_Account:At,CustomSequence:st,ResultCode:Gt,ResultInfo:xt,StandardSequence:Ui,ProfileItem:ao}=He,zi=da.parseProfileItem(ao);ue.push({userId:At,customSequence:st,resultCode:Gt,resultInfo:xt,standardSequence:Ui,profileItem:zi})}),{actionStatus:rA,errorCode:DA,errorDisplay:GA,errorInfo:JA,userProfile:ue}}(z)})}function Ca(Q){return Xr.getFriendMap().has(Q)}const{isEmpty:al}=fe.utils;class wE{constructor(){this._strangerProfileMap=new Map}init(){Ks.getInstance().registerApi({apiName:"getMyProfile",context:this}),Ks.getInstance().registerApi({apiName:"getUserProfile",context:this}),Ks.getInstance().registerApi({apiName:"updateMyProfile",context:this}),this.createProfile=da.createProfile.bind(da);const{notificationCenter:h}=fe;en.getInstance().registerWorkflowStep(sr.SYNC_SERVER_INFO_AFTER_LOGIN,Pt.USER_PROFILE_SYNC,this.getMyProfileCacheThenServer,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,h.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),h.subscribeInnerEvent(Ii.LOGOUT,this._reset,this),h.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}getMyProfile(){return pA(this,void 0,void 0,function*(){try{const h=qn(),v=yield jI([h]);if(v){const N=this._handleProfileFormResponse(v)[0];return Xr.getUserProfileMap().set(h,N),{code:0,data:N}}}catch(h){const{errorCode:v,errorInfo:N}=h;throw new ss({functionName:"getMyProfile",code:v,message:N})}})}getUserProfile(h){return pA(this,void 0,void 0,function*(){try{let{userIDList:v}=h;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>Ug&&(fe.ssoLog.warn("getUserProfile","userIdListToRequest.length > 1000"),N.length=Ug);const{data:z,error:X}=yield this._batchFetchUserProfiles(N),rA=N.length,DA=z.length,GA=rA-DA;if(O.length===0&&rA===GA&&!al(X))throw X;if(p(z))return z.forEach(ee=>{Ca(ee.userID)?Xr.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 ss(v)}})}getMyProfileCacheThenServer(){return pA(this,void 0,void 0,function*(){const h=qn(),v=Xr.getUserProfileMap().has(h);return v?{code:0,data:v}:this.getMyProfile()})}updateMyProfile(h){return pA(this,void 0,void 0,function*(){const v=qn(),N={};for(const z in h)h[z]!==void 0&&(N[z]=h[z]);const O=da.convertParamsToProfile(N);try{yield function(GA){return pA(this,void 0,void 0,function*(){const JA="profile.portrait_set",ee=BI({servcmd:JA,data:GA}),ue=`${ee.head.seq}${JA}`,He=yield fe.channel.sendPacket(ee,{requestId:ue});if(He){const{ActionStatus:At,ErrorCode:st,ErrorDisplay:Gt,ErrorInfo:xt}=He;return{actionStatus:At,errorCode:st,errorDisplay:Gt,errorInfo:xt}}})}({From_Account:v,ProfileItem:O});const X=Xr.getUserProfile(v);let rA;rA=X?Object.assign(Object.assign({},X),N):da.createProfile(v,O);const DA=!Mg(X,rA,["lastUpdatedTime"]);return rA.lastUpdatedTime=Date.now(),Xr.getUserProfileMap().set(v,rA),DA&&this._emitProfileUpdated(rA),{code:0,data:rA,successLog:{message:`profileArray: ${fe.utils.safeStringify(O)}`}}}catch(z){const{errorCode:X,errorInfo:rA}=z;throw new ss({functionName:"updateMyProfile",code:X,message:rA,moreMessage:`params: ${fe.utils.safeStringify(h)}`})}})}updateMyNickAndAvatar(h){return pA(this,void 0,void 0,function*(){const v=qn(),N=Date.now(),O=Xr.getUserProfile(v);let z={};z=O?Object.assign(O,h):da.createProfile(v,h),z.lastUpdatedTime=N,Xr.getUserProfileMap().set(v,z)})}_onProfileDataModify(h){const v=function(z){const{Profile_Account:X,PushType:rA,ProfileList:DA}=z;return{userId:X,pushType:rA,profileList:da.parseProfileList(DA)}}(h.ProfileDataMod[0]);if(al(v))return;const{isProfileUpdated:N,profile:O}=this._handleProfileModified(v);N&&this._emitProfileUpdated(O)}_emitProfileUpdated(h){fe.notificationCenter.emitInnerEvent(Ii.PROFILE_UPDATE,{name:Ii.PROFILE_UPDATE,data:[h]}),fe.notificationCenter.emitOuterEvent(Dn.PROFILE_UPDATED,{name:Dn.PROFILE_UPDATED,data:[h]}),Xg.updateConversation(`C2C${h?.userID}`,{userProfile:h})}_dispose(){const{notificationCenter:h}=fe;h.unSubscribeInnerEvent(Ii.LOGOUT,this._reset,this),h.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,h.InnerEventSubType.PROFILE_MODIFIED,this._onProfileDataModify,this),h.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this),this._reset()}_handleProfileModified(h){const{userId:v,profileList:N}=h,O=Xr.getUserProfile(v);if(!(qn()===v||Ca(v)&&O))return{isProfileUpdated:!1,profile:null};const z=da.normalizeProfileFields(N),X=Object.keys(z).some(JA=>JA===rr?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,rr)?this._mergeProfileCustomField(O.profileCustomField,z.profileCustomField):O.profileCustomField,GA=Object.assign(Object.assign(Object.assign({},O),z),{profileCustomField:DA,lastUpdatedTime:rA});return Xr.getUserProfileMap().set(v,GA),{isProfileUpdated:X,profile:GA}}_filterRequestAndCacheUsers(h){const v=[],N=[];return h.forEach(O=>{const z=Xr.getUserProfileMap().has(O);Ca(O)&&z?N.push(Xr.getUserProfile(O)):this._isStrangerAndProfileValid(O)?N.push(this._strangerProfileMap.get(O)):v.push(O)}),{userIdListToRequest:v,profileFromCache:N}}_handleProfileFormResponse(h){const{userProfile:v}=h;if(!Array.isArray(v))return[];const N=v.filter(z=>z.userId!=="@TLS#NOT_FOUND"&&z.userId!==""&&!al(z.profileItem)),O=Date.now();return N.map(z=>{const X=da.createProfile(z.userId,z.profileItem);return X.lastUpdatedTime=O,X})}_isStrangerAndProfileValid(h){var v;if(!Ca(h)){const{lastUpdatedTime:N=0}=this._strangerProfileMap.get(h)||{},O=((v=fe.store.get("cloudConfig"))===null||v===void 0?void 0:v.stranger_profile_expiration_time)||6e5;return Date.now()-N<=O}return!1}_chunkUserIDList(h,v){return Array.from({length:Math.ceil(h.length/v)},(N,O)=>h.slice(O*v,(O+1)*v))}_batchFetchUserProfiles(h){return pA(this,void 0,void 0,function*(){const v=[],N=[];let O={};return this._chunkUserIDList(h,100).forEach(z=>{v.push(jI(z))}),(yield Promise.allSettled(v)).forEach(z=>{if(z.status==="fulfilled"){const X=z.value,rA=this._handleProfileFormResponse(X);p(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(h=[],v=[]){if(!p(v)||v.length===0)return!1;if(!p(h)||h.length===0)return!0;const N=new Map(h.map(O=>[O.key,O.value]));return v.some(O=>N.get(O.key)!==O.value)}_mergeProfileCustomField(h=[],v=[]){const N=p(h)?h.map(O=>Object.assign({},O)):[];return p(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(){Xr.getUserProfileMap().clear(),this._strangerProfileMap.clear()}}const WI=new Map,_E=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];for(let Q=0,h=_E.length;Q>(-2*z&6)):0)O="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(O);try{return decodeURIComponent(escape(v))}catch(N){return console.warn(N),""}}const{isEmpty:zI}=fe.utils,{generateProtocolData:Ut}=fe.common;function ku(Q){return pA(this,void 0,void 0,function*(){const h="im_open_status.ws_get_user_status",v=Ut({servcmd:h,data:{To_Account:Q}}),N=`${v.head.seq}${h}`,O=yield fe.channel.sendPacket(v,{requestId:N});if(O)return function(z){const{ErrorCode:X,ErrorInfo:rA,ErrorList:DA=[],UserStatusList:GA=[]}=z,JA=GA.map(ue=>{const{To_Account:He,Status:At,CustomStatus:st,Detail:Gt=[]}=ue;return{userID:He,statusType:At,customStatus:xr(st),onlineDevices:Lu(Gt)}}),ee=DA.map(ue=>{const{To_Account:He,Invalid_Account:At,ErrorCode:st,ErrorInfo:Gt}=ue;return{userID:zI(At)?He:At,code:st,message:Gt}});return{errorCode:X,errorInfo:rA,successUserList:JA,failureUserList:ee}}(O)})}function Lu(Q){const h=[];return Q?.forEach(v=>{const{Platform:N,Status:O}=v;O==="Online"&&h.push(N)}),h}class lC{constructor(){this._customStatus=""}init(){const{notificationCenter:h}=fe;Ks.getInstance().registerApi({apiName:"getUserStatus",context:this}),Ks.getInstance().registerApi({apiName:"setSelfStatus",context:this}),Ks.getInstance().registerApi({apiName:"subscribeUserStatus",context:this}),Ks.getInstance().registerApi({apiName:"unsubscribeUserStatus",context:this}),en.getInstance().registerWorkflowStep(sr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Pt.USER_STATUS_UPDATE,this._onReOnline,this),h.subscribeInnerEvent(Ii.MESSAGE_PUSH,h.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),h.subscribeInnerEvent(Ii.LOGOUT,this._reset,this),h.subscribeInnerEvent(Ii.DESTROY,this._dispose,this)}setSelfStatus(h){return pA(this,void 0,void 0,function*(){const v=qn(),{customStatus:N}=h;try{return yield function(O){return pA(this,void 0,void 0,function*(){const z="im_open_status.ws_set_custom_status",X=Ut({servcmd:z,data:{CustomStatus:O}}),rA=`${X.head.seq}${z}`,DA=yield fe.channel.sendPacket(X,{requestId:rA});if(DA){const{ErrorCode:GA,ErrorInfo:JA}=DA;return{errorCode:GA,errorInfo:JA}}})}(N),this._customStatus=N,{code:0,data:{userID:v,statusType:tc,customStatus:N},successLog:{message:`customStatus: ${N}`}}}catch(O){const{errorCode:z,errorInfo:X}=O;throw new ss({functionName:"setSelfStatus",code:z,message:X})}})}getUserStatus(h){return pA(this,void 0,void 0,function*(){const{userIDList:v=[]}=h;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(h){const v=xr(h);this._customStatus=v}subscribeUserStatus(h){return pA(this,void 0,void 0,function*(){try{const{userIDList:v=[]}=h;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}=fe,GA="im_open_status.ws_status_subscribe",JA=Ut({servcmd:GA,data:{To_Account:rA}}),ee=`${JA.head.seq}${GA}`;return yield DA.sendPacket(JA,{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 ss({functionName:"subscribeUserStatus",code:N})}})}unsubscribeUserStatus(h){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("unsubscribeUserStatus");const{userIDList:v=[]}=h,N=this._getMaxUserCount("unsubscribe"),O=this._sliceUserIDList(v,N),z=yield function(rA){return pA(this,void 0,void 0,function*(){const{channel:DA}=fe,GA="im_open_status.ws_status_unsubscribe";let JA={};JA=rA.length===0?{UnsubscribeAll:1}:{To_Account:rA};const ee=Ut({servcmd:GA,data:JA}),ue=`${ee.head.seq}${GA}`;return yield DA.sendPacket(ee,{requestId:ue})})}(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 ss({functionName:"unsubscribeUserStatus",code:N})}})}_onUserStatusUpdate(h){const{UserStatusList:v=[]}=h||{},N=v.map(O=>{const{To_Account:z,Status:X,CustomStatus:rA,Platform:DA}=O,GA={userID:z,statusType:X,customStatus:xr(rA)};return DA&&(GA.onlineDevices=DA),GA});this._emitUserStatusUpdatedEvent(N)}_onReOnline(h){const v=xr(h.data.customStatus);if(this._customStatus===v)return;this._customStatus=v;const N={userID:qn(),statusType:tc,customStatus:v};this._emitUserStatusUpdatedEvent(N)}_emitUserStatusUpdatedEvent(h){fe.notificationCenter.emitOuterEvent(Dn.USER_STATUS_UPDATED,{name:Dn.USER_STATUS_UPDATED,data:h})}_sliceUserIDList(h,v){return h.slice(0,v)}_parseResponse(h){const{ErrorList:v=[]}=h;return v.map(N=>{const{To_Account:O,Invalid_Account:z,ErrorCode:X,ErrorInfo:rA}=N;return{userID:fe.utils.isEmpty(z)?O:z,code:X,message:rA}})}_checkBusinessCapabilityBits(h){if(!fe.store.get("commercialConfig").get(vr))throw new ss({functionName:h,code:ko.NO_USE,replacement1:h})}_getMaxUserCount(h){const v=fe.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[h],X=v[O]||z;return parseInt(X,10)}_getMyStatus(){return{code:0,data:{successUserList:[{userID:qn(),statusType:tc,customStatus:this._customStatus}],failureUserList:[]}}}_getUserStatus(h){return pA(this,void 0,void 0,function*(){try{this._checkBusinessCapabilityBits("getUserStatus");const v=this._getMaxUserCount("query"),N=this._sliceUserIDList(h,v),O=yield ku(N),{successUserList:z,failureUserList:X}=O||{};return{code:0,data:{successUserList:z,failureUserList:X}}}catch(v){const{errorCode:N}=v;throw new ss({functionName:"getUserStatus",code:N})}})}_isOnlyMeInArray(h){const v=qn();return h.length===1&&h.indexOf(v)>-1}_dispose(){const{notificationCenter:h}=fe;h.unSubscribeInnerEvent(Ii.MESSAGE_PUSH,h.InnerEventSubType.USER_STATUS_UPDATE,this._onUserStatusUpdate,this),h.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this),h.unSubscribeInnerEvent(Ii.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(Q){for(const h of Q){if(typeof h!="object")return"Each item in profileCustomField must be an object";if(typeof h?.key!="string")return"Each item.key in profileCustomField must be a string";if(!h?.key.startsWith(lg))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 sA{constructor(){this.userProfile=new wE,this.userStatus=new lC,this.userProfile.init(),this.userStatus.init(),Sc({auth:L,params:q})}}function G(Q){const h=[];if(!l(Q))return h;const v=Q.length;if(v===0)return h;for(let N=v-1;N>=0;N--)Q[N]==="1"&&h.push(2**(v-N-1));return h}var x,iA,uA;(function(Q){Q.NOT_START="notStart",Q.PENDING="pending",Q.RESOLVED="resolved",Q.REJECTED="rejected"})(x||(x={})),function(Q){Q[Q.C2C=1]="C2C",Q[Q.GROUP=2]="GROUP"}(iA||(iA={})),function(Q){Q[Q.C2C=8]="C2C",Q[Q.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:h}=fe;en.getInstance().registerWorkflowStep(sr.SYNC_SERVER_INFO_AFTER_RE_ONLINE,Pt.CONVERSATION_RECOVER,this._syncConversationList,this),en.getInstance().registerWorkflowStep(sr.SYNC_SERVER_INFO_AFTER_LOGIN,Pt.CONVERSATION_LIST_SYNC,this._syncConversationListAfterLogin,this),h.subscribeInnerEvent(Ii.LOGOUT,this._reset,this),h.subscribeInnerEvent(Ii.DESTROY,this._dispose,this),fe.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:h,utils:{safeStringify:v}}=fe;h.debug("_syncConversationList","start");try{const N=yield this._pagingGetConversationList(!0);this._pagingStatus=x.RESOLVED;const{conversationList:O=[]}=N||{};return h.info("_syncConversationList",`success count:${O.length}`),N}catch(N){const O=new ss(N);h.error("_syncConversationList",`fail ${v(N)}`,{error:O})}})}_pagingGetConversationList(h){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:ue,pagingTimeStamp:He,pagingStartIndex:At,pagingPinnedTimeStamp:st,pagingPinnedStartIndex:Gt}=ee;return zg({servcmd:"recentcontact.page_get",data:{AssistFlags:31,MsgAssistFlags:15,OrderType:1,From_Account:ue,StartIndex:At,TimeStamp:He,TopStartIndex:Gt,TopTimeStamp:st}})})}({fromAccount:qn(),pagingTimeStamp:h?this._pagingTimeStamp:0,pagingStartIndex:h?this._pagingStartIndex:0,pagingPinnedTimeStamp:h?this._pagingPinnedTimeStamp:0,pagingPinnedStartIndex:h?this._pagingPinnedStartIndex:0}),{CompleteFlag:O,SessionItem:z=[],TimeStamp:X,StartIndex:rA,TopTimeStamp:DA,TopStartIndex:GA}=N||{};let JA=[];if(O===1&&(this._pagingStatus=x.RESOLVED),z.length>0&&(JA=this._getConversationOptions(z),v.push(...JA)),fe.notificationCenter.emitInnerEvent(Ii.SYNC_CONVERSATION_LIST,{conversationUpdateFieldList:JA}),this._pagingTimeStamp=X,this._pagingStartIndex=rA,this._pagingPinnedTimeStamp=DA,this._pagingPinnedStartIndex=GA,O!==1){const{conversationList:ee}=yield this._pagingGetConversationList(h);v.push(...ee)}return{conversationList:v}}catch(v){throw v}})}_getConversationOptions(h){const{utils:{isUndefined:v}}=fe,N=this._convertConversationKey(h);return this._filterValidConversations(N).map(O=>(v(O.lastMsg)&&(O.lastMsg={elements:[]}),O.type===iA.C2C?this._assembleC2COption(O):this._assembleGroupOption(O)))}_filterValidConversations(h){return h.filter(({type:v,userID:N})=>v===iA.C2C&&!function(O){let z;return O.startsWith(Cs.CONV_C2C)&&(z=O.replace(Cs.CONV_C2C,"")),z==="@TLS#ERROR"||z==="@TLS#NOT_FOUND"}(N)||v===2)}_assembleC2COption(h){var v,N,O,z,X,rA,DA,GA;const JA=this._createUserprofile(h);return{conversationID:`${Cs.CONV_C2C}${h.userID}`,type:Cs.CONV_C2C,lastMessage:{lastTime:h.time,lastSequence:h.sequence,fromAccount:h.lastC2CMsgFromAccount,type:!((v=h.lastMsg)===null||v===void 0)&&v.elements[0]?(N=h.lastMsg)===null||N===void 0?void 0:N.elements[0].type:null,payload:!((O=h.lastMsg)===null||O===void 0)&&O.elements[0]?this._amendLayersOverLimitProp(h.lastMsg.elements[0].content):null,cloudCustomData:((rA=(X=(z=h.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:h.lastMessageFlag===uA.C2C,onlineOnlyFlag:!1,nick:"",nameCard:"",version:0,isPeerRead:this._computeIsPeerRead(h),revoker:((GA=(DA=h.lastMsg)===null||DA===void 0?void 0:DA.revokerInfo)===null||GA===void 0?void 0:GA.revoker)||null},unreadCount:0,userProfile:JA,peerReadTime:h.peerReadTime,isPinned:h.isPinned===1,customData:h.customMark||"",markList:G(h.standardMark),conversationGroupList:[],remark:h.friendRemark||"",messageRemindType:this._transMsgRemindType(h.messageRemindType)}}_createUserprofile(h){var v;const{userID:N,nick:O,peerAvatar:z}=h,X=[{tag:"Tag_Profile_IM_Nick",value:O},{tag:"Tag_Profile_IM_Image",value:z}];return(v=fe.user.userProfile)===null||v===void 0?void 0:v.createProfile(N,X)}_computeIsPeerRead(h){const v=qn(),{lastC2CMsgFromAccount:N,time:O,c2cPeerReadTime:z}=h;return N===v&&O<=z}_assembleGroupOption(h){var v,N,O,z,X;return{conversationID:`${Cs.CONV_GROUP}${h.groupID}`,type:Cs.CONV_GROUP,lastMessage:Object.assign(Object.assign({lastTime:h.time,lastSequence:h.sequence,fromAccount:h.msgGroupFromAccount},this._patchTypeAndPayload(h)),{cloudCustomData:((O=(N=(v=h.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:h.lastMessageFlag===uA.GROUP,onlineOnlyFlag:!1,nick:h.msgGroupFromNickName||"",nameCard:h.msgGroupFromCardName||"",revoker:((X=(z=h.lastMsg)===null||z===void 0?void 0:z.revokerInfo)===null||X===void 0?void 0:X.revoker)||null}),groupProfile:{groupID:h.groupID,name:h.groupNick,avatar:h.groupImage,type:h.groupType,nextMessageSeq:h.nextMessageSeq},unreadCount:this._computeGroupUnreadCount(h),peerReadTime:0,isPinned:h.isPinned===1,version:0,customData:h.customMark||"",markList:G(h.standardMark),conversationGroupList:[],messageRemindType:this._transMsgRemindType(h.messageRemindType),subType:h.groupType}}_convertConversationKey(h){return h.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(h){var v,N,O;const{utils:{isEmpty:z}}=fe;if(z(h))return null;let X="",rA=null;if(!z(h.GroupTips)){const{From_Account:DA,GroupName:GA}=((v=h.GroupTips)===null||v===void 0?void 0:v.GroupInfo)||{};X=Cs.MSG_GRP_TIP,rA=Object.assign(Object.assign({},this._parseContent(X,h.GroupTips.MsgBody)),{groupProfile:{from:DA,groupName:GA}})}return h.MsgBody&&(X=(N=h.MsgBody[0])===null||N===void 0?void 0:N.MsgType,rA=this._parseContent(X,h.MsgBody[0])),{event:h.Event,elements:[{type:X,content:rA,cloudCustomData:h.CloudCustomData}],revokerInfo:{revoker:(O=h.RevokerInfo)===null||O===void 0?void 0:O.Revoker_Account}}}_parseContent(h,v){var N;if(!v)return v;const O=fe.message.messageFactory.getElementClass(h);return O?(N=O.parseServerPushElement(v))===null||N===void 0?void 0:N.content:v}_amendLayersOverLimitProp(h){const{LayersOverLimit:v}=h;return yo(h,["LayersOverLimit"]).layersOverLimit=v===1,h}_transMsgRemindType(h){let v="";return h===0?v=Cs.MSG_REMIND_ACPT_AND_NOTE:h===1?v=Cs.MSG_REMIND_DISCARD:h===2?v=Cs.MSG_REMIND_ACPT_NOT_NOTE:h===3&&(v=Cs.NOT_RECEIVE_OFFLINE_PUSH_EXCEPT_AT),v}_patchTypeAndPayload(h){var v;const{utils:{isUndefined:N}}=fe,{event:O,elements:z=[]}=h.lastMsg||{};return N(O)?{type:z[0]?z[0].type:null,payload:z[0]?this._amendLayersOverLimitProp(z[0].content):null}:{type:Cs.MSG_GRP_TIP,payload:((v=z?.[0])===null||v===void 0?void 0:v.content)||{}}}_computeGroupUnreadCount(h){const{unreadCount:v=0,noUnreadCount:N=0}=h,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:h}=fe;h.unSubscribeInnerEvent(Ii.LOGOUT,this._reset,this),h.unSubscribeInnerEvent(Ii.DESTROY,this._dispose,this)}}class XA{constructor(){this.syncConversationHandler=new _A,this.syncConversationHandler.init()}}console.log(`TencentCloudLiteChat.VERSION:${Wr}`);var Qe={create:function(Q){var h,v;const{SDKAppID:N,testEnv:O=!1,devMode:z=!1,unlimitedAVChatRoom:X=!1,scene:rA="",oversea:DA=!1,instance:GA,disableIndependentDomain:JA=!1,proxyServer:ee=""}=Q;let ue=N;if(!function(At){if(typeof At=="number")return!0;const st=Number(At);return!Number.isNaN(st)}(ue))return console.error("Create SDK instance failed. Failed to parse the SDKAppID, please check the arguments"),null;if(ue=Number(ue),Rs.has(ue))return Rs.get(ue);let He=null;if(GA)He=GA,He._workflowManager&&en.setInstance(He._workflowManager),He._pluginManager&&He._pluginManager.installBuiltInPlugin(ur),GA.isReady()&&((v=(h=en.getInstance()).executeWorkflow)===null||v===void 0||v.call(h,sr.SYNC_SERVER_INFO_AFTER_LOGIN));else{const At=function(){function zi(){return(65536*(1+Math.random())|0).toString(16).substring(1)}return`${zi()+zi()}${zi()}${zi()}${zi()}${zi()}${zi()}${zi()}`}();fe.init({sdkAppId:ue,instanceId:At,testEnv:O,devMode:z,unlimitedAVChatRoom:X,disableIndependentDomain:JA,scene:rA,oversea:DA,sdkEdition:wu,version:Wr,proxyServer:ee}),en.getInstance().init(),fe.message=new rl,fe.user=new sA,fe.login=new $g,fe.conversation=new XA,Fo.getInstance().installBuiltInPlugin(ur),He=Ks.getInstance().exposeApiForClient(),He._workflowManager=en.getInstance(),He._pluginManager=Fo.getInstance();const{utils:{IS_WORKER_AVAILABLE:st,USER_AGENT:Gt,getPlatformType:xt,isIOSWebView:Ui}}=fe,ao=`instanceID:${At} SDKAppID:${N} platform:${qA} host:${xt()} isIOSWebView:${Ui} workerAvailable:${st} UserAgent:${Gt}`;fe.ssoLog.info("sdkConstruct",ao)}return Rs.set(ue,He),He},TSignaling:so,EVENT:Dn,VERSION:Wr,TYPES:Cs};return Qe})}(h1)),h1.exports}var $k={exports:{}},B1={exports:{}},hnA=B1.exports,Fz;function BnA(){return Fz||(Fz=1,function(t,i){(function(r,l){t.exports=l()})(hnA,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 pg<"u"?pg:typeof self<"u"?self:{};function u(A){return A&&A.__esModule&&Object.prototype.hasOwnProperty.call(A,"default")?A.default:A}var p=function(A){return A&&A.Math===Math&&A},y=p(typeof globalThis=="object"&&globalThis)||p(typeof window=="object"&&window)||p(typeof self=="object"&&self)||p(typeof l=="object"&&l)||p(typeof l=="object"&&l)||function(){return this}()||Function("return this")(),w={},_=function(A){try{return!!A()}catch{return!0}},k=!_(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!==7}),F=!_(function(){var A=function(){}.bind();return typeof A!="function"||A.hasOwnProperty("prototype")}),j=F,lA=Function.prototype.call,aA=j?lA.bind(lA):function(){return lA.apply(lA,arguments)},mA={},IA={}.propertyIsEnumerable,tA=Object.getOwnPropertyDescriptor,MA=tA&&!IA.call({1:2},1);mA.f=MA?function(A){var e=tA(this,A);return!!e&&e.enumerable}:IA;var PA,ge,de=function(A,e){return{enumerable:!(1&A),configurable:!(2&A),writable:!(4&A),value:e}},Ve=F,Be=Function.prototype,ct=Be.call,mt=Ve&&Be.bind.bind(ct,ct),Ke=Ve?mt:function(A){return function(){return ct.apply(A,arguments)}},Dt=Ke,qt=Dt({}.toString),It=Dt("".slice),re=function(A){return It(qt(A),8,-1)},qe=_,ft=re,si=Object,Vt=Ke("".split),gi=qe(function(){return!si("z").propertyIsEnumerable(0)})?function(A){return ft(A)==="String"?Vt(A,""):si(A)}:si,Fi=function(A){return A==null},_o=Fi,to=TypeError,uo=function(A){if(_o(A))throw new to("Can't call method on "+A);return A},Ys=gi,ki=uo,os=function(A){return Ys(ki(A))},Ko=typeof document=="object"&&document.all,$i=Ko===void 0&&Ko!==void 0?function(A){return typeof A=="function"||A===Ko}:function(A){return typeof A=="function"},jt=$i,io=function(A){return typeof A=="object"?A!==null:jt(A)},bi=y,Ms=$i,qA=function(A,e){return arguments.length<2?(o=bi[A],Ms(o)?o:void 0):bi[A]&&bi[A][e];var o},ce=Ke({}.isPrototypeOf),Pe=y.navigator,kt=Pe&&Pe.userAgent,it=kt?String(kt):"",gt=y,Xt=it,$t=gt.process,Ge=gt.Deno,je=$t&&$t.versions||Ge&&Ge.version,Mt=je&&je.v8;Mt&&(ge=(PA=Mt.split("."))[0]>0&&PA[0]<4?1:+(PA[0]+PA[1])),!ge&&Xt&&(!(PA=Xt.match(/Edge\/(\d+)/))||PA[1]>=74)&&(PA=Xt.match(/Chrome\/(\d+)/))&&(ge=+PA[1]);var Rt=ge,Oi=Rt,Qo=_,To=y.String,oo=!!Object.getOwnPropertySymbols&&!Qo(function(){var A=Symbol("symbol detection");return!To(A)||!(Object(A)instanceof Symbol)||!Symbol.sham&&Oi&&Oi<41}),No=oo&&!Symbol.sham&&typeof Symbol.iterator=="symbol",$s=qA,rn=$i,us=ce,an=Object,yo=No?function(A){return typeof A=="symbol"}:function(A){var e=$s("Symbol");return rn(e)&&us(e.prototype,an(A))},pA=String,Jn=function(A){try{return pA(A)}catch{return"Object"}},Br=$i,Es=Jn,jr=TypeError,Pi=function(A){if(Br(A))return A;throw new jr(Es(A)+" is not a function")},vs=Pi,ir=Fi,An=function(A,e){var o=A[e];return ir(o)?void 0:vs(o)},wn=aA,Jt=$i,fg=io,On=TypeError,Gn={exports:{}},Vs=y,Qr=Object.defineProperty,Pn=function(A,e){try{Qr(Vs,A,{value:e,configurable:!0,writable:!0})}catch{Vs[A]=e}return e},pr=y,po=Pn,gn="__core-js_shared__",fl=Gn.exports=pr[gn]||po(gn,{});(fl.versions||(fl.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,mr=cn,ks=function(A,e){return mr[A]||(mr[A]=e||{})},Yc=uo,ps=Object,rs=function(A){return ps(Yc(A))},Bu=rs,ja=Ke({}.hasOwnProperty),ds=Object.hasOwn||function(A,e){return ja(Bu(A),e)},og=Ke,LI=0,Xo=Math.random(),Zi=og(1.1.toString),Qc=function(A){return"Symbol("+(A===void 0?"":A)+")_"+Zi(++LI+Xo,36)},sg=ks,yg=ds,la=Qc,Go=oo,Wr=No,wo=y.Symbol,Vc=sg("wks"),Hn=Wr?wo.for||wo:wo&&wo.withoutSetter||la,Js=function(A){return yg(Vc,A)||(Vc[A]=Go&&yg(wo,A)?wo[A]:Hn("Symbol."+A)),Vc[A]},Dg=aA,pc=io,fn=yo,Na=An,In=function(A,e){var o,a;if(e==="string"&&Jt(o=A.toString)&&!fg(a=wn(o,A))||Jt(o=A.valueOf)&&!fg(a=wn(o,A))||e!=="string"&&Jt(o=A.toString)&&!fg(a=wn(o,A)))return a;throw new On("Can't convert object to primitive value")},ms=TypeError,Ia=Js("toPrimitive"),yn=function(A,e){if(!pc(A)||fn(A))return A;var o,a=Na(A,Ia);if(a){if(e===void 0&&(e="default"),o=Dg(a,A,e),!pc(o)||fn(o))return o;throw new ms("Can't convert object to primitive value")}return e===void 0&&(e="number"),In(A,e)},Ga=yn,ya=yo,$=function(A){var e=Ga(A,"string");return ya(e)?e:e+""},K=io,RA=y.document,KA=K(RA)&&K(RA.createElement),Ae=function(A){return KA?RA.createElement(A):{}},pe=Ae,Fe=!k&&!_(function(){return Object.defineProperty(pe("div"),"a",{get:function(){return 7}}).a!==7}),Ue=k,ot=aA,ut=mA,St=de,Ot=os,li=$,nt=ds,Ft=Fe,Ji=Object.getOwnPropertyDescriptor;w.f=Ue?Ji:function(A,e){if(A=Ot(A),e=li(e),Ft)try{return Ji(A,e)}catch{}if(nt(A,e))return St(!ot(ut.f,A,e),A[e])};var qi={},Hs=k&&_(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),Mi=io,Wo=String,Sg=TypeError,or=function(A){if(Mi(A))return A;throw new Sg(Wo(A)+" is not an object")},fr=k,xn=Fe,yl=Hs,qs=or,tI=$,jg=TypeError,mc=Object.defineProperty,Qu=Object.getOwnPropertyDescriptor,Da="enumerable",Dl="configurable",fe="writable";qi.f=fr?yl?function(A,e,o){if(qs(A),e=tI(e),qs(o),typeof A=="function"&&e==="prototype"&&"value"in o&&fe in o&&!o[fe]){var a=Qu(A,e);a&&a[fe]&&(A[e]=o.value,o={configurable:Dl in o?o[Dl]:a[Dl],enumerable:Da in o?o[Da]:a[Da],writable:!1})}return mc(A,e,o)}:mc:function(A,e,o){if(qs(A),e=tI(e),qs(o),xn)try{return mc(A,e,o)}catch{}if("get"in o||"set"in o)throw new jg("Accessors not supported");return"value"in o&&(A[e]=o.value),A};var me=qi,Mg=de,ng=k?function(A,e,o){return me.f(A,e,Mg(1,o))}:function(A,e,o){return A[e]=o,A},vg={exports:{}},Dn=k,yr=ds,Ii=Function.prototype,so=Dn&&Object.getOwnPropertyDescriptor,Jc=yr(Ii,"name"),Wg={PROPER:Jc&&function(){}.name==="something",CONFIGURABLE:Jc&&(!Dn||Dn&&so(Ii,"name").configurable)},Rg=$i,Or=cn,fc=Ke(Function.toString);Rg(Or.inspectSource)||(Or.inspectSource=function(A){return fc(A)});var Hc,rg,pu,uE=Or.inspectSource,wg=$i,ba=y.WeakMap,yc=wg(ba)&&/native code/.test(String(ba)),EE=Qc,ka=ks("keys"),oa=function(A){return ka[A]||(ka[A]=EE(A))},_g={},iI=yc,Cs=y,ko=io,ua=ng,sr=ds,Pt=cn,Ht=oa,Tg=_g,oI="Object already initialized",nr=Cs.TypeError,UI=Cs.WeakMap;if(iI||Pt.state){var Wa=Pt.state||(Pt.state=new UI);Wa.get=Wa.get,Wa.has=Wa.has,Wa.set=Wa.set,Hc=function(A,e){if(Wa.has(A))throw new nr(oI);return e.facade=A,Wa.set(A,e),e},rg=function(A){return Wa.get(A)||{}},pu=function(A){return Wa.has(A)}}else{var sa=Ht("state");Tg[sa]=!0,Hc=function(A,e){if(sr(A,sa))throw new nr(oI);return e.facade=A,ua(A,sa,e),e},rg=function(A){return sr(A,sa)?A[sa]:{}},pu=function(A){return sr(A,sa)}}var un={set:Hc,get:rg,has:pu,enforce:function(A){return pu(A)?rg(A):Hc(A,{})},getterFor:function(A){return function(e){var o;if(!ko(e)||(o=rg(e)).type!==A)throw new nr("Incompatible receiver, "+A+" required");return o}}},Sn=Ke,mu=_,Ng=$i,La=ds,qc=k,FI=Wg.CONFIGURABLE,dE=uE,sI=un.enforce,fu=un.get,Sl=String,Dc=Object.defineProperty,yu=Sn("".slice),Du=Sn("".replace),Ml=Sn([].join),ss=qc&&!mu(function(){return Dc(function(){},"length",{value:8}).length!==8}),as=String(String).split("String"),td=vg.exports=function(A,e,o){yu(Sl(e),0,7)==="Symbol("&&(e="["+Du(Sl(e),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),o&&o.getter&&(e="get "+e),o&&o.setter&&(e="set "+e),(!La(A,"name")||FI&&A.name!==e)&&(qc?Dc(A,"name",{value:e,configurable:!0}):A.name=e),ss&&o&&La(o,"arity")&&A.length!==o.arity&&Dc(A,"length",{value:o.arity});try{o&&La(o,"constructor")&&o.constructor?qc&&Dc(A,"prototype",{writable:!1}):A.prototype&&(A.prototype=void 0)}catch{}var a=sI(A);return La(a,"source")||(a.source=Ml(as,typeof e=="string"?e:"")),A};Function.prototype.toString=td(function(){return Ng(this)&&fu(this).source||dE(this)},"toString");var nI=vg.exports,rI=$i,CE=qi,id=nI,vl=Pn,Dr=function(A,e,o,a){a||(a={});var c=a.enumerable,d=a.name!==void 0?a.name:e;if(rI(o)&&id(o,d,a),a.global)c?A[e]=o:vl(e,o);else{try{a.unsafe?A[e]&&(c=!0):delete A[e]}catch{}c?A[e]=o:CE.f(A,e,{value:o,enumerable:!1,configurable:!a.nonConfigurable,writable:!a.nonWritable})}return A},Sc={},Kc=Math.ceil,en=Math.floor,Rs=Math.trunc||function(A){var e=+A;return(e>0?en:Kc)(e)},Ea=Rs,zr=function(A){var e=+A;return e!=e||e===0?0:Ea(e)},jc=zr,od=Math.max,zg=Math.min,ag=function(A,e){var o=jc(A);return o<0?od(o+e,0):zg(o,e)},hE=zr,Zg=Math.min,qn=function(A){var e=hE(A);return e>0?Zg(e,9007199254740991):0},Ar=qn,Ua=function(A){return Ar(A.length)},sd=os,AC=ag,Su=Ua,OI=function(A){return function(e,o,a){var c=sd(e),d=Su(c);if(d===0)return!A&&-1;var C,f=AC(a,d);if(A&&o!=o){for(;d>f;)if((C=c[f++])!=C)return!0}else for(;d>f;f++)if((A||f in c)&&c[f]===o)return A||f||0;return!A&&-1}},Wc={includes:OI(!0),indexOf:OI(!1)},zc=ds,PI=os,aI=Wc.indexOf,Zc=_g,Xc=Ke([].push),Sa=function(A,e){var o,a=PI(A),c=0,d=[];for(o in a)!zc(Zc,o)&&zc(a,o)&&Xc(d,o);for(;e.length>c;)zc(a,o=e[c++])&&(~aI(d,o)||Xc(d,o));return d},Gg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],fs=Sa,Kn=Gg.concat("length","prototype");Sc.f=Object.getOwnPropertyNames||function(A){return fs(A,Kn)};var Mc={};Mc.f=Object.getOwnPropertySymbols;var xI=qA,YI=Sc,BE=Mc,zC=or,eC=Ke([].concat),ZC=xI("Reflect","ownKeys")||function(A){var e=YI.f(zC(A)),o=BE.f;return o?eC(e,o(A)):e},$c=ds,bg=ZC,no=w,tC=qi,QE=function(A,e,o){for(var a=bg(e),c=tC.f,d=no.f,C=0;CC;)uI.f(A,o=c[C++],a[o]);return A};var Lg,Ac=qA("document","documentElement"),cd=or,DE=_l,Tc=Gg,HI=_g,co=Ac,SE=Ae,Xa="prototype",qI="script",_u=oa("IE_PROTO"),Nc=function(){},EI=function(A){return"<"+qI+">"+A+""},il=function(A){A.write(EI("")),A.close();var e=A.parentWindow.Object;return A=null,e},ol=function(){try{Lg=new ActiveXObject("htmlfile")}catch{}ol=typeof document<"u"?document.domain&&Lg?il(Lg):function(){var e,o=SE("iframe"),a="java"+qI+":";return o.style.display="none",co.appendChild(o),o.src=String(a),(e=o.contentWindow.document).open(),e.write(EI("document.F=Object")),e.close(),e.F}():il(Lg);for(var A=Tc.length;A--;)delete ol[Xa][Tc[A]];return ol()};HI[_u]=!0;var Pa=Object.create||function(A,e){var o;return A!==null?(Nc[Xa]=cd(A),o=new Nc,Nc[Xa]=null,o[_u]=A):o=ol(),e===void 0?o:DE.f(o,e)},ME=Js,na=Pa,Mn=qi.f,Nr=ME("unscopables"),sl=Array.prototype;sl[Nr]===void 0&&Mn(sl,Nr,{configurable:!0,value:na(null)});var bl=function(A){sl[Nr][A]=!0},Gc=Wc.includes,vE=bl;_n({target:"Array",proto:!0,forced:_(function(){return!Array(1).includes()})},{includes:function(A){return Gc(this,A,arguments.length>1?arguments[1]:void 0)}}),vE("includes");var bc,Tu,gC,KI={},Ah=!_(function(){function A(){}return A.prototype.constructor=null,Object.getPrototypeOf(new A)!==A.prototype}),Nu=ds,dI=$i,nl=rs,cC=Ah,ra=oa("IE_PROTO"),ec=Object,cg=ec.prototype,CI=cC?ec.getPrototypeOf:function(A){var e=nl(A);if(Nu(e,ra))return e[ra];var o=e.constructor;return dI(o)&&e instanceof o?o.prototype:e instanceof ec?cg:null},RE=_,Gu=$i,bu=io,hI=CI,rl=Dr,Gr=Js("iterator"),br=!1;[].keys&&("next"in(gC=[].keys())?(Tu=hI(hI(gC)))!==Object.prototype&&(bc=Tu):br=!0);var lg=!bu(bc)||RE(function(){var A={};return bc[Gr].call(A)!==A});lg&&(bc={}),Gu(bc[Gr])||rl(bc,Gr,function(){return this});var rr={IteratorPrototype:bc,BUGGY_SAFARI_ITERATORS:br},vr=qi.f,tc=ds,Ug=Js("toStringTag"),xa=function(A,e,o){A&&!o&&(A=A.prototype),A&&!tc(A,Ug)&&vr(A,Ug,{configurable:!0,value:e})},kl=rr.IteratorPrototype,da=Pa,BI=de,jI=xa,Ca=KI,al=function(){return this},wE=function(A,e,o,a){var c=e+" Iterator";return A.prototype=da(kl,{next:BI(+!a,o)}),jI(A,c,!1),Ca[c]=al,A},WI=Ke,_E=Pi,xr=io,zI=function(A){return xr(A)||A===null},Ut=String,ku=TypeError,Lu=function(A,e,o){try{return WI(_E(Object.getOwnPropertyDescriptor(A,e)[o]))}catch{}},lC=io,q=uo,L=function(A){if(zI(A))return A;throw new ku("Can't set "+Ut(A)+" as a prototype")},sA=Object.setPrototypeOf||("__proto__"in{}?function(){var A,e=!1,o={};try{(A=Lu(Object.prototype,"__proto__","set"))(o,[]),e=o instanceof Array}catch{}return function(a,c){return q(a),L(c),lC(a)&&(e?A(a,c):a.__proto__=c),a}}():void 0),G=_n,x=aA,iA=$i,uA=wE,_A=CI,XA=sA,Qe=xa,Q=ng,h=Dr,v=KI,N=Wg.PROPER,O=Wg.CONFIGURABLE,z=rr.IteratorPrototype,X=rr.BUGGY_SAFARI_ITERATORS,rA=Js("iterator"),DA="keys",GA="values",JA="entries",ee=function(){return this},ue=function(A,e,o,a,c,d,C){uA(o,e,a);var f,S,b,V=function(Oe){if(Oe===c&&$A)return $A;if(!X&&Oe&&Oe in CA)return CA[Oe];switch(Oe){case DA:case GA:case JA:return function(){return new o(this,Oe)}}return function(){return new o(this)}},J=e+" Iterator",cA=!1,CA=A.prototype,vA=CA[rA]||CA["@@iterator"]||c&&CA[c],$A=!X&&vA||V(c),he=e==="Array"&&CA.entries||vA;if(he&&(f=_A(he.call(new A)))!==Object.prototype&&f.next&&(_A(f)!==z&&(XA?XA(f,z):iA(f[rA])||h(f,rA,ee)),Qe(f,J,!0)),N&&c===GA&&vA&&vA.name!==GA&&(O?Q(CA,"name",GA):(cA=!0,$A=function(){return x(vA,this)})),c)if(S={values:V(GA),keys:d?$A:V(DA),entries:V(JA)},C)for(b in S)(X||cA||!(b in CA))&&h(CA,b,S[b]);else G({target:e,proto:!0,forced:X||cA},S);return CA[rA]!==$A&&h(CA,rA,$A,{name:c}),v[e]=$A,S},He=function(A,e){return{value:A,done:e}},At=os,st=bl,Gt=KI,xt=un,Ui=qi.f,ao=ue,zi=He,ui=k,Oo="Array Iterator",$o=xt.set,Qi=xt.getterFor(Oo),Ki=ao(Array,"Array",function(A,e){$o(this,{type:Oo,target:At(A),index:0,kind:e})},function(){var A=Qi(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,zi(void 0,!0);switch(A.kind){case"keys":return zi(o,!1);case"values":return zi(e[o],!1)}return zi([o,e[o]],!1)},"values"),js=Gt.Arguments=Gt.Array;if(st("keys"),st("values"),st("entries"),ui&&js.name!=="values")try{Ui(js,"name",{value:"values"})}catch{}var we=Pi,vt=rs,FA=gi,Wt=Ua,En=TypeError,Zt="Reduce of empty array with no initial value",Is=function(A){return function(e,o,a,c){var d=vt(e),C=FA(d),f=Wt(d);if(we(o),f===0&&a<2)throw new En(Zt);var S=A?f-1:0,b=A?-1:1;if(a<2)for(;;){if(S in C){c=C[S],S+=b;break}if(S+=b,A?S<0:f<=S)throw new En(Zt)}for(;A?S>=0:f>S;S+=b)S in C&&(c=o(c,C[S],S,d));return c}},vi={left:Is(!1),right:Is(!0)},Co=_,Et=function(A,e){var o=[][A];return!!o&&Co(function(){o.call(null,e||function(){return 1},1)})},Ct=y,Ig=it,bs=re,ji=function(A){return Ig.slice(0,A.length)===A},Yr=ji("Bun/")?"BUN":ji("Cloudflare-Workers")?"CLOUDFLARE":ji("Deno/")?"DENO":ji("Node.js/")?"NODE":Ct.Bun&&typeof Bun.version=="string"?"BUN":Ct.Deno&&typeof Deno.version=="object"?"DENO":bs(Ct.process)==="process"?"NODE":Ct.window&&Ct.document?"BROWSER":"REST",ic=Yr==="NODE",es=vi.left;_n({target:"Array",proto:!0,forced:!ic&&Rt>79&&Rt<83||!Et("reduce")},{reduce:function(A){var e=arguments.length;return es(this,A,e,e>1?arguments[1]:void 0)}});var aa=vi.right;_n({target:"Array",proto:!0,forced:!ic&&Rt>79&&Rt<83||!Et("reduceRight")},{reduceRight:function(A){return aa(this,A,arguments.length,arguments.length>1?arguments[1]:void 0)}});var ha=re,$r=Array.isArray||function(A){return ha(A)==="Array"},H=_n,BA=$r,yA=Ke([].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,ve=TypeError,le=Ke([].slice),Te=le,ne=Math.floor,Le=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=ne(o/2),f=Le(Te(A,0,C),e),S=Le(Te(A,C),e),b=f.length,V=S.length,J=0,cA=0;J3)){if(lm)return!0;if(ti)return ti<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++)fo.push({k:e+a,v:o})}for(fo.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},jy=Math.fround||function(A){return Ky(A,11920928955078125e-23,34028234663852886e22,11754943508222875e-54)},hv=Array,Y_=Math.abs,Id=Math.pow,V_=Math.floor,Wy=Math.log,J_=Math.LN2,zy={pack:function(A,e,o){var a,c,d,C=hv(o),f=8*o-e-1,S=(1<>1,V=e===23?Id(2,-24)-Id(2,-77):0,J=A<0||A===0&&1/A<0?1:0,cA=0;for((A=Y_(A))!=A||A===1/0?(c=A!=A?1:0,a=S):(a=V_(Wy(A)/J_),A*(d=Id(2,-a))<1&&(a--,d*=2),(A+=a+b>=1?V/d:V*Id(2,1-b))*d>=2&&(a++,d/=2),a+b>=S?(c=0,a=S):a+b>=1?(c=(A*d-1)*Id(2,e),a+=b):(c=A*Id(2,b-1)*Id(2,e),a=0));e>=8;)C[cA++]=255&c,c/=256,e-=8;for(a=a<0;)C[cA++]=255&a,a/=256,f-=8;return C[cA-1]|=128*J,C},unpack:function(A,e){var o,a=A.length,c=8*a-e-1,d=(1<>1,f=c-7,S=a-1,b=A[S--],V=127&b;for(b>>=7;f>0;)V=256*V+A[S--],f-=8;for(o=V&(1<<-f)-1,V>>=-f,f+=e;f>0;)o=256*o+A[S--],f-=8;if(V===0)V=1-C;else{if(V===d)return o?NaN:b?-1/0:1/0;o+=Id(2,e),V-=C}return(b?-1:1)*o*Id(2,V-e)}},H_=rs,Bv=ag,q_=Ua,Qv=function(A){for(var e=H_(this),o=q_(e),a=arguments.length,c=Bv(a>1?arguments[1]:void 0,o),d=a>2?arguments[2]:void 0,C=d===void 0?o:Bv(d,o);C>c;)e[c++]=A;return e},K_=$i,j_=io,Zy=sA,Xy=function(A,e,o){var a,c;return Zy&&K_(a=e.constructor)&&a!==o&&j_(c=a.prototype)&&c!==o.prototype&&Zy(A,c),A},mQ=y,Cm=Ke,hm=k,ud=Sr,W_=ng,z_=kg,Bm=ZI,$y=_,eh=pI,Z_=zr,X_=qn,Qm=um,pv=jy,AD=zy,pm=CI,mv=sA,$_=Qv,AT=le,fv=Xy,Ed=QE,mm=xa,dd=un,TE=Wg.PROPER,fm=Wg.CONFIGURABLE,IC="ArrayBuffer",th="DataView",Ou="prototype",Yi="Wrong index",ym=dd.getterFor(IC),dn=dd.getterFor(th),yv=dd.set,Pu=mQ[IC],Ws=Pu,ih=Ws&&Ws[Ou],Ul=mQ[th],sc=Ul&&Ul[Ou],NE=Object.prototype,fQ=mQ.Array,AB=mQ.RangeError,eT=Cm($_),tT=Cm([].reverse),yQ=AD.pack,DQ=AD.unpack,Dv=function(A){return[255&A]},Sv=function(A){return[255&A,A>>8&255]},eD=function(A){return[255&A,A>>8&255,A>>16&255,A>>24&255]},uC=function(A){return A[3]<<24|A[2]<<16|A[1]<<8|A[0]},eB=function(A){return yQ(pv(A),23,4)},tD=function(A){return yQ(A,52,8)},SQ=function(A,e,o){z_(A[Ou],e,{configurable:!0,get:function(){return o(this)[e]}})},Cd=function(A,e,o,a){var c=dn(A),d=Qm(o),C=!!a;if(d+e>c.byteLength)throw new AB(Yi);var f=c.bytes,S=d+c.byteOffset,b=AT(f,S,S+e);return C?b:tT(b)},hd=function(A,e,o,a,c,d){var C=dn(A),f=Qm(o),S=a(+c),b=!!d;if(f+e>C.byteLength)throw new AB(Yi);for(var V=C.bytes,J=f+C.byteOffset,cA=0;cA>24)},setUint8:function(A,e){iD(this,A,e<<24>>24)}},{unsafe:!0})}else ih=(Ws=function(A){eh(this,ih);var e=Qm(A);yv(this,{type:IC,bytes:eT(fQ(e),0),byteLength:e}),hm||(this.byteLength=e,this.detached=!1)})[Ou],sc=(Ul=function(A,e,o){eh(this,sc),eh(A,ih);var a=ym(A),c=a.byteLength,d=Z_(e);if(d<0||d>c)throw new AB("Wrong offset");if(d+(o=o===void 0?c-d:X_(o))>c)throw new AB("Wrong length");yv(this,{type:th,buffer:A,byteLength:o,byteOffset:d,bytes:a.bytes}),hm||(this.buffer=A,this.byteLength=o,this.byteOffset=d)})[Ou],hm&&(SQ(Ws,"byteLength",ym),SQ(Ul,"buffer",dn),SQ(Ul,"byteLength",dn),SQ(Ul,"byteOffset",dn)),Bm(sc,{getInt8:function(A){return Cd(this,1,A)[0]<<24>>24},getUint8:function(A){return Cd(this,1,A)[0]},getInt16:function(A){var e=Cd(this,2,A,arguments.length>1&&arguments[1]);return(e[1]<<8|e[0])<<16>>16},getUint16:function(A){var e=Cd(this,2,A,arguments.length>1&&arguments[1]);return e[1]<<8|e[0]},getInt32:function(A){return uC(Cd(this,4,A,arguments.length>1&&arguments[1]))},getUint32:function(A){return uC(Cd(this,4,A,arguments.length>1&&arguments[1]))>>>0},getFloat32:function(A){return DQ(Cd(this,4,A,arguments.length>1&&arguments[1]),23)},getFloat64:function(A){return DQ(Cd(this,8,A,arguments.length>1&&arguments[1]),52)},setInt8:function(A,e){hd(this,1,A,Dv,e)},setUint8:function(A,e){hd(this,1,A,Dv,e)},setInt16:function(A,e){hd(this,2,A,Sv,e,arguments.length>2&&arguments[2])},setUint16:function(A,e){hd(this,2,A,Sv,e,arguments.length>2&&arguments[2])},setInt32:function(A,e){hd(this,4,A,eD,e,arguments.length>2&&arguments[2])},setUint32:function(A,e){hd(this,4,A,eD,e,arguments.length>2&&arguments[2])},setFloat32:function(A,e){hd(this,4,A,eB,e,arguments.length>2&&arguments[2])},setFloat64:function(A,e){hd(this,8,A,tD,e,arguments.length>2&&arguments[2])}});mm(Ws,IC),mm(Ul,th);var Dm={ArrayBuffer:Ws,DataView:Ul},vv=qA,iT=kg,Sm=k,tB=Js("species"),Mm=function(A){var e=vv(A);Sm&&e&&!e[tB]&&iT(e,tB,{configurable:!0,get:function(){return this}})},oT=Mm,oD="ArrayBuffer",sD=Dm[oD];_n({global:!0,constructor:!0,forced:y[oD]!==sD},{ArrayBuffer:sD}),oT(oD);var vQ=re,GE=Ke,xu=function(A){if(vQ(A)==="Function")return GE(A)},nD=_n,oh=xu,vm=_,Rv=or,RQ=ag,wv=qn,rD=Dm.ArrayBuffer,vn=Dm.DataView,wQ=vn.prototype,Bd=oh(rD.prototype.slice),aD=oh(wQ.getUint8),sT=oh(wQ.setUint8);nD({target:"ArrayBuffer",proto:!0,unsafe:!0,forced:vm(function(){return!new rD(2).slice(1,void 0).byteLength})},{slice:function(A,e){if(Bd&&e===void 0)return Bd(Rv(this),A);for(var o=Rv(this).byteLength,a=RQ(A,o),c=RQ(e===void 0?o:e,o),d=new rD(wv(c-a)),C=new vn(this),f=new vn(d),S=0;ad;d++)if((f=Oe(A[d]))&&UD(Sd,f))return f;return new BC(!1)}a=MT(A,c)}for(S=cA?A.next:a.next;!(b=yT(S,a)).done;){try{f=Oe(b.value)}catch(Se){FD(a,"throw",Se)}if(typeof f=="object"&&f&&UD(Sd,f))return f}return new BC(!1)},PD=Js("iterator"),xD=!1;try{var s=0,n={next:function(){return{done:!!s++}},return:function(){xD=!0}};n[PD]=function(){return this},Array.from(n,function(){throw 2})}catch{}var g=function(A,e){try{if(!e&&!xD)return!1}catch{return!1}var o=!1;try{var a={};a[PD]=function(){return{next:function(){return{done:o=!0}}}},A(a)}catch{}return o},I=dB,E=hh.CONSTRUCTOR||!g(function(A){I.all(A).then(void 0,function(){})}),m=aA,D=Pi,M=Jr,T=EB,P=OD;_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),f=[],S=0,b=1;P(A,function(V){var J=S++,cA=!1;b++,m(C,e,V).then(function(CA){cA||(cA=!0,f[J]=CA,--b||a(f))},c)}),--b||a(f)});return d.error&&c(d.value),o.promise}});var W=_n,oA=hh.CONSTRUCTOR,EA=dB,wA=qA,kA=$i,YA=Dr,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&&YA(LA,"catch",SA,{unsafe:!0})}var OA=aA,HA=Pi,se=Jr,oe=EB,_i=OD;_n({target:"Promise",stat:!0,forced:E},{race:function(A){var e=this,o=se.f(e),a=o.reject,c=oe(function(){var d=HA(e.resolve);_i(A,function(C){OA(d,e,C).then(o.resolve,a)})});return c.error&&a(c.value),o.promise}});var Ti=Jr;_n({target:"Promise",stat:!0,forced:hh.CONSTRUCTOR},{reject:function(A){var e=Ti.f(this);return(0,e.reject)(A),e.promise}});var bt=or,Ni=io,gs=Jr,De=function(A,e){if(bt(A),Ni(e)&&e.constructor===A)return e;var o=gs.f(A);return(0,o.resolve)(e),o.promise},Bt=_n,UA=hh.CONSTRUCTOR,ii=De;qA("Promise"),Bt({target:"Promise",stat:!0,forced:UA},{resolve:function(A){return ii(this,A)}});var ws=_n,Gi=dB,Lr=_,xi=qA,ar=$i,wt=Gv,_t=De,qu=Dr,ln=Gi&&Gi.prototype;if(ws({target:"Promise",proto:!0,real:!0,forced:!!Gi&&Lr(function(){ln.finally.call({then:function(){}},function(){})})},{finally:function(A){var e=wt(this,xi("Promise")),o=ar(A);return this.then(o?function(a){return _t(e,A()).then(function(){return a})}:A,o?function(a){return _t(e,A()).then(function(){throw a})}:A)}}),ar(Gi)){var ho=xi("Promise").prototype.finally;ln.finally!==ho&&qu(ln,"finally",ho,{unsafe:!0})}var cl=io,QC=re,Rr=Js("match"),Pg=function(A){var e;return cl(A)&&((e=A[Rr])!==void 0?!!e:QC(A)==="RegExp")},yI=_,rc=y.RegExp,Wm=!yI(function(){var A=!0;try{rc(".","d")}catch{A=!1}var e={},o="",a=A?"dgimsy":"gimsy",c=function(f,S){Object.defineProperty(e,f,{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(rc.prototype,"flags").get.call(e)!==a||o!==a}),XQ=or,Ya=function(){var A=XQ(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},Ol=aA,DI=ds,Ku=ce,xg={correct:Wm},Eg=Ya,YD=RegExp.prototype,ER=xg.correct?function(A){return A.flags}:function(A){return xg.correct||!Ku(YD,A)||DI(A,"flags")?A.flags:Ol(Eg,A)},dR=_,CR=y.RegExp,RT=dR(function(){var A=CR("a","y");return A.lastIndex=2,A.exec("abcd")!==null}),FY=RT||dR(function(){return!CR("a","y").sticky}),EU=RT||dR(function(){var A=CR("^r","gy");return A.lastIndex=2,A.exec("str")!==null}),$Q={BROKEN_CARET:EU,MISSED_STICKY:FY,UNSUPPORTED_Y:RT},wT=qi.f,_T=_,TT=y.RegExp,NT=_T(function(){var A=TT(".","s");return!(A.dotAll&&A.test(` +`)&&A.flags==="s")}),dU=_,OY=y.RegExp,CU=dU(function(){var A=OY("(?b)","g");return A.exec("b").groups.a!=="b"||"b".replace(A,"$c")!=="bc"}),zm=k,GT=y,Zm=Ke,bT=Mr,PY=Xy,xY=ng,YY=Pa,VY=Sc.f,hR=ce,hU=Pg,kT=ur,BU=ER,VD=$Q,LT=function(A,e,o){o in A||wT(A,o,{configurable:!0,get:function(){return e[o]},set:function(a){e[o]=a}})},BR=Dr,QR=_,JY=ds,UT=un.enforce,pR=Mm,QU=NT,Xm=CU,HY=Js("match"),mB=GT.RegExp,$m=mB.prototype,qY=GT.SyntaxError,pU=Zm($m.exec),Af=Zm("".charAt),mU=Zm("".replace),FT=Zm("".indexOf),OT=Zm("".slice),KY=/^\?<[^\s\d!#%&*+<=>@^][^\s!#%&*+<=>@^]*>/,ju=/a/g,fB=/a/g,fU=new mB(ju)!==ju,yU=VD.MISSED_STICKY,jY=VD.UNSUPPORTED_Y,PT=zm&&(!fU||yU||QU||Xm||QR(function(){return fB[HY]=!1,mB(ju)!==ju||mB(fB)===fB||String(mB(ju,"i"))!=="/a/i"}));if(bT("RegExp",PT)){for(var yB=function(A,e){var o,a,c,d,C,f,S=hR($m,this),b=hU(A),V=e===void 0,J=[],cA=A;if(!S&&b&&V&&A.constructor===yB)return A;if((b||hR($m,A))&&(A=A.source,V&&(e=BU(cA))),A=A===void 0?"":kT(A),e=e===void 0?"":kT(e),cA=A,QU&&"dotAll"in ju&&(a=!!e&&FT(e,"s")>-1)&&(e=mU(e,/s/g,"")),o=e,yU&&"sticky"in ju&&(c=!!e&&FT(e,"y")>-1)&&jY&&(e=mU(e,/y/g,"")),Xm&&(d=function(CA){for(var vA,$A=CA.length,he=0,Oe="",Se=[],fi=YY(null),Ne=!1,dt=!1,Ci=0,yi="";he<=$A;he++){if((vA=Af(CA,he))==="\\")vA+=Af(CA,++he);else if(vA==="]")Ne=!1;else if(!Ne)switch(!0){case vA==="[":Ne=!0;break;case vA==="(":if(Oe+=vA,OT(CA,he+1,he+3)==="?:")continue;pU(KY,OT(CA,he+1))&&(he+=2,dt=!0),Ci++;continue;case(vA===">"&&dt):if(yi===""||JY(fi,yi))throw new qY("Invalid capture group name");fi[yi]=!0,Se[Se.length]=[yi,Ci],dt=!1,yi="";continue}dt?yi+=vA:Oe+=vA}return[Oe,Se]}(A),A=d[0],J=d[1]),C=PY(mB(A,e),S?this:$m,yB),(a||c||J.length)&&(f=UT(C),a&&(f.dotAll=!0,f.raw=yB(function(CA){for(var vA,$A=CA.length,he=0,Oe="",Se=!1;he<=$A;he++)(vA=Af(CA,he))!=="\\"?Se||vA!=="."?(vA==="["?Se=!0:vA==="]"&&(Se=!1),Oe+=vA):Oe+="[\\s\\S]":Oe+=vA+Af(CA,++he);return Oe}(A),o)),c&&(f.sticky=!0),J.length&&(f.groups=J)),A!==cA)try{xY(C,"source",cA===""?"(?:)":cA)}catch{}return C},xT=VY(mB),YT=0;xT.length>YT;)LT(yB,mB,xT[YT++]);$m.constructor=yB,yB.prototype=$m,BR(GT,"RegExp",yB,{constructor:!0})}pR("RegExp");var ef=aA,Ap=Ke,DB=ur,WY=Ya,tf=$Q,DU=Pa,SU=un.get,zY=NT,ZY=CU,XY=ks("native-string-replace",String.prototype.replace),ep=RegExp.prototype.exec,VT=ep,$Y=Ap("".charAt),AV=Ap("".indexOf),MU=Ap("".replace),JD=Ap("".slice),JT=function(){var A=/a/,e=/b*/g;return ef(ep,A,"a"),ef(ep,e,"a"),A.lastIndex!==0||e.lastIndex!==0}(),vU=tf.BROKEN_CARET,HT=/()??/.exec("")[1]!==void 0;(JT||HT||vU||zY||ZY)&&(VT=function(A){var e,o,a,c,d,C,f,S=this,b=SU(S),V=DB(A),J=b.raw;if(J)return J.lastIndex=S.lastIndex,e=ef(VT,J,V),S.lastIndex=J.lastIndex,e;var cA=b.groups,CA=vU&&S.sticky,vA=ef(WY,S),$A=S.source,he=0,Oe=V;if(CA&&(vA=MU(vA,"y",""),AV(vA,"g")===-1&&(vA+="g"),Oe=JD(V,S.lastIndex),S.lastIndex>0&&(!S.multiline||S.multiline&&$Y(V,S.lastIndex-1)!==` +`)&&($A="(?: "+$A+")",Oe=" "+Oe,he++),o=new RegExp("^(?:"+$A+")",vA)),HT&&(o=new RegExp("^"+$A+"$(?!\\s)",vA)),JT&&(a=S.lastIndex),c=ef(ep,CA?o:S,Oe),CA?c?(c.input=JD(c.input,he),c[0]=JD(c[0],he),c.index=S.lastIndex,S.lastIndex+=c[0].length):S.lastIndex=0:JT&&c&&(S.lastIndex=S.global?c.index+c[0].length:a),HT&&c&&c.length>1&&ef(XY,c[0],o,function(){for(d=1;d0;(a>>>=1)&&(e+=e))1&a&&(o+=e);return o},of=uo,sf=_U(tV),DR=_U("".slice),TU=Math.ceil,qT=function(A){return function(e,o,a){var c,d,C=yR(of(e)),f=eV(o),S=C.length,b=a===void 0?" ":yR(a);return f<=S||b===""?C:((d=sf(b,TU((c=f-S)/b.length))).length>c&&(d=DR(d,0,c)),A?C+d:d+C)}},KT={start:qT(!1)},jT=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(it),iV=KT.start;_n({target:"String",proto:!0,forced:jT},{padStart:function(A){return iV(this,A,arguments.length>1?arguments[1]:void 0)}});var NU=aA,WT=Dr,GU=HD,zT=_,ZT=Js,oV=ZT("species"),bU=RegExp.prototype,SR=Ke,sV=zr,nf=ur,rf=uo,XT=SR("".charAt),kU=SR("".charCodeAt),nV=SR("".slice),LU=function(A){return function(e,o){var a,c,d=nf(rf(e)),C=sV(o),f=d.length;return C<0||C>=f?A?"":void 0:(a=kU(d,C))<55296||a>56319||C+1===f||(c=kU(d,C+1))<56320||c>57343?A?XT(d,C):a:A?nV(d,C,C+2):c-56320+(a-55296<<10)+65536}},MR={codeAt:LU(!1),charAt:LU(!0)},rV=MR.charAt,vR=Ke,aV=rs,gV=Math.floor,$T=vR("".charAt),AN=vR("".replace),eN=vR("".slice),cV=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,lV=/\$([$&'`]|\d{1,2})/g,UU=function(A,e,o,a,c,d){var C=o+A.length,f=a.length,S=lV;return c!==void 0&&(c=aV(c),S=cV),AN(d,S,function(b,V){var J;switch($T(V,0)){case"$":return"$";case"&":return A;case"`":return eN(e,0,o);case"'":return eN(e,C);case"<":J=c[eN(V,1,-1)];break;default:var cA=+V;if(cA===0)return b;if(cA>f){var CA=gV(cA/10);return CA===0?b:CA<=f?a[CA-1]===void 0?$T(V,1):a[CA-1]+$T(V,1):b}J=a[cA-1]}return J===void 0?"":J})},FU=aA,IV=or,OU=$i,uV=re,PU=HD,EV=TypeError,dV=Qd,xU=aA,RR=Ke,CV=function(A,e,o,a){var c=ZT(A),d=!zT(function(){var b={};return b[c]=function(){return 7},""[A](b)!==7}),C=d&&!zT(function(){var b=!1,V=/a/,J;return V.exec=function(){return b=!0,null},V[c](""),!b});if(!d||!C||o){var f=/./[c],S=e(c,""[A],function(b,V,J,cA,CA){var vA=V.exec;return vA===GU||vA===bU.exec?d&&!CA?{done:!0,value:NU(f,V,J,cA)}:{done:!0,value:NU(b,J,V,cA)}:{done:!1}});WT(String.prototype,A,S[0]),WT(bU,c,S[1])}},hV=_,BV=or,YU=$i,QV=io,pV=zr,VU=qn,tp=ur,wR=uo,JU=function(A,e,o){return e+(o?rV(A,e).length:1)},_R=An,HU=UU,qU=ER,mV=function(A,e){var o=A.exec;if(OU(o)){var a=FU(o,A,e);return a!==null&&IV(a),a}if(uV(A)==="RegExp")return FU(PU,A,e);throw new EV("RegExp#exec called on incompatible receiver")},TR=Js("replace"),tN=Math.max,fV=Math.min,KU=RR([].concat),iN=RR([].push),NR=RR("".indexOf),jU=RR("".slice),yV=function(A){return A===void 0?A:String(A)},DV="a".replace(/./,"$0")==="$0",WU=!!/./[TR]&&/./[TR]("a","$0")==="",SV=!hV(function(){var A=/./;return A.exec=function(){var e=[];return e.groups={a:"7"},e},"".replace(A,"$")!=="7"});CV("replace",function(A,e,o){var a=WU?"$":"$0";return[function(c,d){var C=wR(this),f=QV(c)?_R(c,TR):void 0;return f?xU(f,c,C,d):xU(e,tp(C),c,d)},function(c,d){var C=BV(this),f=tp(c);if(typeof d=="string"&&NR(d,a)===-1&&NR(d,"$<")===-1){var S=o(e,C,f,d);if(S.done)return S.value}var b=YU(d);b||(d=tp(d));var V,J=tp(qU(C)),cA=NR(J,"g")!==-1;cA&&(V=NR(J,"u")!==-1,C.lastIndex=0);for(var CA,vA=[];(CA=mV(C,f))!==null&&(iN(vA,CA),cA);)tp(CA[0])===""&&(C.lastIndex=JU(f,VU(C.lastIndex),V));for(var $A="",he=0,Oe=0;Oe=he&&($A+=jU(f,he,Ne)+Se,he=Ne+fi.length)}return $A+jU(f,he)}]},!SV||!DV||WU);var GR=` +\v\f\r                 \u2028\u2029\uFEFF`,MV=uo,vV=ur,oN=GR,sN=Ke("".replace),zU=RegExp("^["+oN+"]+"),RV=RegExp("(^|[^"+oN+"])["+oN+"]+$"),wV=function(A){return function(e){var o=vV(MV(e));return 1&A&&(o=sN(o,zU,"")),2&A&&(o=sN(o,RV,"$1")),o}},_V={trim:wV(3)},TV=Wg.PROPER,NV=_,ZU=GR,GV=_V.trim;_n({target:"String",proto:!0,forced:function(A){return NV(function(){return!!ZU[A]()||"​…᠎"[A]()!=="​…᠎"||TV&&ZU[A].name!==A})}("trim")},{trim:function(){return GV(this)}});var eu,af,bR,nN={exports:{}},bV=Sr,rN=k,SI=y,XU=$i,$U=io,gf=ds,kR=Ir,aN=Jn,gN=ng,cN=Dr,AF=kg,kV=ce,lN=CI,ip=sA,LV=Js,UV=Qc,IN=un.enforce,Dh=SI.Int8Array,cf=Dh&&Dh.prototype,eF=SI.Uint8ClampedArray,tF=eF&&eF.prototype,pC=Dh&&lN(Dh),Md=cf&&lN(cf),FV=Object.prototype,uN=SI.TypeError,iF=LV("toStringTag"),EN=UV("TYPED_ARRAY_TAG"),qD="TypedArrayConstructor",vd=bV&&!!ip&&kR(SI.opera)!=="Opera",oF=!1,SB={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},sF={BigInt64Array:8,BigUint64Array:8},LR=function(A){if(!$U(A))return!1;var e=kR(A);return gf(SB,e)||gf(sF,e)};for(eu in SB)(bR=(af=SI[eu])&&af.prototype)?IN(bR)[qD]=af:vd=!1;for(eu in sF)(bR=(af=SI[eu])&&af.prototype)&&(IN(bR)[qD]=af);if((!vd||!XU(pC)||pC===Function.prototype)&&(pC=function(){throw new uN("Incorrect invocation")},vd))for(eu in SB)SI[eu]&&ip(SI[eu],pC);if((!vd||!Md||Md===FV)&&(Md=pC.prototype,vd))for(eu in SB)SI[eu]&&ip(SI[eu].prototype,Md);if(vd&&lN(tF)!==Md&&ip(tF,Md),rN&&!gf(Md,iF))for(eu in oF=!0,AF(Md,iF,{configurable:!0,get:function(){return $U(this)?this[EN]:void 0}}),SB)SI[eu]&&gN(SI[eu],EN,eu);var Rd={NATIVE_ARRAY_BUFFER_VIEWS:vd,TYPED_ARRAY_TAG:oF&&EN,aTypedArray:function(A){if(LR(A))return A;throw new uN("Target is not a typed array")},aTypedArrayConstructor:function(A){if(XU(A)&&(!ip||kV(pC,A)))return A;throw new uN(aN(A)+" is not a typed array constructor")},exportTypedArrayMethod:function(A,e,o,a){if(rN){if(o)for(var c in SB){var d=SI[c];if(d&&gf(d.prototype,A))try{delete d.prototype[A]}catch{try{d.prototype[A]=e}catch{}}}Md[A]&&!o||cN(Md,A,o?e:vd&&cf[A]||e,a)}},exportTypedArrayStaticMethod:function(A,e,o){var a,c;if(rN){if(ip){if(o){for(a in SB)if((c=SI[a])&&gf(c,A))try{delete c[A]}catch{}}if(pC[A]&&!o)return;try{return cN(pC,A,o?e:vd&&pC[A]||e)}catch{}}for(a in SB)!(c=SI[a])||c[A]&&!o||cN(c,A,e)}},isTypedArray:LR,TypedArray:pC,TypedArrayPrototype:Md},dN=y,KD=_,UR=g,OV=Rd.NATIVE_ARRAY_BUFFER_VIEWS,nF=dN.ArrayBuffer,op=dN.Int8Array,rF=!OV||!KD(function(){op(1)})||!KD(function(){new op(-1)})||!UR(function(A){new op,new op(null),new op(1.5),new op(A)},!0)||KD(function(){return new op(new nF(2),1,void 0).length!==1}),PV=io,xV=Math.floor,aF=Number.isInteger||function(A){return!PV(A)&&isFinite(A)&&xV(A)===A},YV=zr,VV=RangeError,FR=function(A){var e=YV(A);if(e<0)throw new VV("The argument can't be less than 0");return e},JV=RangeError,gF=function(A,e){var o=FR(A);if(o%e)throw new JV("Wrong offset");return o},HV=Math.round,cF=Ir,qV=yn,KV=TypeError,OR=function(A){var e=qV(A,"number");if(typeof e=="number")throw new KV("Can't convert number to bigint");return BigInt(e)},lF=$a,IF=aA,jV=ah,WV=rs,uF=Ua,EF=UE,zV=yh,dF=ND,CF=function(A){var e=cF(A);return e==="BigInt64Array"||e==="BigUint64Array"},ZV=Rd.aTypedArrayConstructor,XV=OR,PR=function(A){var e,o,a,c,d,C,f,S,b=jV(this),V=WV(A),J=arguments.length,cA=J>1?arguments[1]:void 0,CA=cA!==void 0,vA=zV(V);if(vA&&!dF(vA))for(S=(f=EF(V,vA)).next,V=[];!(C=IF(S,f)).done;)V.push(C.value);for(CA&&J>2&&(cA=lF(cA,arguments[2])),o=uF(V),a=new(ZV(b))(o),c=CF(a),e=0;o>e;e++)d=CA?cA(V[e],e):V[e],a[e]=c?XV(d):+d;return a},CN=$r,hN=lD,$V=io,AJ=Js("species"),hF=Array,eJ=function(A){var e;return CN(A)&&(e=A.constructor,(hN(e)&&(e===hF||CN(e.prototype))||$V(e)&&(e=e[AJ])===null)&&(e=void 0)),e===void 0?hF:e},BF=$a,tJ=gi,iJ=rs,QF=Ua,oJ=function(A,e){return new(eJ(A))(e===0?0:e)},BN=Ke([].push),pF=function(A){var e=A===1,o=A===2,a=A===3,c=A===4,d=A===6,C=A===7,f=A===5||d;return function(S,b,V,J){for(var cA,CA,vA=iJ(S),$A=tJ(vA),he=QF($A),Oe=BF(b,V),Se=0,fi=J||oJ,Ne=e?fi(S,he):o||C?fi(S,0):void 0;he>Se;Se++)if((f||Se in $A)&&(CA=Oe(cA=$A[Se],Se,vA),A))if(e)Ne[Se]=CA;else if(CA)switch(A){case 3:return!0;case 5:return cA;case 6:return Se;case 2:BN(Ne,cA)}else switch(A){case 4:return!1;case 7:BN(Ne,cA)}return d?-1:a||c?c:Ne}},mF={forEach:pF(0)},sJ=Ua,fF=_n,yF=y,DF=aA,SF=k,nJ=rF,jD=Rd,MF=Dm,vF=pI,rJ=de,MB=ng,aJ=aF,gJ=qn,RF=um,QN=gF,wF=function(A){var e=HV(A);return e<0?0:e>255?255:255&e},pN=$,sp=ds,cJ=Ir,mN=io,fN=yo,lJ=Pa,yN=ce,xR=sA,IJ=Sc.f,_F=PR,TF=mF.forEach,YR=Mm,uJ=kg,NF=qi,GF=w,bF=function(A,e,o){for(var a=0,c=arguments.length>2?o:sJ(e),d=new A(c);c>a;)d[a]=e[a++];return d},EJ=Xy,DN=un.get,dJ=un.set,np=un.enforce,kF=NF.f,CJ=GF.f,SN=yF.RangeError,LF=MF.ArrayBuffer,hJ=LF.prototype,BJ=MF.DataView,lf=jD.NATIVE_ARRAY_BUFFER_VIEWS,UF=jD.TYPED_ARRAY_TAG,FF=jD.TypedArray,WD=jD.TypedArrayPrototype,zD=jD.isTypedArray,rp="BYTES_PER_ELEMENT",VR="Wrong length",JR=function(A,e){uJ(A,e,{configurable:!0,get:function(){return DN(this)[e]}})},OF=function(A){var e;return yN(hJ,A)||(e=cJ(A))==="ArrayBuffer"||e==="SharedArrayBuffer"},MN=function(A,e){return zD(A)&&!fN(e)&&e in A&&aJ(+e)&&e>=0},HR=function(A,e){return e=pN(e),MN(A,e)?rJ(2,A[e]):CJ(A,e)},PF=function(A,e,o){return e=pN(e),!(MN(A,e)&&mN(o)&&sp(o,"value"))||sp(o,"get")||sp(o,"set")||o.configurable||sp(o,"writable")&&!o.writable||sp(o,"enumerable")&&!o.enumerable?kF(A,e,o):(A[e]=o.value,A)};SF?(lf||(GF.f=HR,NF.f=PF,JR(WD,"buffer"),JR(WD,"byteOffset"),JR(WD,"byteLength"),JR(WD,"length")),fF({target:"Object",stat:!0,forced:!lf},{getOwnPropertyDescriptor:HR,defineProperty:PF}),nN.exports=function(A,e,o){var a=A.match(/\d+/)[0]/8,c=A+(o?"Clamped":"")+"Array",d="get"+A,C="set"+A,f=yF[c],S=f,b=S&&S.prototype,V={},J=function(CA,vA){kF(CA,vA,{get:function(){return function($A,he){var Oe=DN($A);return Oe.view[d](he*a+Oe.byteOffset,!0)}(this,vA)},set:function($A){return function(he,Oe,Se){var fi=DN(he);fi.view[C](Oe*a+fi.byteOffset,o?wF(Se):Se,!0)}(this,vA,$A)},enumerable:!0})};lf?nJ&&(S=e(function(CA,vA,$A,he){return vF(CA,b),EJ(mN(vA)?OF(vA)?he!==void 0?new f(vA,QN($A,a),he):$A!==void 0?new f(vA,QN($A,a)):new f(vA):zD(vA)?bF(S,vA):DF(_F,S,vA):new f(RF(vA)),CA,S)}),xR&&xR(S,FF),TF(IJ(f),function(CA){CA in S||MB(S,CA,f[CA])}),S.prototype=b):(S=e(function(CA,vA,$A,he){vF(CA,b);var Oe,Se,fi,Ne=0,dt=0;if(mN(vA)){if(!OF(vA))return zD(vA)?bF(S,vA):DF(_F,S,vA);Oe=vA,dt=QN($A,a);var Ci=vA.byteLength;if(he===void 0){if(Ci%a)throw new SN(VR);if((Se=Ci-dt)<0)throw new SN(VR)}else if((Se=gJ(he)*a)+dt>Ci)throw new SN(VR);fi=Se/a}else fi=RF(vA),Oe=new LF(Se=fi*a);for(dJ(CA,{buffer:Oe,byteOffset:dt,byteLength:Se,length:fi,view:new BJ(Oe)});Ne1?arguments[1]:void 0,e>2?arguments[2]:void 0)},vN(function(){var A=0;return new Int8Array(2).fill({valueOf:function(){return A++}}),A!==1})),(0,Rd.exportTypedArrayStaticMethod)("from",PR,rF);var VF=y,JF=aA,wN=Rd,HF=Ua,DJ=gF,SJ=rs,qF=_,MJ=VF.RangeError,_N=VF.Int8Array,TN=_N&&_N.prototype,NN=TN&&TN.set,GN=wN.aTypedArray,KF=wN.exportTypedArrayMethod,qR=!qF(function(){var A=new Uint8ClampedArray(2);return JF(NN,A,{length:1,0:3},1),A[1]!==3}),jF=qR&&wN.NATIVE_ARRAY_BUFFER_VIEWS&&qF(function(){var A=new _N(2);return A.set(1),A.set("2",1),A[0]!==0||A[1]!==2});KF("set",function(A){GN(this);var e=DJ(arguments.length>1?arguments[1]:void 0,1),o=SJ(A);if(qR)return JF(NN,this,o,e);var a=this.length,c=HF(o),d=0;if(c+e>a)throw new MJ("Wrong length");for(;d0&&1/a<0?1:-1:o>a}}(A))},!KR||PN);var zF=_n,xN=aA,XD=Ke,YN=uo,VN=$i,wJ=io,ZF=Pg,$D=ur,_J=An,AS=ER,XF=UU,TJ=Js("replace"),$F=TypeError,wd=XD("".indexOf);XD("".replace);var eS=XD("".slice),NJ=Math.max;zF({target:"String",proto:!0},{replaceAll:function(A,e){var o,a,c,d,C,f,S,b,V,J=YN(this),cA=0,CA="";if(wJ(A)){if(ZF(A)&&(o=$D(YN(AS(A))),!~wd(o,"g")))throw new $F("`.replaceAll` does not allow non-global regexes");if(a=_J(A,TJ))return xN(a,A,J,e)}for(c=$D(J),d=$D(A),(C=VN(e))||(e=$D(e)),f=d.length,S=NJ(1,f),b=wd(c,d);b!==-1;)V=C?$D(e(d,b,c)):XF(d,c,b,[],void 0,e),CA+=eS(c,cA,b)+V,cA=b+f,b=b+S>c.length?-1:wd(c,d,b+S);return cA1?arguments[1]:void 0)},eO=y,tO=JN,kJ=HN,WR=bJ,LJ=ng,iO=function(A){if(A&&A.forEach!==WR)try{LJ(A,"forEach",WR)}catch{A.forEach=WR}};for(var qN in tO)tO[qN]&&iO(eO[qN]&&eO[qN].prototype);iO(kJ);var zR=y,oO=JN,UJ=HN,tS=Ki,iS=ng,FJ=xa,KN=Js("iterator"),jN=tS.values,sO=function(A,e){if(A){if(A[KN]!==jN)try{iS(A,KN,jN)}catch{A[KN]=jN}if(FJ(A,e,!0),oO[e]){for(var o in tS)if(A[o]!==tS[o])try{iS(A,o,tS[o])}catch{A[o]=tS[o]}}}};for(var WN in oO)sO(zR[WN]&&zR[WN].prototype,WN);sO(UJ,"DOMTokenList");var zN=dC.clear;_n({global:!0,bind:!0,enumerable:!0,forced:y.clearImmediate!==zN},{clearImmediate:zN});var oS=y,OJ=Qd,PJ=$i,xJ=Yr,YJ=it,VJ=le,JJ=nB,ZN=oS.Function,HJ=/MSIE .\./.test(YJ)||xJ==="BUN"&&function(){var A=oS.Bun.version.split(".");return A.length<3||A[0]==="0"&&(A[1]<3||A[1]==="3"&&A[2]==="0")}(),nO=_n,rO=y,ZR=dC.set,qJ=function(A,e){var o=1;return HJ?function(a,c){var d=JJ(arguments.length,1)>o,C=PJ(a)?a:ZN(a),f=d?VJ(arguments,o):[],S=d?function(){OJ(C,this,f)}:C;return A(S)}:A},XN=rO.setImmediate?qJ(ZR):ZR;nO({global:!0,bind:!0,enumerable:!0,forced:rO.setImmediate!==XN},{setImmediate:XN});var Sh=MR.charAt,KJ=ur,XR=un,jJ=ue,aO=He,gO="String Iterator",WJ=XR.set,cO=XR.getterFor(gO);jJ(String,"String",function(A){WJ(this,{type:gO,string:KJ(A),index:0})},function(){var A,e=cO(this),o=e.string,a=e.index;return a>=o.length?aO(void 0,!0):(A=Sh(o,a),e.index+=A.length,aO(A,!1))});var zJ=_,ZJ=k,XJ=Js("iterator"),lO=!zJ(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&&!ZJ||!e.sort||A.href!=="https://a/c%20d?a=1&c=3"||e.get("c")!=="3"||String(new URLSearchParams("?a=1"))!=="a=1"||!e[XJ]||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"}),IO=k,$J=Ke,$N=aA,AG=_,eG=Tl,AH=Mc,eH=mA,tH=rs,uO=gi,ap=Object.assign,EO=Object.defineProperty,dO=$J([].concat),iH=!ap||AG(function(){if(IO&&ap({b:1},ap(EO({},"a",{enumerable:!0,get:function(){EO(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}),ap({},A)[o]!==7||eG(ap({},e)).join("")!==a})?function(A,e){for(var o=tH(A),a=arguments.length,c=1,d=AH.f,C=eH.f;a>c;)for(var f,S=uO(arguments[c++]),b=d?dO(eG(S),d(S)):eG(S),V=b.length,J=0;V>J;)f=b[J++],IO&&!$N(C,S,f)||(o[f]=S[f]);return o}:ap,oH=or,sH=LD,nH=k,rH=qi,CO=de,aH=$a,sS=aA,hO=rs,BO=function(A,e,o,a){try{return a?e(oH(o)[0],o[1]):e(o)}catch(c){sH(A,"throw",c)}},tG=ND,gH=lD,cH=Ua,nS=function(A,e,o){nH?rH.f(A,e,CO(0,o)):A[e]=o},iG=UE,lH=yh,QO=Array,vB=Ke,oG=2147483647,pO=/[^\0-\u007E]/,sG=/[.\u3002\uFF0E\uFF61]/g,mO="Overflow: input needs wider integers to process",fO=RangeError,IH=vB(sG.exec),RB=Math.floor,$R=String.fromCharCode,A0=vB("".charCodeAt),Wu=vB([].join),wB=vB([].push),Ba=vB("".replace),yO=vB("".split),uH=vB("".toLowerCase),DO=function(A){return A+22+75*(A<26)},nG=function(A,e,o){var a=0;for(A=o?RB(A/700):A>>1,A+=RB(A/e);A>455;)A=RB(A/35),a+=36;return RB(a+36*A/(A+38))},EH=function(A){var e=[];A=function(Oe){for(var Se=[],fi=0,Ne=Oe.length;fi=55296&&dt<=56319&&fi=d&&aRB((oG-C)/J))throw new fO(mO);for(C+=(V-d)*J,d=V,o=0;ooG)throw new fO(mO);if(a===d){for(var cA=C,CA=36;;){var vA=CA<=f?1:CA>=f+26?26:CA-f;if(cAc;){if(e=+arguments[c++],dH(e,1114111)!==e)throw new CH(e+" is not a valid code point");o[c]=e<65536?Mh(e):Mh(55296+((e-=65536)>>10),e%1024+56320)}return aS(o,"")}});var gp=_n,Ef=y,cp=Yv,rG=qA,Us=aA,zu=Ke,df=k,aG=lO,MO=Dr,hH=kg,BH=ZI,QH=xa,pH=wE,gS=un,vO=pI,gG=$i,mH=ds,fH=$a,yH=Ir,DH=or,RO=io,Pl=ur,SH=Pa,wO=de,_O=UE,MH=yh,e0=He,Cf=nB,vH=yt,RH=Js("iterator"),lp="URLSearchParams",cG=lp+"Iterator",TO=gS.set,ll=gS.getterFor(lp),vh=gS.getterFor(cG),NO=cp("fetch"),hf=cp("Request"),cS=cp("Headers"),lG=hf&&hf.prototype,GO=cS&&cS.prototype,bO=Ef.TypeError,wH=Ef.encodeURIComponent,_H=String.fromCharCode,TH=rG("String","fromCodePoint"),NH=parseInt,t0=zu("".charAt),i0=zu([].join),Rh=zu([].push),kO=zu("".replace),GH=zu([].shift),LO=zu([].splice),UO=zu("".split),FO=zu("".slice),IG=zu(/./.exec),OO=/\+/g,bH=/^[0-9a-f]+$/i,PO=function(A,e){var o=FO(A,e,e+2);return IG(bH,o)?NH(o,16):NaN},kH=function(A){for(var e=0,o=128;o>0&&A&o;o>>=1)e++;return e},LH=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},xO=function(A){for(var e=(A=kO(A,OO," ")).length,o="",a=0;ae){o+="%",a++;continue}var d=PO(A,a+1);if(d!=d){o+=c,a++;continue}a+=2;var C=kH(d);if(C===0)c=_H(d);else{if(C===1||C>4){o+="�",a++;continue}for(var f=[d],S=1;Se||t0(A,a)!=="%");){var b=PO(A,a+1);if(b!=b){a+=3;break}if(b>191||b<128)break;Rh(f,b),a+=2,S++}if(f.length!==C){o+="�";continue}var V=LH(f);V===null?o+="�":c=TH(V)}}o+=c,a++}return o},UH=/[!'()~]|%20/g,FH={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"},OH=function(A){return FH[A]},YO=function(A){return kO(wH(A),UH,OH)},uG=pH(function(A,e){TO(this,{type:cG,target:ll(A).entries,index:0,kind:e})},lp,function(){var A=vh(this),e=A.target,o=A.index++;if(!e||o>=e.length)return A.target=null,e0(void 0,!0);var a=e[o];switch(A.kind){case"keys":return e0(a.key,!1);case"values":return e0(a.value,!1)}return e0([a.key,a.value],!1)},!0),VO=function(A){this.entries=[],this.url=null,A!==void 0&&(RO(A)?this.parseObject(A):this.parseQuery(typeof A=="string"?t0(A,0)==="?"?FO(A,1):A:Pl(A)))};VO.prototype={type:lp,bindURL:function(A){this.url=A,this.update()},parseObject:function(A){var e,o,a,c,d,C,f,S=this.entries,b=MH(A);if(b)for(o=(e=_O(A,b)).next;!(a=Us(o,e)).done;){if(d=(c=_O(DH(a.value))).next,(C=Us(d,c)).done||(f=Us(d,c)).done||!Us(d,c).done)throw new bO("Expected sequence with length 2");Rh(S,{key:Pl(C.value),value:Pl(f.value)})}else for(var V in A)mH(A,V)&&Rh(S,{key:V,value:Pl(A[V])})},parseQuery:function(A){if(A)for(var e,o,a=this.entries,c=UO(A,"&"),d=0;d0?arguments[0]:void 0));df||(this.size=A.entries.length)},Ip=Bf.prototype;if(BH(Ip,{append:function(A,e){var o=ll(this);Cf(arguments.length,2),Rh(o.entries,{key:Pl(A),value:Pl(e)}),df||this.size++,o.updateURL()},delete:function(A){for(var e=ll(this),o=Cf(arguments.length,1),a=e.entries,c=Pl(A),d=o<2?void 0:arguments[1],C=d===void 0?d:Pl(d),f=0;fo.key?1:-1}),A.updateURL()},forEach:function(A){for(var e,o=ll(this).entries,a=fH(A,arguments.length>1?arguments[1]:void 0),c=0;c1?JO(arguments[1]):{})}}),gG(hf)){var dG=function(A){return vO(this,lG),new hf(A,arguments.length>1?JO(arguments[1]):{})};lG.constructor=dG,dG.prototype=lG,gp({global:!0,constructor:!0,dontCallGetSet:!0,forced:!0},{Request:dG})}}var Zu,xH=_n,CG=k,HO=lO,hG=y,qO=$a,FE=Ke,o0=Dr,OE=kg,YH=pI,BG=ds,QG=iH,_B=function(A){var e=hO(A),o=gH(this),a=arguments.length,c=a>1?arguments[1]:void 0,d=c!==void 0;d&&(c=aH(c,a>2?arguments[2]:void 0));var C,f,S,b,V,J,cA=lH(e),CA=0;if(!cA||this===QO&&tG(cA))for(C=cH(e),f=o?new this(C):QO(C);C>CA;CA++)J=d?c(e[CA],CA):e[CA],nS(f,CA,J);else for(f=o?new this:[],V=(b=iG(e,cA)).next;!(S=sS(V,b)).done;CA++)J=d?BO(b,c,[S.value,CA],!0):S.value,nS(f,CA,J);return f.length=CA,f},_d=le,pG=MR.codeAt,VH=function(A){var e,o,a=[],c=yO(Ba(uH(A),sG,"."),".");for(e=0;e?@[\\\]^|]/,XH=/[\0\t\n\r #/:<>?@[\\\]^|]/,$H=/^[\u0000-\u0020]+/,Aq=/(^|[^\u0000-\u0020])[\u0000-\u0020]+$/,eq=/[\t\n\r]/g,mf=function(A){var e,o,a,c;if(typeof A=="number"){for(e=[],o=0;o<4;o++)WH(e,A%256),A=_h(A/256);return lS(e,".")}if(typeof A=="object"){for(e="",a=function(d){for(var C=null,f=1,S=null,b=0,V=0;V<8;V++)d[V]!==0?(b>f&&(C=S,f=b),S=null,b=0):(S===null&&(S=V),++b);return b>f?S:C}(A),o=0;o<8;o++)c&&A[o]===0||(c&&(c=!1),a===o?(e+=o?":":"::",c=!0):(e+=jH(A[o],16),o<7&&(e+=":")));return"["+e+"]"}return A},ff={},AP=QG({},ff,{" ":1,'"':1,"<":1,">":1,"`":1}),MG=QG({},AP,{"#":1,"?":1,"{":1,"}":1}),NB=QG({},MG,{"/":1,":":1,";":1,"=":1,"@":1,"[":1,"\\":1,"]":1,"^":1,"|":1}),Nd=function(A,e){var o=pG(A,0);return o>32&&o<127&&!BG(e,A)?A:encodeURIComponent(A)},Th={ftp:21,file:null,http:80,https:443,ws:80,wss:443},yf=function(A,e){var o;return A.length===2&&Td(IS,PE(A,0))&&((o=PE(A,1))===":"||!e&&o==="|")},vG=function(A){var e;return A.length>1&&yf(up(A,0,2))&&(A.length===2||(e=PE(A,2))==="/"||e==="\\"||e==="?"||e==="#")},uS=function(A){return A==="."||g0(A)==="%2e"},eP=function(A){return(A=g0(A))===".."||A==="%2e."||A===".%2e"||A==="%2e%2e"},Xu={},tu={},GB={},mC={},bB={},I0={},tP={},ES={},u0={},E0={},d0={},C0={},h0={},B0={},RG={},Q0={},Df={},fC={},dS={},iu={},xl={},p0=function(A,e,o){var a,c,d,C=wh(A);if(e){if(c=this.parse(C))throw new fG(c);this.searchParams=null}else{if(o!==void 0&&(a=new p0(o,!0)),c=this.parse(C,null,a))throw new fG(c);(d=KH(new qH)).bindURL(this),this.searchParams=d}};p0.prototype={type:"URL",parse:function(A,e,o){var a,c,d,C,f=this,S=e||Xu,b=0,V="",J=!1,cA=!1,CA=!1;for(A=wh(A),e||(f.scheme="",f.username="",f.password="",f.host=null,f.port=null,f.path=[],f.query=null,f.fragment=null,f.cannotBeABaseURL=!1,A=r0(A,$H,""),A=r0(A,Aq,"$1")),A=r0(A,eq,""),a=_B(A);b<=a.length;){switch(c=a[b],S){case Xu:if(!c||!Td(IS,c)){if(e)return DG;S=GB;continue}V+=g0(c),S=tu;break;case tu:if(c&&(Td(zH,c)||c==="+"||c==="-"||c==="."))V+=g0(c);else{if(c!==":"){if(e)return DG;V="",S=GB,b=0;continue}if(e&&(f.isSpecial()!==BG(Th,V)||V==="file"&&(f.includesCredentials()||f.port!==null)||f.scheme==="file"&&!f.host))return;if(f.scheme=V,e)return void(f.isSpecial()&&Th[f.scheme]===f.port&&(f.port=null));V="",f.scheme==="file"?S=B0:f.isSpecial()&&o&&o.scheme===f.scheme?S=mC:f.isSpecial()?S=ES:a[b+1]==="/"?(S=bB,b++):(f.cannotBeABaseURL=!0,pf(f.path,""),S=dS)}break;case GB:if(!o||o.cannotBeABaseURL&&c!=="#")return DG;if(o.cannotBeABaseURL&&c==="#"){f.scheme=o.scheme,f.path=_d(o.path),f.query=o.query,f.fragment="",f.cannotBeABaseURL=!0,S=xl;break}S=o.scheme==="file"?B0:I0;continue;case mC:if(c!=="/"||a[b+1]!=="/"){S=I0;continue}S=u0,b++;break;case bB:if(c==="/"){S=E0;break}S=fC;continue;case I0:if(f.scheme=o.scheme,c===Zu)f.username=o.username,f.password=o.password,f.host=o.host,f.port=o.port,f.path=_d(o.path),f.query=o.query;else if(c==="/"||c==="\\"&&f.isSpecial())S=tP;else if(c==="?")f.username=o.username,f.password=o.password,f.host=o.host,f.port=o.port,f.path=_d(o.path),f.query="",S=iu;else{if(c!=="#"){f.username=o.username,f.password=o.password,f.host=o.host,f.port=o.port,f.path=_d(o.path),f.path.length--,S=fC;continue}f.username=o.username,f.password=o.password,f.host=o.host,f.port=o.port,f.path=_d(o.path),f.query=o.query,f.fragment="",S=xl}break;case tP:if(!f.isSpecial()||c!=="/"&&c!=="\\"){if(c!=="/"){f.username=o.username,f.password=o.password,f.host=o.host,f.port=o.port,S=fC;continue}S=E0}else S=u0;break;case ES:if(S=u0,c!=="/"||PE(V,b+1)!=="/")continue;b++;break;case u0:if(c!=="/"&&c!=="\\"){S=E0;continue}break;case E0:if(c==="@"){J&&(V="%40"+V),J=!0,d=_B(V);for(var vA=0;vA65535)return c0;f.port=f.isSpecial()&&Oe===Th[f.scheme]?null:Oe,V=""}if(e)return;S=Df;continue}return c0}V+=c;break;case B0:if(f.scheme="file",c==="/"||c==="\\")S=RG;else{if(!o||o.scheme!=="file"){S=fC;continue}switch(c){case Zu:f.host=o.host,f.path=_d(o.path),f.query=o.query;break;case"?":f.host=o.host,f.path=_d(o.path),f.query="",S=iu;break;case"#":f.host=o.host,f.path=_d(o.path),f.query=o.query,f.fragment="",S=xl;break;default:vG(lS(_d(a,b),""))||(f.host=o.host,f.path=_d(o.path),f.shortenPath()),S=fC;continue}}break;case RG:if(c==="/"||c==="\\"){S=Q0;break}o&&o.scheme==="file"&&!vG(lS(_d(a,b),""))&&(yf(o.path[0],!0)?pf(f.path,o.path[0]):f.host=o.host),S=fC;continue;case Q0:if(c===Zu||c==="/"||c==="\\"||c==="?"||c==="#"){if(!e&&yf(V))S=fC;else if(V===""){if(f.host="",e)return;S=Df}else{if(C=f.parseHost(V))return C;if(f.host==="localhost"&&(f.host=""),e)return;V="",S=Df}continue}V+=c;break;case Df:if(f.isSpecial()){if(S=fC,c!=="/"&&c!=="\\")continue}else if(e||c!=="?")if(e||c!=="#"){if(c!==Zu&&(S=fC,c!=="/"))continue}else f.fragment="",S=xl;else f.query="",S=iu;break;case fC:if(c===Zu||c==="/"||c==="\\"&&f.isSpecial()||!e&&(c==="?"||c==="#")){if(eP(V)?(f.shortenPath(),c==="/"||c==="\\"&&f.isSpecial()||pf(f.path,"")):uS(V)?c==="/"||c==="\\"&&f.isSpecial()||pf(f.path,""):(f.scheme==="file"&&!f.path.length&&yf(V)&&(f.host&&(f.host=""),V=PE(V,0)+":"),pf(f.path,V)),V="",f.scheme==="file"&&(c===Zu||c==="?"||c==="#"))for(;f.path.length>1&&f.path[0]==="";)a0(f.path);c==="?"?(f.query="",S=iu):c==="#"&&(f.fragment="",S=xl)}else V+=Nd(c,MG);break;case dS:c==="?"?(f.query="",S=iu):c==="#"?(f.fragment="",S=xl):c!==Zu&&(f.path[0]+=Nd(c,ff));break;case iu:e||c!=="#"?c!==Zu&&(c==="'"&&f.isSpecial()?f.query+="%27":f.query+=c==="#"?"%23":Nd(c,ff)):(f.fragment="",S=xl);break;case xl:c!==Zu&&(f.fragment+=Nd(c,AP))}b++}},parseHost:function(A){var e,o,a;if(PE(A,0)==="["){if(PE(A,A.length-1)!=="]"||(e=function(c){var d,C,f,S,b,V,J,cA=[0,0,0,0,0,0,0,0],CA=0,vA=null,$A=0,he=function(){return PE(c,$A)};if(he()===":"){if(PE(c,1)!==":")return;$A+=2,vA=++CA}for(;he();){if(CA===8)return;if(he()!==":"){for(d=C=0;C<4&&Td(XO,he());)d=16*d+n0(he(),16),$A++,C++;if(he()==="."){if(C===0||($A-=C,CA>6))return;for(f=0;he();){if(S=null,f>0){if(!(he()==="."&&f<4))return;$A++}if(!Td(SG,he()))return;for(;Td(SG,he());){if(b=n0(he(),10),S===null)S=b;else{if(S===0)return;S=10*S+b}if(S>255)return;$A++}cA[CA]=256*cA[CA]+S,++f!==2&&f!==4||CA++}if(f!==4)return;break}if(he()===":"){if($A++,!he())return}else if(he())return;cA[CA++]=d}else{if(vA!==null)return;$A++,vA=++CA}}if(vA!==null)for(V=CA-vA,CA=7;CA!==0&&V>0;)J=cA[CA],cA[CA--]=cA[vA+V-1],cA[vA+--V]=J;else if(CA!==8)return;return cA}(up(A,1,-1)),!e))return TB;this.host=e}else if(this.isSpecial()){if(A=VH(A),Td($O,A)||(e=function(c){var d,C,f,S,b,V,J,cA=yG(c,".");if(cA.length&&cA[cA.length-1]===""&&cA.length--,(d=cA.length)>4)return c;for(C=[],f=0;f1&&PE(S,0)==="0"&&(b=Td(l0,S)?16:8,S=up(S,b===8?1:2)),S==="")V=0;else{if(!Td(b===10?ZO:b===8?ZH:XO,S))return c;V=n0(S,b)}pf(C,V)}for(f=0;f=WO(256,5-d))return null}else if(V>255)return null;for(J=zO(C),f=0;f1?arguments[1]:void 0,a=HH(e,new p0(A,!1,o));CG||(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())},Yl=Nh.prototype,Vl=function(A,e){return{get:function(){return s0(this)[A]()},set:e&&function(o){return s0(this)[e](o)},configurable:!0,enumerable:!0}};if(CG&&(OE(Yl,"href",Vl("serialize","setHref")),OE(Yl,"origin",Vl("getOrigin")),OE(Yl,"protocol",Vl("getProtocol","setProtocol")),OE(Yl,"username",Vl("getUsername","setUsername")),OE(Yl,"password",Vl("getPassword","setPassword")),OE(Yl,"host",Vl("getHost","setHost")),OE(Yl,"hostname",Vl("getHostname","setHostname")),OE(Yl,"port",Vl("getPort","setPort")),OE(Yl,"pathname",Vl("getPathname","setPathname")),OE(Yl,"search",Vl("getSearch","setSearch")),OE(Yl,"searchParams",Vl("getSearchParams")),OE(Yl,"hash",Vl("getHash","setHash"))),o0(Yl,"toJSON",function(){return s0(this).serialize()},{enumerable:!0}),o0(Yl,"toString",function(){return s0(this).serialize()},{enumerable:!0}),Qf){var iP=Qf.createObjectURL,m0=Qf.revokeObjectURL;iP&&o0(Nh,"createObjectURL",qO(iP,Qf)),m0&&o0(Nh,"revokeObjectURL",qO(m0,Qf))}JH(Nh,"URL"),xH({global:!0,constructor:!0,forced:!HO,sham:!CG},{URL:Nh});var oP=aA;_n({target:"URL",proto:!0,enumerable:!0},{toJSON:function(){return oP(URL.prototype.toString,this)}});let sP=!0,f0=!0;function CS(A,e,o){const a=A.match(e);return a&&a.length>=o&&parseFloat(a[o],10)}function kB(A,e,o){if(!A.RTCPeerConnection)return;const a=A.RTCPeerConnection.prototype,c=a.addEventListener;a.addEventListener=function(C,f){if(C!==e)return c.apply(this,arguments);const S=b=>{const V=o(b);V&&(f.handleEvent?f.handleEvent(V):f(V))};return this._eventMap=this._eventMap||{},this._eventMap[e]||(this._eventMap[e]=new Map),this._eventMap[e].set(f,S),c.apply(this,[C,S])};const d=a.removeEventListener;a.removeEventListener=function(C,f){if(C!==e||!this._eventMap||!this._eventMap[e])return d.apply(this,arguments);if(!this._eventMap[e].has(f))return d.apply(this,arguments);const S=this._eventMap[e].get(f);return this._eventMap[e].delete(f),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 nP(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(sP=A,A?"adapter.js logging disabled":"adapter.js logging enabled")}function tq(A){return typeof A!="boolean"?new Error("Argument type: "+typeof A+". Please use a boolean."):(f0=!A,"adapter.js deprecation warnings "+(A?"disabled":"enabled"))}function y0(){if(typeof window=="object"){if(sP)return;typeof console<"u"&&typeof console.log=="function"&&console.log.apply(console,arguments)}}function hS(A,e){f0&&console.warn(A+" is deprecated, please use "+e+" instead.")}function wG(A){return Object.prototype.toString.call(A)==="[object Object]"}function _G(A){return wG(A)?Object.keys(A).reduce(function(e,o){const a=wG(A[o]),c=a?_G(A[o]):A[o],d=a&&!Object.keys(c).length;return c===void 0||d?e:Object.assign(e,{[o]:c})},{}):A}function TG(A,e,o){e&&!o.has(e.id)&&(o.set(e.id,e),Object.keys(e).forEach(a=>{a.endsWith("Id")?TG(A,A.get(e[a]),o):a.endsWith("Ids")&&e[a].forEach(c=>{TG(A,A.get(c),o)})}))}function rP(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(f=>{f.type===a&&f.trackId===C.id&&TG(A,f,c)})}),c}const NG=y0;function aP(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 f={};return Object.keys(C).forEach(S=>{if(S==="require"||S==="advanced"||S==="mediaSource")return;const b=typeof C[S]=="object"?C[S]:{ideal:C[S]};b.exact!==void 0&&typeof b.exact=="number"&&(b.min=b.max=b.exact);const V=function(J,cA){return J?J+cA.charAt(0).toUpperCase()+cA.slice(1):cA==="deviceId"?"sourceId":cA};if(b.ideal!==void 0){f.optional=f.optional||[];let J={};typeof b.ideal=="number"?(J[V("min",S)]=b.ideal,f.optional.push(J),J={},J[V("max",S)]=b.ideal,f.optional.push(J)):(J[V("",S)]=b.ideal,f.optional.push(J))}b.exact!==void 0&&typeof b.exact!="number"?(f.mandatory=f.mandatory||{},f.mandatory[V("",S)]=b.exact):["min","max"].forEach(J=>{b[J]!==void 0&&(f.mandatory=f.mandatory||{},f.mandatory[V(J,S)]=b[J])})}),C.advanced&&(f.optional=(f.optional||[]).concat(C.advanced)),f},c=function(C,f){if(e.version>=61)return f(C);if((C=JSON.parse(JSON.stringify(C)))&&typeof C.audio=="object"){const S=function(b,V,J){V in b&&!(J in b)&&(b[J]=b[V],delete b[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 b=e.version<66;if(S&&(S.exact==="user"||S.exact==="environment"||S.ideal==="user"||S.ideal==="environment")&&(!o.mediaDevices.getSupportedConstraints||!o.mediaDevices.getSupportedConstraints().facingMode||b)){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 cA=J.find(CA=>V.some(vA=>CA.label.toLowerCase().includes(vA)));return!cA&&J.length&&V.includes("back")&&(cA=J[J.length-1]),cA&&(C.video.deviceId=S.exact?{exact:cA.deviceId}:{ideal:cA.deviceId}),C.video=a(C.video),NG("chrome: "+JSON.stringify(C)),f(C)})}C.video=a(C.video)}return NG("chrome: "+JSON.stringify(C)),f(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,f,S){c(C,b=>{o.webkitGetUserMedia(b,f,V=>{S&&S(d(V))})})}.bind(o),o.mediaDevices.getUserMedia){const C=o.mediaDevices.getUserMedia.bind(o.mediaDevices);o.mediaDevices.getUserMedia=function(f){return c(f,S=>C(S).then(b=>{if(S.audio&&!b.getAudioTracks().length||S.video&&!b.getVideoTracks().length)throw b.getTracks().forEach(V=>{V.stop()}),new DOMException("","NotFoundError");return b},b=>Promise.reject(d(b))))}}}function gP(A){A.MediaStream=A.MediaStream||A.webkitMediaStream}function cP(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 kB(A,"track",e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}function GG(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,f){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 f=this._senders.indexOf(C);f!==-1&&this._senders.splice(f,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(f=>f.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 lP(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(f){const S={};return f.result().forEach(b=>{const V={id:b.id,timestamp:b.timestamp,type:{localcandidate:"local-candidate",remotecandidate:"remote-candidate"}[b.type]||b.type};b.names().forEach(J=>{V[J]=b.stat(J)}),S[V.id]=V}),S},C=function(f){return new Map(Object.keys(f).map(S=>[S,f[S]]))};if(arguments.length>=2){const f=function(S){a(C(d(S)))};return e.apply(this,[f,o])}return new Promise((f,S)=>{e.apply(this,[function(b){f(C(d(b)))},S])}).then(a,c)}}function bG(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=>rP(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}),kB(A,"track",a=>(a.receiver._pc=a.srcElement,a)),A.RTCRtpReceiver.prototype.getStats=function(){const a=this;return this._pc.getStats().then(c=>rP(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 IP(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 f=e.apply(this,arguments);return this._shimmedLocalStreams[C.id]?this._shimmedLocalStreams[C.id].indexOf(f)===-1&&this._shimmedLocalStreams[C.id].push(f):this._shimmedLocalStreams[C.id]=[C,f],f};const o=A.RTCPeerConnection.prototype.addStream;A.RTCPeerConnection.prototype.addStream=function(d){this._shimmedLocalStreams=this._shimmedLocalStreams||{},d.getTracks().forEach(S=>{if(this.getSenders().find(b=>b.track===S))throw new DOMException("Track already exists.","InvalidAccessError")});const C=this.getSenders();o.apply(this,arguments);const f=this.getSenders().filter(S=>C.indexOf(S)===-1);this._shimmedLocalStreams[d.id]=[d].concat(f)};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 f=this._shimmedLocalStreams[C].indexOf(d);f!==-1&&this._shimmedLocalStreams[C].splice(f,1),this._shimmedLocalStreams[C].length===1&&delete this._shimmedLocalStreams[C]}),c.apply(this,arguments)}}function uP(A,e){if(!A.RTCPeerConnection)return;if(A.RTCPeerConnection.prototype.addTrack&&e.version>=65)return IP(A);const o=A.RTCPeerConnection.prototype.getLocalStreams;A.RTCPeerConnection.prototype.getLocalStreams=function(){const S=o.apply(this);return this._reverseStreams=this._reverseStreams||{},S.map(b=>this._reverseStreams[b.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(b=>{if(this.getSenders().find(V=>V.track===b))throw new DOMException("Track already exists.","InvalidAccessError")}),!this._reverseStreams[S.id]){const b=new A.MediaStream(S.getTracks());this._streams[S.id]=b,this._reverseStreams[b.id]=S,S=b}a.apply(this,[S])};const c=A.RTCPeerConnection.prototype.removeStream;function d(S,b){let V=b.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:b.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,b){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[b.id];if(J)J.addTrack(S),Promise.resolve().then(()=>{this.dispatchEvent(new Event("negotiationneeded"))});else{const cA=new A.MediaStream([S]);this._streams[b.id]=cA,this._reverseStreams[cA.id]=b,this.addStream(cA)}return this.getSenders().find(cA=>cA.track===S)},["createOffer","createAnswer"].forEach(function(S){const b=A.RTCPeerConnection.prototype[S],V={[S](){const J=arguments;return arguments.length&&typeof arguments[0]=="function"?b.apply(this,[cA=>{const CA=d(this,cA);J[0].apply(null,[CA])},cA=>{J[1]&&J[1].apply(null,cA)},arguments[2]]):b.apply(this,arguments).then(cA=>d(this,cA))}};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,b){let V=b.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:b.type,sdp:V})}(this,arguments[0]),C.apply(this,arguments)):C.apply(this,arguments)};const f=Object.getOwnPropertyDescriptor(A.RTCPeerConnection.prototype,"localDescription");Object.defineProperty(A.RTCPeerConnection.prototype,"localDescription",{get(){const S=f.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 b;this._streams=this._streams||{},Object.keys(this._streams).forEach(V=>{this._streams[V].getTracks().find(J=>S.track===J)&&(b=this._streams[V])}),b&&(b.getTracks().length===1?this.removeStream(this._reverseStreams[b.id]):b.removeTrack(S.track),this.dispatchEvent(new Event("negotiationneeded")))}}function BS(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 EP(A,e){kB(A,"negotiationneeded",o=>{const a=o.target;if(!(e.version<72||a.getConfiguration&&a.getConfiguration().sdpSemantics==="plan-b")||a.signalingState==="stable")return o})}var kG=Object.freeze({__proto__:null,shimMediaStream:gP,shimOnTrack:cP,shimGetSendersWithDtmf:GG,shimGetStats:lP,shimSenderReceiverGetStats:bG,shimAddTrackRemoveTrackWithNative:IP,shimAddTrackRemoveTrack:uP,shimPeerConnection:BS,fixNegotiationNeeded:EP,shimGetUserMedia:aP,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 dP(A,e){const o=A&&A.navigator,a=A&&A.MediaStreamTrack;if(o.getUserMedia=function(c,d,C){hS("navigator.getUserMedia","navigator.mediaDevices.getUserMedia"),o.mediaDevices.getUserMedia(c).then(d,C)},!(e.version>55&&"autoGainControl"in o.mediaDevices.getSupportedConstraints())){const c=function(C,f,S){f in C&&!(S in C)&&(C[S]=C[f],delete C[f])},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 f=C.apply(this,arguments);return c(f,"mozAutoGainControl","autoGainControl"),c(f,"mozNoiseSuppression","noiseSuppression"),f}}if(a&&a.prototype.applyConstraints){const C=a.prototype.applyConstraints;a.prototype.applyConstraints=function(f){return this.kind==="audio"&&typeof f=="object"&&(f=JSON.parse(JSON.stringify(f)),c(f,"autoGainControl","mozAutoGainControl"),c(f,"noiseSuppression","mozNoiseSuppression")),C.apply(this,[f])}}}}function CP(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 D0(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(f=>{if(e.version<53&&!d)try{f.forEach(S=>{S.type=o[S.type]||S.type})}catch(S){if(S.name!=="TypeError")throw S;f.forEach((b,V)=>{f.set(V,Object.assign({},b,{type:o[b.type]||b.type}))})}return f}).then(d,C)}}function hP(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 LG(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}),kB(A,"track",o=>(o.receiver._pc=o.srcElement,o)),A.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function BP(A){A.RTCPeerConnection&&!("removeStream"in A.RTCPeerConnection.prototype)&&(A.RTCPeerConnection.prototype.removeStream=function(e){hS("removeStream","removeTrack"),this.getSenders().forEach(o=>{o.track&&e.getTracks().includes(o.track)&&this.removeTrack(o)})})}function UG(A){A.DataChannel&&!A.RTCDataChannel&&(A.RTCDataChannel=A.DataChannel)}function QP(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 pP(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 mP(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 fP(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 yP=Object.freeze({__proto__:null,shimOnTrack:CP,shimPeerConnection:D0,shimSenderGetStats:hP,shimReceiverGetStats:LG,shimRemoveStream:BP,shimRTCDataChannel:UG,shimAddTransceiver:QP,shimGetParameters:pP,shimCreateOffer:mP,shimCreateAnswer:fP,shimGetUserMedia:dP,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 DP(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 SP(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 FG(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,b){const V=arguments.length>=2?arguments[2]:arguments[0],J=o.apply(this,[V]);return b?(J.then(S,b),Promise.resolve()):J},e.createAnswer=function(S,b){const V=arguments.length>=2?arguments[2]:arguments[0],J=a.apply(this,[V]);return b?(J.then(S,b),Promise.resolve()):J};let f=function(S,b,V){const J=c.apply(this,[S]);return V?(J.then(b,V),Promise.resolve()):J};e.setLocalDescription=f,f=function(S,b,V){const J=d.apply(this,[S]);return V?(J.then(b,V),Promise.resolve()):J},e.setRemoteDescription=f,f=function(S,b,V){const J=C.apply(this,[S]);return V?(J.then(b,V),Promise.resolve()):J},e.addIceCandidate=f}function OG(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(MP(c))}!e.getUserMedia&&e.mediaDevices&&e.mediaDevices.getUserMedia&&(e.getUserMedia=function(o,a,c){e.mediaDevices.getUserMedia(o).then(a,c)}.bind(e))}function MP(A){return A&&A.video!==void 0?Object.assign({},A,{video:_G(A.video)}):A}function vP(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 RP(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 S0(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 wP(A){typeof A!="object"||A.AudioContext||(A.AudioContext=A.webkitAudioContext)}var _P=Object.freeze({__proto__:null,shimLocalStreamsAPI:DP,shimRemoteStreamsAPI:SP,shimCallbacksAPI:FG,shimGetUserMedia:OG,shimConstraints:MP,shimRTCIceServerUrls:vP,shimTrackEventTransceiver:RP,shimCreateOfferLegacy:S0,shimAudioContext:wP}),TP={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;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 +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(f=>{C.rtcpFeedback.find(S=>S.type===f.type&&S.parameter===f.parameter)||C.rtcpFeedback.push(f)})}),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,f=e.matchPrefix(o,"a=ssrc:").map(cA=>e.parseSsrcMedia(cA)).filter(cA=>cA.attribute==="cname"),S=f.length>0&&f[0].ssrc;let b;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&&(b=V[0][1]),c.codecs.forEach(cA=>{if(cA.name.toUpperCase()==="RTX"&&cA.parameters.apt){let CA={ssrc:S,codecPayloadType:parseInt(cA.parameters.apt,10)};S&&b&&(CA.rtx={ssrc:b}),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(cA=>{cA.maxBitrate=J})),a},e.parseRtcpParameters=function(o){const a={},c=e.matchPrefix(o,"a=ssrc:").map(f=>e.parseSsrcMedia(f)).filter(f=>f.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 +`),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 f=e.matchPrefix(o,"a=sctpmap:");if(f.length>0){const S=f[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 +`,`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 +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 PG(A){!A.RTCIceCandidate||A.RTCIceCandidate&&"relayProtocol"in A.RTCIceCandidate.prototype||kB(A,"icecandidate",e=>{if(e.candidate){const o=Gd.parseCandidate(e.candidate.candidate);o.type==="relay"&&(e.candidate.relayProtocol={0:"tls",1:"tcp",2:"udp"}[o.priority>>24])}return e})}function QS(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=Gd.splitSections(a.sdp);return c.shift(),c.some(d=>{const C=Gd.parseMLine(d);return C&&C.kind==="application"&&C.protocol.indexOf("SCTP")!==-1})}(arguments[0])){const a=function(S){const b=S.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(b===null||b.length<2)return-1;const V=parseInt(b[1],10);return V!=V?-1:V}(arguments[0]),c=function(S){let b=65536;return e.browser==="firefox"&&(b=e.version<57?S===-1?16384:2147483637:e.version<60?e.version===57?65535:65536:2147483637),b}(a),d=function(S,b){let V=65536;e.browser==="firefox"&&e.version===57&&(V=65535);const J=Gd.matchPrefix(S.sdp,"a=max-message-size:");return J.length>0?V=parseInt(J[0].substring(19),10):e.browser==="firefox"&&b!==-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 f={};Object.defineProperty(f,"maxMessageSize",{get:()=>C}),this._sctp=f}return o.apply(this,arguments)}}function v0(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],f=C.length||C.size||C.byteLength;if(a.readyState==="open"&&c.sctp&&f>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},kB(A,"datachannel",a=>(e(a.channel,a.target),a))}function xG(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 R0(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(` +`).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 w0(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 _0(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 iq=Object.freeze({__proto__:null,shimRTCIceCandidate:M0,shimRTCIceCandidateRelayProtocol:PG,shimMaxMessageSize:QS,shimSendThrowTypeError:v0,shimConnectionState:xG,removeExtmapAllowMixed:R0,shimAddIceCandidateNullOrEmpty:w0,shimParameterlessSetLocalDescription:_0});(function({window:A}={},e={shimChrome:!0,shimFirefox:!0,shimSafari:!0}){const o=y0,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:f}=d;if(f.mozGetUserMedia)C.browser="firefox",C.version=parseInt(CS(f.userAgent,/Firefox\/(\d+)\./,1));else if(f.webkitGetUserMedia||d.isSecureContext===!1&&d.webkitRTCPeerConnection)C.browser="chrome",C.version=parseInt(CS(f.userAgent,/Chrom(e|ium)\/(\d+)\./,2));else{if(!d.RTCPeerConnection||!f.userAgent.match(/AppleWebKit\/(\d+)\./))return C.browser="Not a supported browser.",C;C.browser="safari",C.version=parseInt(CS(f.userAgent,/AppleWebKit\/(\d+)\./,1)),C.supportsUnifiedPlan=d.RTCRtpTransceiver&&"currentDirection"in d.RTCRtpTransceiver.prototype,C._safariVersion=CS(f.userAgent,/Version\/(\d+(\.?\d+))/,1)}return C}(A),c={browserDetails:a,commonShim:iq,extractVersion:CS,disableLog:nP,disableWarnings:tq,sdp:GP};switch(a.browser){case"chrome":if(!kG||!BS||!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=kG,w0(A,a),_0(A),aP(A,a),gP(A),BS(A,a),cP(A),uP(A,a),GG(A),lP(A),bG(A),EP(A,a),M0(A),PG(A),xG(A),QS(A,a),v0(A),R0(A,a);break;case"firefox":if(!yP||!D0||!e.shimFirefox)return o("Firefox shim is not included in this adapter release."),c;o("adapter.js shimming firefox."),c.browserShim=yP,w0(A,a),_0(A),dP(A,a),D0(A,a),CP(A),BP(A),hP(A),LG(A),UG(A),QP(A),pP(A),mP(A),fP(A),M0(A),xG(A),QS(A,a),v0(A);break;case"safari":if(!_P||!e.shimSafari)return o("Safari shim is not included in this adapter release."),c;o("adapter.js shimming safari."),c.browserShim=_P,w0(A,a),_0(A),vP(A),S0(A),FG(A),DP(A),SP(A),RP(A),OG(A),wP(A),M0(A),PG(A),QS(A,a),v0(A),R0(A,a);break;default:o("Unsupported browser!")}})({window:typeof window>"u"?void 0:window});var go,bP=Object.create,pS=Object.defineProperty,oq=Object.defineProperties,T0=Object.getOwnPropertyDescriptor,mS=Object.getOwnPropertyDescriptors,sq=Object.getOwnPropertyNames,N0=Object.getOwnPropertySymbols,kP=Object.getPrototypeOf,YG=Object.prototype.hasOwnProperty,LP=Object.prototype.propertyIsEnumerable,UP=Reflect.get,fS=Math.pow,G0=(A,e,o)=>e in A?pS(A,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):A[e]=o,pi=(A,e)=>{for(var o in e||(e={}))YG.call(e,o)&&G0(A,o,e[o]);if(N0)for(var o of N0(e))LP.call(e,o)&&G0(A,o,e[o]);return A},Bo=(A,e)=>oq(A,mS(e)),FP=(A,e)=>{var o={};for(var a in A)YG.call(A,a)&&e.indexOf(a)<0&&(o[a]=A[a]);if(A!=null&&N0)for(var a of N0(A))e.indexOf(a)<0&&LP.call(A,a)&&(o[a]=A[a]);return o},Gh=(A,e)=>()=>(e||A((e={exports:{}}).exports,e),e.exports),bh=(A,e)=>{for(var o in e)pS(A,o,{get:e[o],enumerable:!0})},ac=(A,e,o)=>(o=A!=null?bP(kP(A)):{},((a,c,d,C)=>{if(c&&typeof c=="object"||typeof c=="function")for(let f of sq(c))!YG.call(a,f)&&f!==d&&pS(a,f,{get:()=>c[f],enumerable:!(C=T0(c,f))||C.enumerable});return a})(!e&&A&&A.__esModule?o:pS(o,"default",{value:A,enumerable:!0}),A)),di=(A,e,o,a)=>{for(var c,d=T0(e,o),C=A.length-1;C>=0;C--)(c=A[C])&&(d=c(e,o,d)||d);return d&&pS(e,o,d),d},Y=(A,e,o)=>G0(A,typeof e!="symbol"?e+"":e,o),MI=(A,e,o)=>UP(kP(A),o,e),jA=(A,e,o)=>new Promise((a,c)=>{var d=S=>{try{f(o.next(S))}catch(b){c(b)}},C=S=>{try{f(o.throw(S))}catch(b){c(b)}},f=S=>S.done?a(S.value):Promise.resolve(S.value).then(d,C);f((o=o.apply(A,e)).next())}),Jl=Gh((A,e)=>{var o=Object.prototype.hasOwnProperty,a="~";function c(){}function d(b,V,J){this.fn=b,this.context=V,this.once=J||!1}function C(b,V,J,cA,CA){if(typeof J!="function")throw new TypeError("The listener must be a function");var vA=new d(J,cA||b,CA),$A=a?a+V:V;return b._events[$A]?b._events[$A].fn?b._events[$A]=[b._events[$A],vA]:b._events[$A].push(vA):(b._events[$A]=vA,b._eventsCount++),b}function f(b,V){--b._eventsCount===0?b._events=new c:delete b._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 b,V,J=[];if(this._eventsCount===0)return J;for(V in b=this._events)o.call(b,V)&&J.push(a?V.slice(1):V);return Object.getOwnPropertySymbols?J.concat(Object.getOwnPropertySymbols(b)):J},S.prototype.listeners=function(b){var V=a?a+b:b,J=this._events[V];if(!J)return[];if(J.fn)return[J.fn];for(var cA=0,CA=J.length,vA=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 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")})})}),Sf=Gh(A=>{var e=function(C){return String(Number(C))===C?Number(C):C},o=function(C,f,S){var b=C.name&&C.names;C.push&&!f[C.push]?f[C.push]=[]:b&&!f[C.name]&&(f[C.name]={});var V=C.push?{}:b?f[C.name]:f;(function(J,cA,CA,vA){if(vA&&!CA)cA[vA]=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 f=[],S=C.split(" ").map(e),b=0;b{var o=yC(),a=/%[sdv%]/g,c=function(S){var b=1,V=arguments,J=V.length;return S.replace(a,function(cA){if(b>=J)return cA;var CA=V[b];switch(b+=1,cA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,b,V){var J=[S+"="+(b.format instanceof Function?b.format(b.push?V:V[b.name]):b.format)];if(b.names)for(var cA=0;cA{var e=Sf(),o=nq(),a=yC();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=Gh((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")})})}),OP=Gh(A=>{var e=function(C){return String(Number(C))===C?Number(C):C},o=function(C,f,S){var b=C.name&&C.names;C.push&&!f[C.push]?f[C.push]=[]:b&&!f[C.name]&&(f[C.name]={});var V=C.push?{}:b?f[C.name]:f;(function(J,cA,CA,vA){if(vA&&!CA)cA[vA]=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 f=[],S=C.split(" ").map(e),b=0;b{var o=yS(),a=/%[sdv%]/g,c=function(S){var b=1,V=arguments,J=V.length;return S.replace(a,function(cA){if(b>=J)return cA;var CA=V[b];switch(b+=1,cA){case"%%":return"%";case"%s":return String(CA);case"%d":return Number(CA);case"%v":return""}})},d=function(S,b,V){var J=[S+"="+(b.format instanceof Function?b.format(b.push?V:V[b.name]):b.format)];if(b.names)for(var cA=0;cA{var e=OP(),o=PP();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}),aq=ac(Jl()),LB=((go=LB||{})[go.INVALID_PARAMETER=4096]="INVALID_PARAMETER",go[go.INVALID_OPERATION=4097]="INVALID_OPERATION",go[go.NOT_SUPPORTED=4098]="NOT_SUPPORTED",go[go.DEVICE_NOT_FOUND=4099]="DEVICE_NOT_FOUND",go[go.INITIALIZE_FAILED=4100]="INITIALIZE_FAILED",go[go.SIGNAL_CHANNEL_SETUP_FAILED=16385]="SIGNAL_CHANNEL_SETUP_FAILED",go[go.SIGNAL_CHANNEL_ERROR=16386]="SIGNAL_CHANNEL_ERROR",go[go.ICE_TRANSPORT_ERROR=16387]="ICE_TRANSPORT_ERROR",go[go.JOIN_ROOM_FAILED=16388]="JOIN_ROOM_FAILED",go[go.CREATE_OFFER_FAILED=16389]="CREATE_OFFER_FAILED",go[go.SIGNAL_CHANNEL_RECONNECTION_FAILED=16390]="SIGNAL_CHANNEL_RECONNECTION_FAILED",go[go.UPLINK_RECONNECTION_FAILED=16391]="UPLINK_RECONNECTION_FAILED",go[go.DOWNLINK_RECONNECTION_FAILED=16392]="DOWNLINK_RECONNECTION_FAILED",go[go.REMOTE_STREAM_NOT_EXIST=16400]="REMOTE_STREAM_NOT_EXIST",go[go.CLIENT_BANNED=16448]="CLIENT_BANNED",go[go.SERVER_TIMEOUT=16449]="SERVER_TIMEOUT",go[go.SUBSCRIPTION_TIMEOUT=16450]="SUBSCRIPTION_TIMEOUT",go[go.PLAY_NOT_ALLOWED=16451]="PLAY_NOT_ALLOWED",go[go.DEVICE_AUTO_RECOVER_FAILED=16452]="DEVICE_AUTO_RECOVER_FAILED",go[go.START_PUBLISH_CDN_FAILED=16453]="START_PUBLISH_CDN_FAILED",go[go.STOP_PUBLISH_CDN_FAILED=16454]="STOP_PUBLISH_CDN_FAILED",go[go.START_MIX_TRANSCODE_FAILED=16455]="START_MIX_TRANSCODE_FAILED",go[go.STOP_MIX_TRANSCODE_FAILED=16456]="STOP_MIX_TRANSCODE_FAILED",go[go.NOT_SUPPORTED_H264=16457]="NOT_SUPPORTED_H264",go[go.SWITCH_ROLE_FAILED=16458]="SWITCH_ROLE_FAILED",go[go.API_CALL_TIMEOUT=16459]="API_CALL_TIMEOUT",go[go.SCHEDULE_FAILED=16460]="SCHEDULE_FAILED",go[go.API_CALL_ABORTED=16461]="API_CALL_ABORTED",go[go.SPC_INITIALIZED_FAILED=16462]="SPC_INITIALIZED_FAILED",go[go.VIDEO_MANAGER_ERROR=16463]="VIDEO_MANAGER_ERROR",go[go.SWITCH_ROOM_FAILED=16464]="SWITCH_ROOM_FAILED",go[go.VIDEO_ENCODE_FAILED=16465]="VIDEO_ENCODE_FAILED",go[go.AUDIO_ENCODE_FAILED=16466]="AUDIO_ENCODE_FAILED",go[go.UNKNOWN=65535]="UNKNOWN",go),lt=LB,xP=class extends Error{constructor(A){let{name:e="RtcError",message:o,code:a=lt.UNKNOWN,extraCode:c=0,constraint:d}=A,C="<".concat(function(S){for(let b in lt)if(lt[b]===S)return b;return"UNKNOWN"}(a)," 0x").concat(a.toString(16),">"),f="".concat(o).concat(d?" constraint: ".concat(d):"").concat(o!=null&&o.includes(C)?"":" ".concat(C));super(f),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=f,this.constraint=d,this.originMessage=o}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},oi=xP,JG=0,YP=!0,UB=function(A){JG=A;let e=new Date;e.setTime(e.getTime()+A),QA[YP?"info":"debug"]("baseTime from server: ".concat(e," offset: ").concat(A)),YP=!1},VP=function(){return JG},Mf=function(){return Date.now()+JG},JP=function(){let A=new Date;return A.setTime(Mf()),A.toLocaleString()},HG=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)},bd={};bh(bd,{REPORT_TYPE:()=>aw,buildSSOPackage:()=>JB,bytes2ms:()=>ew,calculateScaleResolutionDownNumber:()=>rw,concatArrayBuffers:()=>VS,convertObjectNumberToInt:()=>nw,copyProperties:()=>Ex,deepClone:()=>Pf,deepCloneBasic:()=>xf,deepMerge:()=>Fh,delay:()=>SC,fibonacci:()=>Uf,formatedTime:()=>fx,getConstructorName:()=>FS,getContainerFromElement:()=>Eb,getEnv:()=>lx,getFirst16Bits:()=>Dx,getInternalVersion:()=>px,getLast16Bits:()=>gw,getLoggerUrl:()=>kf,getMediaStreamTrackInfo:()=>Qb,getMuteStateFromFlag:()=>Qp,getNetworkType:()=>$0,getNumNetworkType:()=>Lf,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>sw,getTestSignalDomain:()=>Ix,getTurnServer:()=>mx,getUint32Version:()=>Cb,getValueType:()=>dg,getViewListFromView:()=>xS,glog:()=>Cx,ipv4ToUint32:()=>PS,isArray:()=>va,isAudioWorkletSupported:()=>hx,isBoolean:()=>wr,isConstructor:()=>Of,isEmpty:()=>iw,isFunction:()=>Ma,isLangChinese:()=>Ud,isMediaStreamTrack:()=>Ib,isNumber:()=>bn,isObject:()=>xE,isOverseaSdkAppId:()=>Ld,isPlainObject:()=>eE,isPortrait:()=>db,isPromise:()=>Ff,isRemoteTrack:()=>ub,isRotate90Or270:()=>VB,isSetSinkIdSupported:()=>Bx,isString:()=>Yn,isUndefined:()=>xe,isVideoMixerOutputTrack:()=>pp,loadImage:()=>YS,loadVideo:()=>yx,ms2bytes:()=>dx,ms2samples:()=>tw,normalizeUrl:()=>Bb,performanceNow:()=>bo,promiseAny:()=>OS,samples2ms:()=>lb,setNetworkTypeFromWebRTC:()=>Aw,stringify:()=>Fd,stringifyIncludeValue:()=>ow,throttlePromise:()=>hb});var HP={};bh(HP,{ASR_ROBOT_FROM_TYPE:()=>K0,AUDIO_MUTE_BIT:()=>wf,AUDIO_STAT_BIT:()=>wS,AUX_STAT_BIT:()=>RS,AUX_STREAM_MSID:()=>XP,BACKEND_ENV:()=>vf,BASE_DOC_URL:()=>kh,BASE_HOST:()=>KP,CAPABILITIES_KEYS:()=>ib,CLASS_NAME:()=>hq,CLOUD_CONSOLE_URL:()=>lq,CROSS_ROOM_BIT:()=>ZG,DATA_CHANNEL_FROM_TYPE_BIT:()=>PB,DATA_FREEZE_TIMING:()=>eb,DOC_BILLING_CN:()=>U0,DOC_BILLING_OVERSEA:()=>jG,DOC_URL:()=>Iq,DTLS_STATE_UNKNOWN:()=>Lh,ENV_NAME:()=>FB,EXCHANGE_SDP_TIMEOUT:()=>ix,IS_WORKER:()=>k0,IS_WORKLET:()=>L0,KIBANA_EVENT:()=>Va,LOCAL_STREAM_PUBLISH_STATE:()=>ox,LOGGER_CMD_TYPE:()=>RI,LOGGER_DOMAIN:()=>vI,LOGGER_DOMAIN_OVERSEA:()=>Ep,LOG_LEVEL:()=>OB,LOG_LEVEL_NAME:()=>Qq,MAIN_STREAM_MSID:()=>ou,MAX_RTT:()=>q0,MICROPHONE_COMMUNICATIONS:()=>Bq,MICROPHONE_DEFAULT:()=>NS,MUTE_ALL_BIT:()=>ZP,NAME:()=>VA,NETWORK_TYPE:()=>F0,NOT_SUPPORTED_H264:()=>J0,PAUSED_RETRY_COUNT:()=>hp,PEERCONNECTION_CONNECTING_TIMEOUT:()=>tb,PEER_CONNECTION_STATE:()=>Eo,PEER_LEAVE_REASON:()=>rx,RECOVER_CAPTURE_INTERVAL:()=>bS,REMOTE_STREAM_TYPE_AUX:()=>XG,REMOTE_STREAM_TYPE_MAIN:()=>P0,RENDER_FREEZE_TIMING:()=>sx,SCHEDULE_DOMAIN:()=>YB,SCHEDULE_TIMEOUT:()=>nx,SDP_SEMANTICS_PLAN_B:()=>V0,SDP_SEMANTICS_UNIFIED_PLAN:()=>TS,SECOND_HOST:()=>jP,SIGNAL_PING_PONG_INTERVAL:()=>AE,SIGNAL_PING_TIMEOUT:()=>WP,SIGNAL_RECONNECTION_COUNT:()=>uq,SMALL_STAT_BIT:()=>zG,SPEAKER_DEFAULT:()=>H0,STORAGE_EXPIRES_TIME:()=>O0,STREAM_TYPE_BIG:()=>dq,STREAM_TYPE_SMALL:()=>Cq,SUBSCRIBE_SMALL_RETRY_COUNT:()=>GS,SYNC_USER_LIST_INTERVAL:()=>Eq,Scene:()=>Rf,THIRD_HOST:()=>cq,TRANSPORT_DIRECTION:()=>zn,TRTC_ERROR_ASSISTANCE:()=>SS,TRTC_QUALITY_BAD:()=>_f,TRTC_QUALITY_DISCONNECTED:()=>ex,TRTC_QUALITY_EXCELLENT:()=>x0,TRTC_QUALITY_GOOD:()=>xB,TRTC_QUALITY_POOR:()=>$P,TRTC_QUALITY_UNKNOWN:()=>$G,TRTC_QUALITY_VERY_BAD:()=>Ax,UPDATE_OFFER_TIMEOUT:()=>tx,VIDEO_MUTE_BIT:()=>_S,VIDEO_STAT_BIT:()=>vS,WEBGL_ATTRIBUTES:()=>ob,audioProfileMap:()=>dp,defaultBigVideoProfile:()=>MS,defaultSmallVideoProfile:()=>zP,getRetryCount:()=>Tf,getScriptDir:()=>gq,innerVersion:()=>b0,loggerProxy:()=>KG,screenProfileMap:()=>WG,setLoggerProxy:()=>DS,setRetryCount:()=>Y0,setVersion:()=>qP,version:()=>kd,videoProfileMap:()=>DC});var b0="4.15.00.1600",kd="5.0.0";function qP(A){kd=A;let[e,o,a]=A.split(".").map(c=>parseInt(c,10));b0="".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 qG,$u,k0=typeof importScripts<"u",L0=typeof registerProcessor<"u",gq=()=>{let A=k0?self.location.href:document.currentScript.src;return A.substring(0,A.lastIndexOf("/")+1)},KG="",DS=A=>KG=A,KP="web.sdk.qcloud.com",jP="web.sdk.tencent.cn",cq="web.sdk.cloud.tencent.cn",lq="https://console.cloud.tencent.com/trtc",kh="https://".concat(KP,"/trtc/webrtc/doc"),Iq="".concat(kh,"/zh-cn/"),U0="https://cloud.tencent.com/document/product/647/85386",jG="https://trtc.io/document/56025",vI="https://yun.tim.qq.com",Ep="https://apisgp.my-imcloud.com",SS="trtc_error_assistance",RI={LOG:"jssdk_log",EVENT:"jssdk_event",KEY_POINT:"jssdk_new_endreport",KV_STAT:"jssdk_key_metrics_report"},FB={QCLOUD:"qcloud",OLD_CLOUD_LADDER:"trtc",WEBRTC:"webrtc"},OB=(($u=OB||{})[$u.TRACE=0]="TRACE",$u[$u.DEBUG=1]="DEBUG",$u[$u.INFO=2]="INFO",$u[$u.WARN=3]="WARN",$u[$u.ERROR=4]="ERROR",$u[$u.NONE=5]="NONE",$u),WP=18e3,AE=2e3,F0={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},O0=6048e5,dp={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}},DC={"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}},MS=DC["480p_2"],zP=DC["120p_2"],WG={"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}},VA={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"},vf={OLD_CLOUD_LADDER:"wss://trtc.rtc.qq.com",WEBRTC:"wss://webrtc.qq.com"},Rf=((qG=Rf||{}).LIVE="live",qG.RTC="rtc",qG),vS=1,zG=2,RS=4,wS=8,wf=64,_S=16,ZP=112,ZG=128,PB=256,ou="5Y2wZK8nANNAoVw6dSAHVjNxrD1ObBM2kBPV",XP="224d130c-7b5c-415b-aaa2-79c2eb5a6df2",P0=VA.MAIN,XG=VA.AUXILIARY,$G=0,x0=1,xB=2,$P=3,_f=4,Ax=5,ex=6,Lh="unknown",Eo={NEW:"new",CONNECTING:"connecting",FAILED:"failed",CLOSED:"closed",DISCONNECTED:"disconnected",CONNECTED:"connected",COMPLETED:"completed"},Ab=1/0;function Y0(A){Ab=A}function Tf(){return Ab}var Cp,uq=30,Va={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"},Eq=1e4,tx=1e4,ix=1e4,TS="unified-plan",V0="plan-b",J0=1028,ox=((Cp=ox||{})[Cp.UNPUBLISH=-1]="UNPUBLISH",Cp[Cp.PUBLISHING=0]="PUBLISHING",Cp[Cp.PUBLISHED=1]="PUBLISHED",Cp),eb=500,sx=1e3,dq=VA.BIG,Cq=VA.SMALL,tb=1e4,YB={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"},nx=2e3,hq={TRTC:"TRTC",CLIENT:"Client",LOCAL_STREAM:"LocalStream",REMOTE_STREAM:"RemoteStream",STREAM:"Stream"},hp=5,NS="default",H0=NS,Bq="communications",Qq=Object.keys(OB),rx=["normal leave","timeout leave","kick","role change"],GS=10,bS=2e3,ib=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],q0=1e4,K0=14,ob={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},ax=function(A,e,o,a){return new(o||(o=Promise))(function(c,d){function C(b){try{S(a.next(b))}catch(V){d(V)}}function f(b){try{S(a.throw(b))}catch(V){d(V)}}function S(b){b.done?c(b.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(b.value).then(C,f)}S((a=a.apply(A,[])).next())})},j0=Symbol(32),W0=Symbol(16),sb=Symbol(8),Nf=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 ax(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(j0)}readU16(){return this.read(W0)}readU8(){return this.read(sb)}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===j0){if(a(4))return;A=e[0]<<24|e[1]<<16|e[2]<<8|e[3]}else if(this.need===W0){if(a(2))return;A=e[0]<<8|e[1]}else if(this.need===sb){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}};Nf.U32=j0,Nf.U16=W0,Nf.U8=sb;var kS=128;function z0(A){let e=new Nf;for(;A>=128;)e.malloc(1)[0]=255&A|kS,A>>>=7;return e.malloc(1)[0]=255&A,e.buffer||new Uint8Array(0)}function Z0(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,o=new Nf,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(z0(A));break;case"string":o.malloc(1)[0]=2|a;let d=new TextEncoder().encode(A);o.write(z0(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 su(A,e){return A[e]<<24|A[e+1]<<16|A[e+2]<<8|A[e+3]}function cx(A,e){return A[e]}function bf(A,e,o){return new TextDecoder().decode(function(a,c,d){return a.slice(c,c+d)}(A,e,o))}var LS=0,nb=2654435769,X0=16,Uh=2,US=7;function rb(A,e){let o=new gx,a=function(Se,fi,Ne){let dt=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:Ne,appId:Se,appidAtThird:new Uint8Array(0),a2:"",a2Len:0,serviceCmd:dt,serviceCmdLen:0,cookie:"",cookieLen:0,imei:"",imeiLen:0,ksid:"",ksidLen:0,clientVersionInfo:"",clientVersionInfoLen:0},busiBuff:fi}}(e,A,LS);LS=LS+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 gx;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 Se=4;Se<16;Se++)C.writeByte(0);let f=new TextEncoder().encode(a.reqHead.a2);C.writeInt32(f.length+4),f.length&&C.writeBytes(f);let S=new TextEncoder().encode(a.reqHead.serviceCmd);C.writeInt32(S.length+4),S.length&&C.writeBytes(S);let b=new TextEncoder().encode(a.reqHead.cookie);C.writeInt32(b.length+4),b.length&&C.writeBytes(b);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 cA=new TextEncoder().encode(a.reqHead.clientVersionInfo);C.writeInt16(cA.length+2),cA.length&&C.writeBytes(cA);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 vA=new Uint8Array(C.data),$A=null;a.encryption===1?$A=new TextEncoder().encode(a.uin):a.encryption===2&&($A=new Uint8Array(16)),$A&&(vA=function(Se,fi){let Ne=Se.length,dt=(Ne+1+Uh+US)%8;dt&&(dt=8-dt);let Ci=Ne+1+Uh+US+dt,yi=new Uint8Array(Ci),Yo=0,Vo=new Uint8Array(8),Qn=new Uint8Array(8),Jo=new Uint8Array(8),Ts=0;Vo[0]=248&Math.floor(256*Math.random())|dt,Ts=1;for(let ma=0;ma>>24&255,he[1]=Oe>>>16&255,he[2]=Oe>>>8&255,he[3]=255&Oe,he}function ab(A,e,o,a,c,d){for(let C=0;C<8;C++)A[C]^=a[C];(function(C,f,S,b){let V=su(C,0),J=su(C,4),cA=[];for(let vA=0;vA<4;vA++)cA[vA]=su(f,4*vA);let CA=0;for(let vA=0;vA>>=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;Gf(S,V,b),Gf(S,J,b+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 lx=function(){return new URLSearchParams(location.search).get("trtc_env")||""},Ix=function(A){return A.includes(".")?A:"".concat(A).concat(".rtc.qq.com")},Ld=A=>Number(A)<14e8,kf=function(A,e){let o;o=KG||(Ld(A)?Ep:vI);let a=Math.floor(Math.random()*fS(2,31));return"".concat(o,"/v5/AVQualityReportSvc/C2S?random=").concat(a,"&sdkappid=").concat(A,"&cmdtype=").concat(e)},gb="unknown";function $0(){(function(){var d;ux||(ux=!0,(d=navigator.connection)==null||d.addEventListener("typechange",pq))})();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?cb(a,c):gb}function pq(){QA.warn("netType changed",$0())}var ux=!1;function cb(A,e){if(F0[A])return A;switch(A){case"cellular":case"wimax":return e||"unknown";case"ethernet":return"wired";default:return"unknown"}}function Aw(A){gb=cb(A)}function Lf(){return F0[$0()]}function Ex(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 ew(A){return lb(A/4,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function lb(A){return 1e3*A/(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function dx(A){return 4*tw(A,arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)}function tw(A){return A*(arguments.length>1&&arguments[1]!==void 0?arguments[1]:48e3)/1e3}var Cx=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Ud=()=>{let A=navigator.language;return A=A.substring(0,2),A==="zh"},eE=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 Uf(A){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1;return A<=1?e:Uf(A-1,e,(arguments.length>1&&arguments[1]!==void 0?arguments[1]:1)+e)}function Bp(A){return A>8?3e4:1e3*Uf(A)}function dg(A){return Reflect.apply(Object.prototype.toString,A,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var Ma=A=>typeof A=="function",xe=A=>A===void 0,Yn=A=>typeof A=="string",bn=A=>typeof A=="number",wr=A=>typeof A=="boolean",xE=A=>dg(A)==="object",va=A=>dg(A)==="array",Ib=A=>dg(A)==="MediaStreamTrack".toLowerCase(),ub=A=>A.isRemote,Ff=A=>dg(A)==="promise",Of=A=>Ma(A)&&A.prototype.constructor===A,FS=A=>Of(A)?A.prototype.constructor.name:"",hx=typeof AudioWorkletNode<"u",Bx=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function OS(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 bo(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var Qx=A=>+A<10?"0".concat(A):A,px=A=>{let e=A.match(/^\d+\.\d+\.\d+/)[0];if(!e)return A;let o=e.split("."),a=Qx(o[1])+Qx(o[2]);return o[1]-15>0&&(o[1]="15"),o[2]-15>0&&(o[2]="15"),"".concat(o.join("."),".").concat(a)},mq=Object.prototype.hasOwnProperty;function iw(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(eE(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(mq.call(A,e))return!1;return!0}return!1}function Qp(A,e){return{userId:e,hasAudio:!!(A&wS),hasVideo:!!(A&vS),hasAuxiliary:!!(A&RS),hasSmall:!!(A&zG),audioMuted:!!(A&wf),videoMuted:!!(A&_S),audioAvailable:!(!(A&wS)||A&wf),videoAvailable:!(!(A&vS)||A&_S),hasDatachannel:!!(A&PB)}}function mx(A){let e={urls:A.url.startsWith("turn:")||A.url.startsWith("turns:")?A.url:"turn:".concat(A.url)};return!xe(A.username)&&!xe(A.credential)&&(e.username=A.username,e.credential=A.credential,e.credentialType="password",xe(A.credentialType)||(e.credentialType=A.credentialType)),e}function PS(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 Fh=function(A,e,o,a){if(!xE(A)||!xE(e))return 0;let c,d=0,C=Object.keys(e);for(let f=0,S=C.length;f{e[a]=Pf(o)}),e}if(xE(A)){let e={};return Object.keys(A).forEach(o=>{e[o]=Pf(A[o])}),e}return A}var xS=A=>{let e=[];if(va(A))e=[...A];else if(Yn(A)){let o=document.getElementById(A);o&&e.push(o)}else A&&e.push(A);return e},Eb=A=>Yn(A)?document.getElementById(A):A,fx=()=>(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()),f=e(A.getSeconds());return"".concat(o,"/").concat(a,"/").concat(c," ").concat(d,":").concat(C,":").concat(f)})(new Date);function Fd(A,e){let{keysToInclude:o,keysToExclude:a}=e;try{if(va(A))return"[".concat(A.map(f=>Fd(f,{keysToInclude:o,keysToExclude:a})).join(","),"]");if(!eE(A)||!va(o)&&!va(a))return JSON.stringify(A);let c={},d=new Set(o),C=new Set(a);return Object.keys(A).forEach(f=>{(C.size===0&&d.has(f)||d.size===0&&!C.has(f))&&(c[f]=eE(A[f])||va(A[f])?JSON.parse(Fd(A[f],{keysToExclude:a,keysToInclude:o})):A[f])}),JSON.stringify(c)}catch{return"{}"}}function ow(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)}),Fd(A,{keysToInclude:o})}function sw(A){return A.replace(/[\u4e00-\u9fa5]/g,"aa").length}var db=()=>{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},YS=A=>jA(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 oi({code:lt.INVALID_PARAMETER,message:"load image failed, url: ".concat(A)}))}})}),Cb=A=>{let e=A.split(".");return+e[0]<<24|+e[1]<<16|+e[2]<<8|+e[3]},nw=A=>(Object.keys(A).forEach(e=>{bn(A[e])&&(e.startsWith("uint")||e.startsWith("int"))?A[e]=Math.floor(A[e]):(eE(A[e])||va(A[e]))&&nw(A[e])}),A);function SC(A,e){return new Promise(o=>{let a=setTimeout(o,A);e&&e(a)})}function hb(A,e){let o=null;return function(){for(var a=arguments.length,c=new Array(a),d=0;do=null),o)}}function Bb(A){return A.replace(/(^|[^:])\/{2,}/g,"$1/")}function Qb(A){var e;try{let{width:o,height:a,frameRate:c,sampleRate:d,sampleSize:C,channelCount:f}=(e=A.getSettings)==null?void 0:e.call(A),S=A.kind===VA.AUDIO?"".concat(d,"x").concat(C,"@").concat(f):"".concat(o,"x").concat(a,"@").concat(c),b=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(b)}catch{return""}}function rw(A,e){return A.width*A.height===e.width*e.height?1:db()&&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 VB(A){return A===90||A===270}function yx(A){return jA(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 xf(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]=xf(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]=xf(A[a],e)}),o}return A}var aw=(A=>(A[A.END_REPORT=2001]="END_REPORT",A[A.LOG=2002]="LOG",A[A.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",A))(aw||{});function JB(A,e,o,a){try{let c=function(d,C,f,S){let b={data:d,random:Math.floor(2147483648*Math.random()),sdkAppId:f};return xe(S)||(b=Bo(pi({},b),{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(b)}}}(A,e,o,a);return rb(Z0(c),o)}catch{return JSON.stringify(A)}}function VS(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 gw(A){return(65535&A)>>>0}function Dx(A){return(4294901760&A)>>>0}function pp(A){return!!(A&&A instanceof CanvasCaptureMediaStreamTrack&&A.canvas.id.includes("trtc_mix"))}function fq(A){let e=function(o){try{let a={},c=0;a.totalLength=su(o,c),c+=4,a.version=su(o,c),c+=4,a.encryption=cx(o,c),c+=1,a.uinType=cx(o,c),c+=1,a.uinLength=su(o,c),c+=4,a.uin=a.uinLength>4?bf(o,c,a.uinLength-4):"",c+=a.uinLength-4;let d=o.slice(c);return a.encryption===2?(o=function(C,f){let S=0,b=new Uint8Array(8).fill(0),V=new Uint8Array(C.slice(0,8)),J=cw(V,f),cA=7&J[0],CA=C.length-1-cA-Uh-US,vA=new Uint8Array(CA),$A=0,he=b,Oe=C.slice(0,8);S=8;let Se=1;Se+=cA;for(let Ne=1;Ne<=Uh;)if(Se<8)Se++,Ne++;else if(Se===8){let dt=Yf(C,S,he,Oe,J,f);he=dt.ivPreCrypt,Oe=dt.ivCurCrypt,J=dt.debiBuf,S=dt.bufPos,Se=0}let fi=CA;for(;fi>0;)if(Se<8)vA[$A++]=J[Se]^he[Se],Se++,fi--;else if(Se===8){let Ne=Yf(C,S,he,Oe,J,f);he=Ne.ivPreCrypt,Oe=Ne.ivCurCrypt,J=Ne.debiBuf,S=Ne.bufPos,Se=0}for(let Ne=1;Ne<=US;)if(Se<8)J[Se],he[Se],Se++,Ne++;else if(Se===8){if(S>=C.length)break;let dt=Yf(C,S,he,Oe,J,f);if(!dt.success)break;he=dt.ivPreCrypt,Oe=dt.ivCurCrypt,J=dt.debiBuf,S=dt.bufPos,Se=0}return vA}(d,new Uint8Array(16).fill(0)),a.decrypted=!0,c=0):(o=d,c=0),a.rspHeadLength=su(o,c),c+=4,a.seqNo=su(o,c),c+=4,a.retCode=su(o,c),c+=4,a.retStrLength=su(o,c),c+=4,a.retStr=a.retStrLength?bf(o,c,a.retStrLength-4):"",c+=a.retStrLength-4,a.serviceCmdLength=su(o,c),c+=4,a.serviceCmd=a.serviceCmdLength?bf(o,c,a.serviceCmdLength-4):"",c+=a.serviceCmdLength-4,a.cookieLength=su(o,c),c+=4,a.cookie=a.cookieLength?bf(o,c,a.cookieLength-4):"",c+=a.cookieLength-4,a.flag=su(o,c),c+=4,a.busiBuffLength=su(o,c),c+=4,a.busiBuff=a.busiBuffLength?bf(o,c,a.busiBuffLength-4):"",c+=a.busiBuffLength-4,a}catch{}}(A);return e?.busiBuff}function cw(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=nb*X0>>>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-=nb,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 Yf(A,e,o,a,c,d){if(e+8>A.length)return{success:!1};let C=new Uint8Array(a),f=A.slice(e,e+8),S=new Uint8Array(8);for(let b=0;b<8;b++)S[b]=c[b]^f[b];return{success:!0,ivPreCrypt:C,ivCurCrypt:f,debiBuf:cw(S,d),bufPos:e+8}}var mp=typeof TextDecoder<"u"?new TextDecoder:void 0;function HB(A){let{url:e,body:o,method:a="POST",timeout:c,priority:d}=A;return new Promise((C,f)=>{if("fetch"in window)return fetch(e,{method:a,body:o,priority:d}).then(b=>b.clone().json().then(V=>({data:V}),()=>b.arrayBuffer().then(V=>({data:fq(new Uint8Array(V))||(mp?mp.decode(V):V)})))).then(C,f);let S=new XMLHttpRequest;S.onreadystatechange=()=>{if(S.readyState===4)if(S.status>=200&&S.status<300)try{let b=JSON.parse(S.response);C({data:b})}catch{C({data:S.response})}else f({status:S.status,statusText:S.statusText||"request failed!"})},S.timeout=c||5e3,S.open(a,e,!0),S.send(o)})}function pb(A){return jA(this,null,function*(){let e=bo(),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(bo()-e,"ms")),c}catch{return o}})}var Sx=Object.prototype.hasOwnProperty,fp=A=>typeof A=="function",YE=A=>A===void 0,mb=A=>typeof A=="string",Mx=A=>typeof A=="boolean",fb=A=>A.isRemote,vx=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)},JS=function(A){let{retryFunction:e,settings:o,onError:a,onRetrying:c,onRetryFailed:d,onRetrySuccess:C,context:f}=A;return function(){for(var S=arguments.length,b=new Array(S),V=0;VjA(this,null,function*(){let fi=f||this;try{let Ne=yield e.apply(fi,b);CA>0&&C&&C.call(this,CA),CA=0,Oe(Ne)}catch(Ne){let dt=()=>{clearTimeout(vA),CA=0,$A=2,Se(Ne)},Ci=()=>{$A!==2&&CA<(fp(J)?J():J)?(CA++,$A=1,fp(c)&&c.call(this,CA,dt),vA=window.setTimeout(()=>{vA=-1,he(Oe,Se)},fp(cA)?cA(CA):cA)):(dt(),fp(d)&&d.call(this,Ne))};fp(a)?a.call(this,{error:Ne,retry:Ci,reject:Se,retryFuncArgs:b,retriedCount:CA}):Ci()}});return new Promise(he)}},yb=class p6{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=!Mx(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 p6({id:e.id,userId:YE(e.userId)?this.userId:e.userId,sdkAppId:YE(e.sdkAppId)?this.sdkAppId:e.sdkAppId,type:YE(e.type)?this.type:e.type,isLocal:YE(e.isLocal)?this.isLocal:e.isLocal,remoteUserId:YE(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,YE(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(vx(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(Sx.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;auw,CHROME_MAJOR_VERSION:()=>HE,CHROME_VERSION:()=>yw,EDGE_VERSION:()=>Sb,EDG_MAJOR_VERSION:()=>dw,EDG_VERSION:()=>Mb,ELECTRON_MAJOR_VERSION:()=>Lx,FIREFOX_MAJOR_VERSION:()=>Ew,FIREFOX_VERSION:()=>qS,HUAWEI_VERSION:()=>Ub,IE_VERSION:()=>Sq,IOS_MAIN_VERSION:()=>Od,IOS_VERSION:()=>wI,IPADQQB_VERSION:()=>zS,IS_ANDROID:()=>Ja,IS_ANDROID_WEBVIEW:()=>Pb,IS_ANY_SAFARI:()=>Rp,IS_CHROME:()=>fw,IS_CHROME_OS:()=>Gb,IS_CHROMIUM_128_TO_143:()=>Wf,IS_CHROMIUM_BASE:()=>tE,IS_DESKTOP_IOS_CHROME:()=>Ox,IS_EDG:()=>Jf,IS_EDGE:()=>Vf,IS_ELECTRON:()=>Mq,IS_FIREFOX:()=>er,IS_HEADLESS_CHROME:()=>kx,IS_HONOR:()=>Lb,IS_HUAWEI:()=>kb,IS_HUAWEIBROWSER:()=>Oh,IS_IE:()=>Gx,IS_IE8:()=>Dq,IS_IOS:()=>Ag,IS_IOS_13_OR_14:()=>Fx,IS_IOS_15_1:()=>Ux,IS_IOS_CHROME:()=>tM,IS_IPAD:()=>yp,IS_IPADQQB:()=>Qw,IS_IPAD_PRO:()=>Iw,IS_IPHONE:()=>Dp,IS_IPOD:()=>Tx,IS_LINUX:()=>Kf,IS_LOCAL:()=>wp,IS_MAC:()=>KB,IS_MACQQB:()=>WS,IS_MIBROWSER:()=>pw,IS_MQQB:()=>jS,IS_NATIVE_ANDROID:()=>Nx,IS_OLD_ANDROID:()=>yq,IS_OPENHARMONY:()=>jf,IS_OPPOBROWSER:()=>XS,IS_SAFARI:()=>hg,IS_SAFARI_15_1:()=>vq,IS_SAMSUNGBROWSER:()=>ZS,IS_SOGOU:()=>hw,IS_SOGOUM:()=>KS,IS_TBS:()=>JE,IS_UCBROWSER:()=>bb,IS_VIVOBROWSER:()=>$S,IS_WECHAT:()=>qB,IS_WIN:()=>qf,IS_WQQB:()=>Bw,IS_WX:()=>bx,IS_X5MQQB:()=>Mp,IS_XWEB:()=>Sp,MACQQB_VERSION:()=>Nb,MI_VERSION:()=>vp,MQQB_VERSION:()=>Hf,OPENHARMONY_VERSION:()=>mw,OPPO_VERSION:()=>Ob,SAFARI_VERSION:()=>jB,SAMSUNG_VERSION:()=>Fb,SOGOUM_VERSION:()=>Cw,SOGOU_VERSION:()=>vb,TBS_VERSION:()=>Rb,UA_DATA_STRING:()=>MC,USER_AGENT:()=>VE,VIVO_VERSION:()=>AM,WECHAT_VERSION:()=>_b,WQQB_VERSION:()=>Tb,XWEB_VERSION:()=>wb,browserInfo:()=>zB,getBrowserCoreNumber:()=>Hl,getBrowserInfo:()=>Yb,getChromeMajorVersion:()=>eM,getDeviceModel:()=>ZB,getDeviceModelFromUA:()=>Vb,getGPUInfo:()=>_p,getOSName:()=>Il,getOSNumber:()=>Tp,getOSString:()=>Np,getOSType:()=>B,getTerminalType:()=>Cn,getUserAgentData:()=>iM,isAMDGPU:()=>Zf,isAppleSiliconGPU:()=>Rq,isLocalStorageEnabled:()=>WB,isMobile:()=>Dw,isNvidiaGPU:()=>Px,isRealIOS:()=>HS,isVersionLargerThan:()=>zf,isVersionSmallerThan:()=>xb});var VE=typeof navigator>"u"?"":navigator.userAgent,_s=A=>new RegExp(A,"i").test(VE),Cg=A=>{if(_s(A)){let e=new RegExp("".concat(A,"\\/([\\d.]+)")),o=VE.match(e);if(o&&o[1])return o[1]}return""},lw=A=>{if(_s(A)){let e=new RegExp("".concat(A,"\\/(\\d+)")),o=VE.match(e);if(o&&o[1])return parseFloat(o[1])}return NaN},Db=/AppleWebKit\/([\d.]+)/i.exec(VE),_x=Db?parseFloat(Db[1]):NaN,yp=_s("iPad"),Iw=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&_s("Macintosh"),Dp=_s("iPhone")&&!yp,Tx=_s("iPod"),Ag=Dp||yp||Tx||Iw,HS=()=>{try{return Ag&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return Ag}},Ja=_s("Android"),uw=function(){if(Ja){let A=VE.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}(),yq=Ja&&_s("webkit")&&uw<2.3,Nx=Ja&&uw<5&&_x<537,er=_s("Firefox"),qS=Cg("Firefox"),Ew=lw("Firefox"),Vf=_s("Edge"),Sb=Cg("Edge"),Jf=_s("Edg"),Mb=Cg("Edg"),dw=lw("Edg"),KS=_s("SogouMobileBrowser"),Cw=Cg("SogouMobileBrowser"),hw=_s("MetaSr\\s"),vb=Cg("MetaSr\\s"),JE=_s("TBS"),Rb=Cg("TBS"),Sp=_s("XWEB"),wb=Cg("XWEB"),Dq=_s("MSIE\\s8\\.0"),Gx=_s("MSIE\\/\\d+"),Sq=function(){if(Gx){let A=/MSIE\s(\d+)\.\d/.exec(VE),e=A&&parseFloat(A[1]);return!e&&/Trident\/7.0/i.test(VE)&&/rv:11.0/.test(VE)&&(e=11),e}return NaN}(),qB=_s("(micromessenger|webbrowser)"),_b=Cg("MicroMessenger"),Mp=!JE&&_s("MQQBrowser")&&_s("COVC"),jS=!JE&&_s("MQQBrowser")&&!_s("COVC"),Hf=jS||Mp?Cg("MQQBrowser"):"",Bw=!JE&&_s(" QQBrowser"),Tb=Cg(" QQBrowser"),WS=!JE&&_s("QQBrowserLite"),Nb=Cg("QQBrowserLite"),Qw=!JE&&_s("MQBHD"),zS=Cg("MQBHD"),qf=_s("Windows"),KB=!Ag&&_s("MAC OS X"),Kf=!Ja&&_s("Linux"),Gb=_s("CrOS"),bx=_s("MicroMessenger"),bb=_s("UCBrowser"),Mq=_s("Electron"),pw=_s("MiuiBrowser"),vp=Cg("MiuiBrowser"),Oh=_s("HuaweiBrowser"),kb=_s("Huawei")||_s("HUAWEI"),Lb=_s("Honor")||_s("HONOR"),Ub=Cg("HuaweiBrowser"),ZS=_s("SamsungBrowser"),Fb=Cg("SamsungBrowser"),XS=_s("HeyTapBrowser"),Ob=Cg("HeyTapBrowser"),$S=_s("VivoBrowser"),AM=Cg("VivoBrowser"),jf=_s("OpenHarmony"),mw=Cg("OpenHarmony"),eM=()=>lw("Chrome"),tM=_s("CriOS"),tE=_s("Chrome"),fw=!Vf&&!hw&&!KS&&!JE&&!Sp&&!Jf&&!Bw&&!pw&&!Oh&&!ZS&&!XS&&!$S&&tE,kx=_s("HeadlessChrome"),HE=eM(),Wf=tE&&HE>=128&&HE<=143,yw=Cg("Chrome"),Lx=lw("Electron"),hg=!tE&&!jS&&!Mp&&!WS&&!Qw&&_s("Safari"),Rp=hg||Ag,jB=Cg("Version"),Pb=/Android.*(wv|.0.0.0)/.test(VE),wI=(()=>{if(Iw)return jB;if(Ag){let A=VE.match(/OS (\d+)_(\d+)/i);if(A&&A[1]){let e=A[1];return A[2]&&(e+=".".concat(A[2])),e}}return""})();function xb(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 zf(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;df)return!0;if(C{let A=Number(wI.split(".")[0]);return A===14||A===13})(),Ox=tM&&jB==="11.1.1",wp=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),WB=(()=>{let A;return()=>{if(A===void 0)try{A=!!window.localStorage}catch{A=!1}return A}})(),zB=Yb();function Yb(){let A=new Map([[er,["Firefox",qS]],[Jf,["Edg",Mb]],[fw,["Chrome",yw]],[tM,["ChiOS",Cg("CriOS")]],[hg&&!tM,["Safari",jB]],[JE,["TBS",Rb]],[Sp,["XWEB",wb]],[qB&&Dp,["WeChat",_b]],[Bw,["QQ(Win)",Tb]],[jS,["QQ(Mobile)",Hf]],[Mp,["QQ(Mobile X5)",Hf]],[WS,["QQ(Mac)",Nb]],[Qw,["QQ(iPad)",zS]],[pw,["MI",vp]],[Oh,["HW",Ub]],[ZS,["Samsung",Fb]],[XS,["OPPO",Ob]],[$S,["VIVO",AM]],[Vf,["EDGE",Sb]],[KS,["SogouMobile",Cw]],[hw,["Sogou",vb]]]),e="unknown",o="unknown";return A.has(!0)&&([e,o]=A.get(!0)),{name:e,version:o}}var Ur=null;function Dw(){return Ur&&typeof Ur.mobile=="boolean"?Ur.mobile:Ja||Ag||Dp||yp||jf}var MC="";function iM(){return jA(this,null,function*(){if(Ur)return Ur;if(!navigator.userAgentData||typeof navigator.userAgentData.getHighEntropyValues!="function")return null;try{return(Ur=yield navigator.userAgentData.getHighEntropyValues(["architecture","bitness","model","platformVersion","fullVersionList"]))&&!MC&&(MC="UAData: ".concat(Ur.platform,"/").concat(Ur.platformVersion),Ur.architecture&&Ur.bitness&&(MC+=" ".concat(Ur.architecture,"/").concat(Ur.bitness)),Ur.mobile&&(MC+=" mobile"),Ur.model&&(MC+=" model: ".concat(Ur.model.replace(/\s+/g,"/"))),Ur.fullVersionList&&(MC+=" ".concat(Ur.fullVersionList.filter(A=>A.brand!=="Not/A)Brand").map(A=>"".concat(A.brand,"/").concat(A.version)).join(",")))),Ur}catch{return null}})}var oM="";function _p(){try{if(oM)return oM;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 oM="".concat(a," ").concat(c)}return""}catch{return""}}function Zf(){try{let A=_p();return A.includes("AMD")||A.includes("ATI")}catch{return!1}}function Px(){try{let A=_p();return A.includes("NVIDIA")||A.includes("GeForce")}catch{return!1}}function Rq(){try{return _p().includes("Apple M")}catch{return!1}}function ZB(){return Ur?.model||Vb()||""}function Vb(){let A=VE.match(/;\s*([^;)]+)\s+Build\//);return A!=null&&A[1]?A[1].trim():null}var xx=new Map([[Ja,"Android"],[Ag,"iOS"],[qf,"Windows"],[KB,"MacOS"],[Kf,"Linux"],[Gb,"ChromeOS"]]),Il=function(){return xx.get(!0)?xx.get(!0):Ur?Ur.platform:"unknown"};function Tp(){return qf?1:Ja?2:KB?3:Ag?4:Kf?5:Gb?6:jf?7:0}function Hl(){return qB||Sp?4:tE?1:hg?2:er?3:0}var Np=()=>{let A=Il();return Ur!=null&&Ur.platformVersion?A+="/".concat(Ur.platformVersion):Ag?A+="/".concat(wI):Ja&&(A+="/".concat(uw)),A+="/".concat(zB.name,"/").concat(hg&&!tM?zB.version:zB.version.split(".")[0]),Ur!=null&&Ur.architecture&&(A+="/".concat(Ur.architecture)),A};function Cn(){return Ja?4:Dp?2:yp?3:KB?12:qf?5:Kf?13:jf?22:1}function B(){return Ja?"Android":Dp?"iPhone":yp?"iPad":KB?"Mac":qf?"Windows":Kf?"Linux":"unknown"}var R,U=new(ac(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),U.on("22",A=>{let{schedule:e}=A;var o;(o=e?.config)!=null&&o.sso&&U.emit("266",{enable:!0})}),U.on("266",A=>{let{enable:e}=A;this.enable=e})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&U.emit("266",{enable:!1})}},ZA=class m6{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),!k0&&!L0&&(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){U.on(nA.JOIN_SCHEDULE_SUCCESS,e=>{let{schedule:o}=e;var a;(a=o?.config)!=null&&a.logLevelToUpload&&OB[o.config.logLevelToUpload]&&(this._logLevelToUpload=o.config.logLevelToUpload)}),U.on(nA.JOIN_START,e=>{let{params:o}=e;this.addJoinedUser({userId:o.userId,sdkAppId:o.sdkAppId}),this.startUpload()}),U.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 jA(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;dcA.log).join(` +`)},V=JSON.stringify(b),J=TA.enable?JB(b,2002,f):V;yield this.uploadLogWithRetry(J,f,J instanceof Uint8Array,V),S.forEach(cA=>cA.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 JS({retryFunction:()=>HB({url:kf(o,RI.LOG),body:e,timeout:5e3,priority:"low"}).then(d=>{a&&d.data!=="ok"&&(TA.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(Mf()),"[".concat(HG(o),"] <").concat(OB[e],">")}getLogLevel(){return this._logLevel}setLogLevel(e){xe(OB[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((f,S)=>"".concat(f," ").concat(this.logChunkToString(S)).trim(),""),level:e,userId:c,sdkAppId:d,forAllJoinedClients:a};U.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)})},WA=new class{constructor(){Y(this,"_prefix","TRTC"),Y(this,"_queue",new Map)}getRealKey(A){return"".concat(this._prefix,"_").concat(A)}checkStorage(){WB()&&(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(WB())try{for(let[A,e]of this._queue)localStorage.setItem(A,JSON.stringify(e))}catch(A){QA.warn(A)}}getItem(A){if(!WB())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(WB())try{let o={expiresIn:Date.now()+O0,value:e};this._queue.set(this.getRealKey(A),o)}catch(o){QA.warn(o)}}deleteItem(A){if(!WB())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(WB())try{localStorage.clear()}catch(A){QA.warn(A)}}},te={};bh(te,{HTTPS_API:()=>ok,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>Zx,IS_GET_CAPABILITIES_SUPPORTED:()=>zx,IS_GET_SETTINGS_SUPPORTED:()=>ny,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>ck,IS_INSERTABLE_STREAM_SUPPORTED:()=>Up,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>iQ,IS_RTC_RTP_SENDER_SUPPORTED:()=>vC,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>Gw,IS_SEI_SUPPORTED:()=>lk,IS_SPC_SUPPORTED:()=>EM,basis:()=>$x,capabilityCheck:()=>Ek,checkSystemRequirementsInternal:()=>tk,decodeSupportStatus:()=>ek,detectH264SupportedByFakeStreaming:()=>jx,detectVideoCodecCapabilities:()=>CM,detectVideoDecoderCapabilities:()=>Ck,detectVideoEncoderCapabilities:()=>dk,encodeSupportStatus:()=>cM,getBrowserInfo:()=>aM,getDisplayResolution:()=>jE,getH264ProfileLevelIds:()=>t2,isAddTransceiverSupported:()=>Pd,isBrowserSupported:()=>$b,isCanvasCaptureStreamAPISupported:()=>IM,isCanvasSmallStreamSupported:()=>Nw,isGetReceiversSupported:()=>sy,isGetSendersSupported:()=>_I,isGetTransceiversSupported:()=>tQ,isGetUserMediaSupported:()=>sk,isMediaDevicesSupported:()=>Ak,isMediaSessionSupported:()=>Xx,isMediaStreamTrackGeneratorSupported:()=>Tq,isMediaStreamTrackProcessorSupported:()=>gM,isReplaceTrackSupported:()=>Wx,isRequestVideoFrameCallbackSupported:()=>Fp,isSIMDSupported:()=>dM,isScaleResolutionDownBySupported:()=>rk,isScreenCaptureApiAvailable:()=>Lp,isSelectedCandidatePair:()=>lM,isSetParametersSupported:()=>gk,isSetSinkIdSupported:()=>Gq,isSmallStreamSupported:()=>uM,isStopTransceiverSupported:()=>ea,isTRTCSupported:()=>Nq,isUnifiedPlanDefault:()=>ak,isUsedInHttpProtocol:()=>nu,isWebAudioSupported:()=>nk,isWebCodecSupported:()=>bw,isWebCodecsSupported:()=>Tw,isWebRTCSupported:()=>ry,isWebTransportSupported:()=>ay});var be={};bh(be,{AUDIO_LEVEL_SCALE:()=>qE,AlphaStitchingType:()=>ty,AudioCodecPipelineType:()=>eQ,AudioDecoderDowngradeState:()=>sM,AudioPlayerMode:()=>vw,AudioType:()=>Yx,BASIC_TYPE:()=>jb,BannedReason:()=>Bg,CONNECTION_CLOSED_REASON:()=>Yt,CheckPermissionType:()=>gr,ClientEvent:()=>We,CodecType:()=>nM,ConnectionEvent:()=>Po,ConnectionState:()=>Xf,DECODE_FAILED_ERROR_CODE:()=>rM,DenoiserMode:()=>Gp,DeviceType:()=>Wb,FacingMode:()=>Hb,FrameWorkType:()=>eo,LeaveReason:()=>qb,LocalTrackEvent:()=>Do,MULTI_VIDEO_DATA_TYPE:()=>ey,MediaType:()=>Sw,MediaTypeLabel:()=>wq,MonitorEventId:()=>ul,MutedFlag:()=>Zn,NetworkQualityValue:()=>iE,PlayerState:()=>Io,ReceiveMode:()=>ql,RemoteStreamType:()=>Ay,RemoteTrackEvent:()=>hn,RoomEvent:()=>lo,SMALL_MODE:()=>kp,SceneNumber:()=>Ha,StreamEvent:()=>Di,StreamType:()=>AQ,SubscribeMediaType:()=>Kb,TIMER_TYPE:()=>ww,TRACK_ACTION:()=>Jb,TRACK_KIND:()=>XB,TrackEvent:()=>xo,UserRole:()=>Uc,UserRoleNumber:()=>As,VideoCodec:()=>El,VideoCodecPipelineType:()=>bp,VideoContentHint:()=>Rw,VideoDecoderDowngradeState:()=>$f,VideoPlayerMode:()=>Mw,VideoType:()=>$B});var _e,Ce,at,ni,Ze,Je,dA,ht,ze,Vi,ci,eo=(A=>(A[A.WEBRTC=30]="WEBRTC",A[A.WASM=37]="WASM",A))(eo||{}),Po=((ci=Po||{}).TRACK_ADDED="track-added",ci.TRACK_UPDATED="track-updated",ci.TRACK_SUBSCRIBED="track-subscribed",ci.STREAM_ADDED="stream-added",ci.STREAM_REMOVED="stream-removed",ci.STREAM_UPDATED="stream-updated",ci.STREAM_PUBLISHED="stream-published",ci.STREAM_SUBSCRIBED="stream-subscribed",ci.STREAM_UNSUBSCRIBED="stream-unsubscribed",ci.STATE_CHANGED="state-changed",ci.ERROR="error",ci.CONNECTION_STATE_CHANGED="connection-state-changed",ci.FIREWALL_RESTRICTION="firewall-restriction",ci.SEI_MESSAGE="sei-message",ci.CLOSED="closed",ci),Yt=(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))(Yt||{}),We=((Vi=We||{}).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),Di=((ze=Di||{}).PLAYER_STATE_CHANGED="player-state-changed",ze.SCREEN_SHARING_STOPPED="screen-sharing-stopped",ze.CONNECTION_STATE_CHANGED="connection-state-changed",ze.DEVICE_AUTO_RECOVERED="device-auto-recovered",ze.ERROR="error",ze),Do=((ht=Do||{}).DEVICE_AUTO_RECOVERED="1",ht.DEVICE_RECOVER_FAILED="5",ht.DEVICE_CHANGED="2",ht.ERROR="3",ht.PUBLISH_STATE_CHANGED="4",ht.ENCODE_FAILED="6",ht.TRACK_ENDED="7",ht.RENDER="render",ht),Io=(A=>(A.PAUSED="PAUSED",A.PLAYING="PLAYING",A.STOPPED="STOPPED",A))(Io||{}),lo=((dA=lo||{}).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),xo=((Je=xo||{}).PLAYER_STATE_CHANGED="player-state-changed",Je.MUTE="mute",Je.UNMUTE="unmute",Je.ERROR="error",Je.INPUT_MEDIA_TRACK_CHANGED="input-media-track-changed",Je.OUTPUT_MEDIA_TRACK_CHANGED="output-media-track-changed",Je.FIRST_VIDEO_FRAME="first-video-frame",Je.FIRST_FRAME_RENDER="first-frame-render",Je.VIDEO_SIZE_CHANGED="video-size-changed",Je),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=((Ze=Zn||{})[Ze.VIDEO=1]="VIDEO",Ze[Ze.SMALL=2]="SMALL",Ze[Ze.AUX=4]="AUX",Ze[Ze.AUDIO=8]="AUDIO",Ze[Ze.VIDEO_MUTE=16]="VIDEO_MUTE",Ze[Ze.AUX_MUTE=32]="AUX_MUTE",Ze[Ze.AUDIO_MUTE=64]="AUDIO_MUTE",Ze),Ha=(A=>(A[A.RTC=1]="RTC",A[A.LIVE=2]="LIVE",A))(Ha||{}),As=(A=>(A[A.ANCHOR=20]="ANCHOR",A[A.AUDIENCE=21]="AUDIENCE",A))(As||{}),Uc=(A=>(A.ANCHOR="anchor",A.AUDIENCE="audience",A))(Uc||{}),Xf=(A=>(A.CONNECTED="CONNECTED",A.DISCONNECTED="DISCONNECTED",A.CONNECTING="CONNECTING",A.RECONNECTED="RECONNECTED",A.RECONNECTING="RECONNECTING",A))(Xf||{}),sM=((ni=sM||{}).INITIALIZED="INITIALIZED",ni.STARTING="STARTING",ni.STARTED="STARTED",ni.FAILED="FAILED",ni),$f=(A=>(A.INITIALIZED="INITIALIZED",A.STARTING="STARTING",A.STARTED="STARTED",A.FAILED="FAILED",A))($f||{}),XB=(A=>(A.AUDIO="audio",A.VIDEO="video",A.AUXILIARY="auxVideo",A))(XB||{}),Jb=(A=>(A.ADD="add",A.REMOVE="remove",A))(Jb||{}),Sw=(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))(Sw||{}),wq={1:"audio",2:"auxVideo",4:"video"},Yx=((at=Yx||{})[at.opus=111]="opus",at),$B=(A=>(A[A.h264=100]="h264",A[A.vp8=101]="vp8",A))($B||{}),AQ=(A=>(A.Big="big",A.Small="small",A))(AQ||{}),Ay=(A=>(A.Main="main",A.Aux="auxiliary",A))(Ay||{}),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||{}),ul=((Ce=ul||{})[Ce.PUBLISH_VIDEO=32768]="PUBLISH_VIDEO",Ce[Ce.PUBLISH_AUDIO=32769]="PUBLISH_AUDIO",Ce[Ce.UNPUBLISH_VIDEO=32770]="UNPUBLISH_VIDEO",Ce[Ce.UNPUBLISH_AUDIO=32771]="UNPUBLISH_AUDIO",Ce[Ce.MUTE_AUDIO=32772]="MUTE_AUDIO",Ce[Ce.MUTE_VIDEO=32773]="MUTE_VIDEO",Ce[Ce.UNMUTE_AUDIO=32774]="UNMUTE_AUDIO",Ce[Ce.UNMUTE_VIDEO=32775]="UNMUTE_VIDEO",Ce[Ce.SUBSCRIBE_VIDEO=32776]="SUBSCRIBE_VIDEO",Ce[Ce.SUBSCRIBE_AUDIO=32777]="SUBSCRIBE_AUDIO",Ce[Ce.UNSUBSCRIBE_VIDEO=32778]="UNSUBSCRIBE_VIDEO",Ce[Ce.UNSUBSCRIBE_AUDIO=32779]="UNSUBSCRIBE_AUDIO",Ce[Ce.SWITCH_CAMERA=32780]="SWITCH_CAMERA",Ce[Ce.SWITCH_MICROPHONE=32781]="SWITCH_MICROPHONE",Ce[Ce.REPLACE_VIDEO=32782]="REPLACE_VIDEO",Ce[Ce.REPLACE_AUDIO=32783]="REPLACE_AUDIO",Ce[Ce.MUTE_REMOTE_VIDEO=32784]="MUTE_REMOTE_VIDEO",Ce[Ce.MUTE_REMOTE_AUDIO=32785]="MUTE_REMOTE_AUDIO",Ce[Ce.UNMUTE_REMOTE_VIDEO=32786]="UNMUTE_REMOTE_VIDEO",Ce[Ce.UNMUTE_REMOTE_AUDIO=32787]="UNMUTE_REMOTE_AUDIO",Ce[Ce.JOIN=32788]="JOIN",Ce[Ce.LEAVE=32789]="LEAVE",Ce[Ce.SIGNAL_DISCONNECTED=32790]="SIGNAL_DISCONNECTED",Ce[Ce.SIGNAL_CONNECTED=32791]="SIGNAL_CONNECTED",Ce[Ce.TRANSPORT_UPLINK_CONNECTED=32792]="TRANSPORT_UPLINK_CONNECTED",Ce[Ce.TRANSPORT_DOWNLINK_CONNECTED=32793]="TRANSPORT_DOWNLINK_CONNECTED",Ce[Ce.SIGNAl_RECONNECTING=32794]="SIGNAl_RECONNECTING",Ce[Ce.SIGNAL_RECONNECT_SUCCESS=32795]="SIGNAL_RECONNECT_SUCCESS",Ce[Ce.SIGNAL_RECONNECT_FAIL=32796]="SIGNAL_RECONNECT_FAIL",Ce[Ce.TRANSPORT_UPLINK_RECONNECTING=32797]="TRANSPORT_UPLINK_RECONNECTING",Ce[Ce.TRANSPORT_UPLINK_RECONNECT_SUCCESS=32798]="TRANSPORT_UPLINK_RECONNECT_SUCCESS",Ce[Ce.TRANSPORT_UPLINK_RECONNECT_FAIL=32799]="TRANSPORT_UPLINK_RECONNECT_FAIL",Ce[Ce.TRANSPORT_DOWNLINK_RECONNECTING=32800]="TRANSPORT_DOWNLINK_RECONNECTING",Ce[Ce.TRANSPORT_DOWNLINK_RECONNECT_SUCCESS=32801]="TRANSPORT_DOWNLINK_RECONNECT_SUCCESS",Ce[Ce.TRANSPORT_DOWNLINK_RECONNECT_FAIL=32802]="TRANSPORT_DOWNLINK_RECONNECT_FAIL",Ce[Ce.SUBSCRIBE_SMALL_VIDEO=32803]="SUBSCRIBE_SMALL_VIDEO",Ce[Ce.UNSUBSCRIBE_SMALL_VIDEO=32804]="UNSUBSCRIBE_SMALL_VIDEO",Ce[Ce.PUBLISH_AUX=32805]="PUBLISH_AUX",Ce[Ce.UNPUBLISH_AUX=32806]="UNPUBLISH_AUX",Ce[Ce.DEVICE_CAPTURE=2003]="DEVICE_CAPTURE",Ce[Ce.VIDEO_ENCODER=4004]="VIDEO_ENCODER",Ce[Ce.VIDEO_DECODER=4005]="VIDEO_DECODER",Ce),iE=(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))(iE||{}),ql=(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))(ql||{}),Hb=(A=>(A.user="user",A.environment="environment",A))(Hb||{}),Mw=(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))(Mw||{}),vw=(A=>(A[A.ELEMENT=0]="ELEMENT",A[A.CONTEXT=1]="CONTEXT",A))(vw||{}),Bg=(A=>(A.BANNED="banned",A.KICK="kick",A.USER_TIME_OUT="user_time_out",A.ROOM_DISBAND="room_disband",A))(Bg||{}),qb=(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))(qb||{}),qE=1e8,Gp=(A=>(A[A.NORMAL=0]="NORMAL",A[A.FAR_FIELD_REDUCTION=1]="FAR_FIELD_REDUCTION",A))(Gp||{}),Kb=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)}},jb=(A=>(A.String="string",A.Number="number",A.Boolean="boolean",A.Array="array",A.Object="object",A))(jb||{}),El=(A=>(A.H264="h264",A.H265="h265",A.VP8="vp8",A.VP9="vp9",A.AV1="av1",A))(El||{}),bp=(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))(bp||{}),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||{}),nM=(A=>(A.WebRTC="webrtc",A.WebCodecs="webcodecs",A.WebAssembly="webassembly",A))(nM||{}),rM=((_e=rM||{})[_e.SUCCESS=0]="SUCCESS",_e[_e.FAILED=1]="FAILED",_e[_e.WEBCODEC_INIT=2]="WEBCODEC_INIT",_e[_e.WEBCODEC_CONFIG_NOT_SUPPORT=3]="WEBCODEC_CONFIG_NOT_SUPPORT",_e[_e.WEBCODEC_DECODER_ERROR=4]="WEBCODEC_DECODER_ERROR",_e[_e.WEBCODEC_TRACK_MUTE=5]="WEBCODEC_TRACK_MUTE",_e[_e.WASM_INIT=6]="WASM_INIT",_e[_e.WASM_WEBGL_UNAVALIABLE=7]="WASM_WEBGL_UNAVALIABLE",_e[_e.WASM_DECODER_ERROR=8]="WASM_DECODER_ERROR",_e[_e.WASM_TRACK_MUTE=9]="WASM_TRACK_MUTE",_e[_e.TEST=10]="TEST",_e[_e.RENDER_2D_ERROR=11]="RENDER_2D_ERROR",_e),Rw=(A=>(A.NONE="",A.DETAIL="detail",A.MOTION="motion",A.TEXT="text",A))(Rw||{}),ww=(A=>(A.INTERVAL="interval",A.TIMEOUT="timeout",A.RAF="raf",A.RIC="ric",A.INTERVAL_IN_WORKER="intervalInWorker",A))(ww||{}),kp=(A=>(A.CANVAS="canvas",A.API="api",A))(kp||{}),gr=(A=>(A[A.NONE=0]="NONE",A[A.MICROPHONE=1]="MICROPHONE",A[A.CAMERA=2]="CAMERA",A[A.BOTH=3]="BOTH",A))(gr||{}),Wb=(A=>(A.CAMERA="camera",A.MICROPHONE="microphone",A))(Wb||{}),ty=(A=>(A[A.none=0]="none",A[A.horizontal=1]="horizontal",A[A.vertical=2]="vertical",A))(ty||{}),So={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"},gc={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(dg(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(dg(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,".")},Vx=(A,e)=>e?"".concat(kh,"/").concat(A,"/").concat(e):"".concat(kh,"/").concat(A,"/index.html"),zb=()=>{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(SS);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 Zo(A){let{key:e,data:o,link:a,addDocLink:c=!0}=A,d="",C="",f="";Ma(gc[e])?d=gc[e](o):Yn(gc[e])&&(d=gc[e]);let{TRTC_ERROR_INFO:S,TRTC_ERROR_LINK:b}=zb();a?f="".concat(a.className,".html#").concat(a.fnName):b&&b[e]&&(Ma(b[e])?f=b[e](o):Yn(b[e])&&(f=b[e]));let V=d;return Ud()&&(S&&S[e]&&(Ma(S[e])?C=S[e](o):Yn(S[e])&&(C=S[e])),C&&(V=c?"".concat(C,` +请查看文档: `).concat(Vx("zh-cn",f),` + +`):"".concat(C,` + +`),V+=d)),c&&(V+=` +Refer to: `.concat(Vx("en",f),` +`)),V}var hs,Bn,Zb=ac(rq(),1),Xb=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&&(U.on("102",e=>{let{track:o,cost:a}=e;this.addSuccessEvent({key:o.kind===VA.AUDIO?501700:511700,cost:a})}),U.on("103",e=>{let{track:o,error:a}=e;this.addFailedEvent({key:o.kind===VA.AUDIO?501700:511700,error:a})}),U.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:Cb(this.version||kd),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[f,S]=C;return{uint32_item_key:f,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 f=((C=this.distributionMap)==null?void 0:C.get(e))||new Map,S=0;if(bn(a))S=Math.floor(o/a);else for(let b=a.length-1;b>0;b--)if(o>a[b]){S=b;break}f.set(S,(f.get(S)||0)+1),this.distributionMap.set(e,f)}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=lt.UNKNOWN;o&&(bn(o)?a=o:(!xe(o.extraCode)||!xe(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})}},Jx=((hs=Jx||{})[hs.enterRoom=500700]="enterRoom",hs[hs.exitRoom=500701]="exitRoom",hs[hs.switchRole=500702]="switchRole",hs[hs.destroy=500703]="destroy",hs[hs.startLocalAudio=500704]="startLocalAudio",hs[hs.updateLocalAudio=500705]="updateLocalAudio",hs[hs.stopLocalAudio=500706]="stopLocalAudio",hs[hs.startLocalVideo=500707]="startLocalVideo",hs[hs.updateLocalVideo=500708]="updateLocalVideo",hs[hs.stopLocalVideo=500709]="stopLocalVideo",hs[hs.startScreenShare=500710]="startScreenShare",hs[hs.updateScreenShare=500711]="updateScreenShare",hs[hs.stopScreenShare=500712]="stopScreenShare",hs[hs.startRemoteVideo=500713]="startRemoteVideo",hs[hs.updateRemoteVideo=500714]="updateRemoteVideo",hs[hs.stopRemoteVideo=500715]="stopRemoteVideo",hs[hs.muteRemoteAudio=500716]="muteRemoteAudio",hs[hs.setRemoteAudioVolume=500717]="setRemoteAudioVolume",hs[hs.use=500718]="use",hs[hs.switchRoom=500719]="switchRoom",hs[hs.getPermissions=500720]="getPermissions",hs[hs.sendSEIMessage=5e5]="sendSEIMessage",hs[hs.sendCustomMessage=500001]="sendCustomMessage",hs),Hx=(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))(Hx||{}),iy=(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))(iy||{}),_w=(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))(_w||{}),oy=((Bn=oy||{})[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),_q=new Xb(!0),Ph=new Xb(!1),Ai=_q,Bs={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}},qx=new Map([[er,["Firefox",qS]],[Jf,["Edg",Mb]],[fw,["Chrome",yw]],[hg,["Safari",jB]],[JE,["TBS",Rb]],[Sp,["XWEB",wb]],[qB&&Dp,["WeChat",_b]],[Bw,["QQ(Win)",Tb]],[jS,["QQ(Mobile)",Hf]],[Mp,["QQ(Mobile X5)",Hf]],[WS,["QQ(Mac)",Nb]],[Qw,["QQ(iPad)",zS]],[pw,["MI",vp]],[Oh,["HW",Ub]],[ZS,["Samsung",Fb]],[XS,["OPPO",Ob]],[$S,["VIVO",AM]],[Vf,["EDGE",Sb]],[KS,["SogouMobile",Cw]],[hw,["Sogou",vb]]]);function aM(){let A=qx.get(!0);return{browserName:A?A[0]:"unknown",browserVersion:A?A[1]:"unknown"}}var $b=function(){return!(bb||Vf||Jf&&dw<80||er&&Ew<56)},Tw=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(A=>A in window)},Ak=function(){if(!navigator.mediaDevices)return nu()||QA.error(gc.NOT_SUPPORTED_MEDIA),!1;let A=["getUserMedia","enumerateDevices"];return A.filter(e=>e in navigator.mediaDevices).length===A.length},Kx=!1;function nu(){return location.protocol==="http:"&&!wp&&(Kx||QA.error(Zo({key:So.NOT_SUPPORTED_HTTP})),Kx=!0,!0)}var gM=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},Tq=function(){return!(window==null||!window.MediaStreamTrackGenerator)},cM=function(){return jA(this,null,function*(){var A,e,o;if(Bs.detail.isH264EncodeSupported&&Bs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Bs.detail.isH264EncodeSupported,isVp8EncodeSupported:Bs.detail.isVp8EncodeSupported,isH265EncodeSupported:Bs.detail.isH265EncodeSupported};let a,c=!1,d=!1,C=!1;try{let f=new RTCPeerConnection,S=document.createElement(VA.CANVAS);S.getContext("2d");let b=S.captureStream(0);return f.addTrack(b.getVideoTracks()[0],b),a=yield f.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,f.close(),{isH264EncodeSupported:c,isVp8EncodeSupported:d,isH265EncodeSupported:C}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}})},ek=function(){return jA(this,null,function*(){var A;if(Bs.detail.isH264DecodeSupported&&Bs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Bs.detail.isH264DecodeSupported,isVp8DecodeSupported:Bs.detail.isVp8DecodeSupported,isH265DecodeSupported:Bs.detail.isH265DecodeSupported};let e,o=!1,a=!1;try{let c=new RTCPeerConnection;Pd()?(c.addTransceiver(VA.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}}})},tk=hb(A=>jA(null,null,function*(){let e=Date.now(),o=ry(),a=Ak(),c=Tw();if(Bs.detail.isWebRTCSupported=o,Bs.detail.isMediaDevicesSupported=a,Bs.detail.isWebCodecsSupported=c,Bs.detail.isScreenShareSupported=Lp(),Bs.detail.isSmallStreamSupported=uM(),A===37)return Object.assign(Bs.detail,yield function(){return jA(this,null,function*(){return KE||(KE=new Promise(vA=>jA(null,null,function*(){let $A={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!Tw())return void vA($A);let he=null,Oe=null,Se=null,fi=()=>{Se&&clearTimeout(Se),he=null,Oe=null};try{he=document.createElement("canvas"),Oe=he.getContext("2d"),he.width=320,he.height=240;let Ne=0,dt=()=>{!Oe||!he||(Oe.fillStyle="hsl(".concat(Ne%360,", 50%, 50%)"),Oe.fillRect(0,0,he.width,he.height),Oe.fillStyle="white",Oe.font="20px Arial",Oe.fillText("Frame ".concat(Ne),10,30),Ne++)};Se=setTimeout(()=>{fi(),vA($A)},5e3);let Ci=[{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(Ci.map(yi=>jA(null,null,function*(){let Yo,Vo={type:yi.type,encodeSupported:!1,decodeSupported:!1};try{Yo=yield new Promise((Qn,Jo)=>jA(null,null,function*(){try{let Ts=new VideoEncoder({output:ma=>{Qn(ma),Vo.encodeSupported=!0},error:Jo});Ts.configure(yi.encodeConfig),dt();let Qg=new VideoFrame(he,{timestamp:0});Ts.encode(Qg,{keyFrame:!0}),Qg.close(),yield Ts.flush(),Ts.close()}catch(Ts){Jo(Ts)}}))}catch(Qn){return QA.warn("".concat(yi.type," encoder error:"),Qn),Vo}try{yield new Promise((Qn,Jo)=>jA(null,null,function*(){try{let Ts=new VideoDecoder({output:Qg=>{Vo.decodeSupported=!0,Qn(0),Qg.close()},error:Jo});Ts.configure(yi.decodeConfig),Ts.decode(Yo),yield Ts.flush(),Ts.close()}catch(Ts){Jo(Ts)}}))}catch(Qn){QA.warn("".concat(yi.type," decoder error:"),Qn)}return Vo})))).forEach(yi=>{yi.type==="h264"?($A.isH264EncodeSupported=yi.encodeSupported,$A.isH264DecodeSupported=yi.decodeSupported):yi.type==="vp8"&&($A.isVp8EncodeSupported=yi.encodeSupported,$A.isVp8DecodeSupported=yi.decodeSupported)}),fi(),vA($A)}catch(Ne){fi(),QA.warn("detectWebCodecsSupported failed:",Ne),vA($A)}})),KE)})}()),Bs.detail.isBrowserSupported=c,Bs.result=a&&c,Bs.result||QA.error("".concat(navigator.userAgent," ").concat(ow(Bs.detail,!1))),uk(A),Ai.addNumber({key:523800,value:Date.now()-e}),Bs;if(Bs.result&&Bs.detail.isH264EncodeSupported&&Bs.detail.isVp8EncodeSupported&&Bs.detail.isH265EncodeSupported&&Bs.detail.isH264DecodeSupported&&Bs.detail.isVp8DecodeSupported&&Bs.detail.isH265DecodeSupported)return Bs;let d=$b(),{encode:C,decode:f}=yield function(){return jA(this,null,function*(){let[vA,$A]=yield Promise.all([cM(),ek()]);return{encode:{h264:vA.isH264EncodeSupported,vp8:vA.isVp8EncodeSupported,h265:vA.isH265EncodeSupported},decode:{h264:$A.isH264DecodeSupported,vp8:$A.isVp8DecodeSupported,h265:$A.isH265DecodeSupported}}})}(),{h264:S,vp8:b}=C,{h264:V}=f,{h265:J}=C,{vp8:cA,h265:CA}=f;if(!S||!b){let vA=yield cM();QA.warn("detect encode again h264:".concat(S," vp8:").concat(b," result: ").concat(JSON.stringify(vA))),S=vA.isH264EncodeSupported,b=vA.isVp8EncodeSupported}if(S&&V&&Ja&&tE&&!Sp&&!JE&&(!XS||HE!==115)){let{encode:vA,decode:$A}=yield jx();S=vA,V=$A}return Bs.result=d&&o&&a&&(S||b)&&(V||cA),Bs.detail.isBrowserSupported=d,Bs.detail.isWebRTCSupported=o,Bs.detail.isH264EncodeSupported=S,Bs.detail.isVp8EncodeSupported=b,Bs.detail.isH265EncodeSupported=J,Bs.detail.isH264DecodeSupported=V,Bs.detail.isVp8DecodeSupported=cA,Bs.detail.isH265DecodeSupported=CA,Bs.result||QA.error("".concat(navigator.userAgent," ").concat(ow(Bs.detail,!1))),uk(),Ai.addNumber({key:523800,value:Date.now()-e}),Bs})),Nq=function(){return Bs.result},Lp=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},Gq=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,ik=null;function jx(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:2e3;return jA(this,null,function*(){return ik||(ik=new Promise(e=>jA(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),f=-1,S=-1;a=()=>{clearInterval(f),clearInterval(C),clearTimeout(S),V.close(),J.close(),b.getTracks().forEach(he=>he.stop())},S=setTimeout(()=>{a(),e(o)},A);let b=c.captureStream(),V=new RTCPeerConnection({}),J=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});V.addEventListener("icecandidate",he=>J.addIceCandidate(he.candidate)),J.addEventListener("icecandidate",he=>V.addIceCandidate(he.candidate)),V.addTrack(b.getVideoTracks()[0],b);let cA=yield V.createOffer();yield V.setLocalDescription(cA),yield J.setRemoteDescription(cA);let CA=yield J.createAnswer(),vA=Zb.default.parse(CA.sdp),$A=vA.media[0].rtp.findIndex(he=>he.codec==="H264");vA.media[0].rtp=[vA.media[0].rtp[$A]],vA.media[0].fmtp=vA.media[0].fmtp.filter(he=>he.payload===vA.media[0].rtp[0].payload),vA.media[0].rtcpFb&&(vA.media[0].rtcpFb=vA.media[0].rtcpFb.filter(he=>he.payload===vA.media[0].rtp[0].payload)),CA.sdp=Zb.default.write(vA),yield J.setLocalDescription(CA),yield V.setRemoteDescription(CA),f=setInterval(()=>jA(null,null,function*(){o.encode&&o.decode&&(a(),e(o));let[he,Oe]=yield Promise.all([V.getSenders()[0].getStats(),J.getReceivers()[0].getStats()]);o.encode||he.forEach(Se=>{Se.type==="outbound-rtp"&&(Se.mediaType===VA.VIDEO||Se.kind===VA.VIDEO)&&Se.bytesSent>0&&(o.encode=!0)}),o.decode||Oe.forEach(Se=>{Se.type==="inbound-rtp"&&(Se.mediaType===VA.VIDEO||Se.kind===VA.VIDEO)&&Se.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(MC)),e)),ik)})}var KE=null,ok=(A,e,o)=>{location.protocol==="http:"&&!wp&&(A[e]=()=>{throw new oi({code:lt.INVALID_OPERATION,message:gc.NOT_SUPPORTED_HTTP})})},lM=function(A){return!(A.type!=="candidate-pair"||!A.nominated||A.state!=="in-progress"&&A.state!=="succeeded")&&!(wr(A.selected)&&!A.selected)};function jE(){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 sk(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function nk(){let A={isSupported:!1},e=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let o=0;o=86,Gw="RTCRtpScriptTransform"in window,lk=vC&&(Up||Gw),ry=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(A=>A in window).length>0};function bw(){let A={AudioDecoder:!1,AudioEncoder:!1,VideoDecoder:!1,VideoEncoder:!1,ImageDecoder:!1};return xe(window.AudioDecoder)||(A.AudioDecoder=!0),xe(window.AudioEncoder)||(A.AudioEncoder=!0),xe(window.VideoDecoder)||(A.VideoDecoder=!0),xe(window.VideoEncoder)||(A.VideoEncoder=!0),xe(window.ImageDecoder)||(A.ImageDecoder=!0),A}function Xx(){return"mediaSession"in navigator&&!xe(navigator.mediaSession.setActionHandler)}function ay(){return!xe(window.WebTransport)}function dM(){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 $x(){let A={browser:"".concat(zB.name,"/").concat(zB.version),os:Il(),displayResolution:jE(),isScreenShareSupported:Lp(),isWebRTCSupported:ry(),isGetUserMediaSupported:sk(),isWebAudioSupported:nk(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:bw(),isMediaSessionSupported:Xx(),isWebTransportSupported:ay()};return navigator.userAgent.includes("miniProgram")&&(A.browser="mini/".concat(A.browser)),A}var Ik="checkResult";function uk(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30;WA.setItem(Ik+A,{ua:navigator.userAgent,checkResult:Bs})}function Ek(A){nu();let e=WA.getItem(Ik+A);e&&e.ua===navigator.userAgent&&e.checkResult&&function(o,a){return!!xE(o)&&Object.keys(a).every(c=>c in o)}(e.checkResult.detail,Bs.detail)&&(Bs=e.checkResult),tk(A)}function Fp(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var iQ="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function A2(A){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[A]}var e2=!1;function CM(){return jA(this,null,function*(){var A;try{if(e2||(A=navigator?.mediaCapabilities)==null||!A.encodingInfo)return;let e=Tp(),o=Hl();if(e===0||o===0)return;e2=!0;let a=["H264","VP8","VP9","AV1","H265"],[c,d]=yield Promise.all([dk(a),Ck(a)]);c&&Object.keys(c).forEach(S=>{let b=A2(S.toLowerCase());Ai.addEnum({key:513707,value:+"".concat(b).concat(+c[S].supported).concat(+c[S].powerEfficient).concat(e).concat(o),useUV:!1})}),d&&Object.keys(d).forEach(S=>{let b=A2(S.toLowerCase());Ai.addEnum({key:514713,value:+"".concat(b).concat(+d[S].supported).concat(+d[S].powerEfficient).concat(e).concat(o),useUV:!1})});let{sender:C,receiver:f}=t2();Ai.addEnum({key:513708,value:+"".concat(e).concat(o).concat(+C.high),useUV:!1}),Ai.addEnum({key:513709,value:+"".concat(e).concat(o).concat(+C.main),useUV:!1}),Ai.addEnum({key:514714,value:+"".concat(e).concat(o).concat(+f.high),useUV:!1}),Ai.addEnum({key:514715,value:+"".concat(e).concat(o).concat(+f.main),useUV:!1})}catch(e){QA.info("detectVideoCodecCapabilities failed",e)}})}function dk(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 jA(this,null,function*(){let d={};try{for(let C of A){let f=yield navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:"video/".concat(C),width:e,height:o,bitrate:c,framerate:a}});d[C]=f}}catch{}return d})}function Ck(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 jA(this,null,function*(){let d={};try{for(let C of A){let f=yield navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:"video/".concat(C),width:e,height:o,bitrate:c,framerate:a}});d[C]=f}}catch{}return d})}function t2(){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 bq=ac(Jl(),1),hM=Symbol("instance"),BM=Symbol("cacheResult"),RC=class{constructor(A,e,o){this.oldState=A,this.newState=e,this.action=o,this.aborted=!1}abort(A){this.aborted=!0,Op.call(A,this.oldState,new Error("action '".concat(this.action,"' aborted")))}toString(){return"".concat(this.action,"ing")}},kw=class extends Error{constructor(A,e,o){super(e),this.state=A,this.message=e,this.cause=o}},QM=new Map;function cc(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=QM.get(a)||[];QM.has(a)||QM.set(a,S),S.push({from:A,to:e,action:C})}let f=d.value;d.value=function(){let S=this;for(var b=arguments.length,V=new Array(b),J=0;J{if(o.fail&&o.fail.call(this,Se),o.sync){if(o.ignoreError)return Se;throw Se}return o.ignoreError?Promise.resolve(Se):Promise.reject(Se)};if(cA)return CA(cA);let vA=S.state,$A=new RC(vA,e,C);Op.call(S,$A);let he=Se=>{var fi;return S[BM]=Se,$A.aborted||(Op.call(S,e),(fi=o.success)===null||fi===void 0||fi.call(this,S[BM])),Se},Oe=Se=>(Op.call(S,vA,Se),CA(Se));try{let Se=f.apply(this,V);return function(fi){return typeof fi=="object"&&fi&&"then"in fi}(Se)?Se.then(he).catch(Oe):o.sync?he(Se):Promise.resolve(he(Se))}catch(Se){return Oe(new kw(S._state,"".concat(S.name," ").concat(C," from ").concat(A," to ").concat(e," failed: ").concat(Se),Se instanceof Error?Se:new Error(String(Se))))}}}}var Lw=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 Op(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 LC extends bq.default{constructor(e,o,a){super(),this.name=e,this.groupName=o,this._state=LC.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[hM];c?this.name=c.name+"-"+c.count++:a[hM]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){let e=Object.getPrototypeOf(this),o=QM.get(e)||[],a=new Set,c=[],d=[],C=new Set,f=Object.getPrototypeOf(e);QM.has(f)&&(f.stateDiagram.forEach(b=>a.add(b)),f.allStates.forEach(b=>C.add(b))),o.forEach(b=>{let{from:V,to:J,action:cA}=b;typeof V=="string"?c.push({from:V,to:J,action:cA}):V.length?V.forEach(CA=>{c.push({from:CA,to:J,action:cA})}):d.push({to:J,action:cA})}),c.forEach(b=>{let{from:V,to:J,action:cA}=b;C.add(V),C.add(J),C.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(b=>{let{to:V,action:J}=b;a.add("".concat(J,"ing --> ").concat(V," : ").concat(J," 🟢")),C.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:C}}),S}static get(e){let o;return typeof e=="string"?(o=LC.instances.get(e),o||LC.instances.set(e,o=new LC(e,void 0,Object.create(LC.prototype)))):(o=LC.instances2.get(e),o||LC.instances2.set(e,o=new LC(e.constructor.name,void 0,Object.create(LC.prototype)))),o}static getState(e){var o;return(o=LC.get(e))===null||o===void 0?void 0:o.state}updateDevTools(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Lw(LC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},e))}get state(){return this._state}set state(e){Op.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 Uw=typeof window<"u",hk=Uw&&window.requestIdleCallback||function(A){let e=Date.now();return setTimeout(()=>{A({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-e))})},1e3)},dl=Uw&&window.cancelIdleCallback||function(A){clearTimeout(A)},Pp=Uw&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),gy=class nE{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=pi(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=Bo(pi({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,nE.isBreakLoop(e)},e.delay)}static intervalInWorker(e){nE.sharedWorker||(nE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` + const timers = new Map(); + self.onmessage = function(e) { + const { taskId, delay, type } = e.data; + if (type === 'start') { + timers.set(taskId, setInterval(() => { + self.postMessage({ type: 'tick', taskId }); + }, delay)); + } else if (type === 'stop') { + clearInterval(timers.get(taskId)); + timers.delete(taskId); + } + }; + `],{type:"application/javascript"}))),nE.sharedWorker.onmessage=o=>{var a;if(o.data.type==="tick"){let c=nE.workerTasks.get(o.data.taskId);c&&(nE.isBreakLoop(c)?((a=nE.sharedWorker)==null||a.postMessage({type:"stop",taskId:c.taskID}),nE.workerTasks.delete(c.taskID)):(c.callback(),c.loopCount+=1))}}),nE.workerTasks.set(e.taskID,e),nE.sharedWorker.postMessage({taskId:e.taskID,delay:e.delay,type:"start"})}static timeout(e){let o=()=>{if(e.callback(),e.loopCount+=1,!nE.isBreakLoop(e))return e.timeoutID=setTimeout(o,e.delay)};return e.timeoutID=setTimeout(o,e.delay)}static ric(e){let o,a=bo(),c=()=>{if(o=bo()-a,o>=e.delay&&(a=bo()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),!nE.isBreakLoop(e))return e.ricID=hk(c,{timeout:e.delay})};return e.ricID=hk(c,{timeout:e.delay})}static raf(e){let o,a=bo(),c=()=>document.hidden&&e.backgroundTask?(o=bo()-a,a=bo(),e.callback(),e.loopCount+=1,nE.isBreakLoop(e)?void 0:e.timeoutID=setTimeout(c,e.delay-Math.floor(o%e.delay))):(o=bo()-a,o>=e.delay&&(a=bo()-Math.floor(o%e.delay),e.callback(),e.loopCount+=1),nE.isBreakLoop(e)?void 0:e.rafID=requestAnimationFrame(c));if(e.rafID=requestAnimationFrame(c),e.backgroundTask){let d=()=>{if(document.hidden){let C=bo()-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&&Pp&&Pp(c),d&&dl(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(gy,"taskMap",new Map),Y(gy,"currentTaskID",1),Y(gy,"sharedWorker",null),Y(gy,"workerTasks",new Map);var _r=gy,mo={LOAD_START:VA.LOADSTART,LOADED_DATA:VA.LOADEDDATA,LOADED_META_DATA:VA.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:VA.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:VA.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:VA.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"},Bk={};bh(Bk,{create:()=>WE,remove:()=>kn});var xh=new WeakMap;function WE(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 on=new class{constructor(){Y(this,"_roomIdMap",new Map),Y(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:kd,env:FB.QCLOUD,browserVersion:zB.name+zB.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){wp||!QA.isAbleToUpload||this._configs.env===FB.QCLOUD&&this.uploadEventToKibana(Bo(pi({},A),{result:"success"}))}logFailedEvent(A){if(wp||!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||lt.UNKNOWN};this._configs.env===FB.QCLOUD&&this.uploadEventToKibana(Bo(pi({},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:JP(),sdkAppId:this._configs.sdkAppId,userId:o||this._configs.userId,version:kd,log:e};a&&(c.errorInfo=a.message,a.stack&&(c.errorInfo+=` +`.concat(a.stack)));let d=TA.enable?JB(c,2002,Number(this._configs.sdkAppId)):JSON.stringify(c);this.sendRequest(kf(this._configs.sdkAppId,RI.LOG),d)}sendRequest(A,e){setTimeout(()=>HB({url:A,body:e,priority:"low"}).catch(()=>{}),2e3)}},wC=new WeakMap;function Yh(A){let{settings:e={retries:5,timeout:2e3},onError:o,onRetrying:a,onRetryFailed:c}=A;return function(d,C,f){let S=JS({retryFunction:f.value,settings:e,onError(b){let{error:V,retry:J,reject:cA,retryFuncArgs:CA}=b;var vA;o?o.call(this,V,()=>{var $A;($A=wC.get(d))!=null&&$A.has(C)?J():cA(V)},cA,CA):(vA=wC.get(d))!=null&&vA.has(C)?J():cA(V)},onRetrying(b,V){var J;fp(a)&&a.call(this,b,V),(J=wC.get(d))!=null&&J.has(C)&&(wC.get(d).get(C).stopRetry=V)},onRetryFailed:c});return f.value=function(){let b=wC.get(d);for(var V=arguments.length,J=new Array(V),cA=0;cA{var CA;return(CA=wC.get(d))==null?void 0:CA.delete(C)})},f}}function Fw(A){let{fnName:e,callback:o,validateArgs:a=!0}=A;return function(c,d,C){let f=C.value;return C.value=function(){for(var S,b,V=arguments.length,J=new Array(V),cA=0;cAOe===he)){$A=!1;break}}$A&&(o&&o.apply(this,J),CA&&CA(),(b=wC.get(c))==null||b.delete(e))}return f.apply(this,J)},C}}var _C=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=hp,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 jA(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=Zo({key:So.PLAY_FAILED,data:{media:this.kind,error:A}});if(this._log.warn(A),e.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new oi({code:lt.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&&!Rp?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(VA.ENDED),this._interval>0&&_r.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():Ux?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 WE(this.element,this.element).add(VA.PLAYING,A).add(VA.ENDED,A).add(VA.PAUSE,A).add(VA.ERROR,A).add(VA.LOADSTART,A).add(VA.LOADEDDATA,A).add(VA.LOADEDMETADATA,A)}}bindTrackEvents(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.track;if(A){let e=this.handleTrackEvent.bind(this);Bk?.create(A,A).add(VA.ENDED,e).add(VA.MUTE,e).add(VA.UNMUTE,e),A.readyState===VA.ENDED&&this.handleTrackEvent({type:VA.ENDED}),A.muted&&this.handleTrackEvent({type:VA.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),U.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(),U.off(nA.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(A){switch(A.type){case VA.PLAYING:mi()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info("".concat(this.kind," player is playing")),this.handlePlaying(VA.PLAYING),this._interval&&(_r.clearTask(this._interval),this._interval=-1);break;case VA.ENDED:this._log.info("".concat(this.kind," player is ended")),this.handleStopped(VA.ENDED);break;case VA.PAUSE:this._log.info("".concat(this.kind," player is paused")),this.handlePaused(VA.PAUSE);break;case VA.ERROR:if(this.element&&this.element.error){this.handlePaused(VA.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)),on.uploadEvent({log:"stat-".concat(this.kind,"-").concat(Va.PLAYER_ERROR,"-").concat(e,"-").concat(navigator.userAgent),error:this.element.error}),Lb||kb?this.emit(mo.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case VA.LOADEDDATA:this.kind===VA.VIDEO&&this.emit(mo.LOADED_DATA);break;case VA.LOADEDMETADATA:this.kind===VA.VIDEO&&this.emit(mo.LOADED_META_DATA);break;case VA.LOADSTART:this.emit(mo.LOAD_START)}}replayByRecreateMediaStream(A){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),on.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),Ai.addSuccessEvent({key:this.kind===VA.AUDIO?506700:516700})}).catch(()=>{var e;this._log.error("replayByRecreateMediaStream failed"),on.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),Ai.addFailedEvent({key:this.kind===VA.AUDIO?506700:516700,error:(e=this.element)==null?void 0:e.error}),this.emit(mo.ERROR,A)})}doReplayByRecreateMediaStream(A){return this._log.warn("delay ".concat(A,"ms to recreate mediaStream")),new Promise((e,o)=>{SC(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)}),SC(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 jA(this,null,function*(){let e=A.type;switch(this.options.enableLogTrackState&&this._log[e===VA.UNMUTE?"info":"warn"]("track ".concat(e)),e){case VA.ENDED:this.handleStopped(VA.ENDED);break;case VA.MUTE:this.handlePaused(VA.MUTE);break;case VA.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(VA.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(_C,"PlayerEvent",mo),di([Yh({settings:{retries:2,timeout:0},onError(A,e,o,a){a[0]=(a[0]||1e3)+1e3,e()}})],_C.prototype,"doReplayByRecreateMediaStream"),di([cc([],"PLAYING",{sync:!0,success(A){this.emit(mo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:A})}})],_C.prototype,"handlePlaying"),di([cc("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(A){this.emit(mo.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:A})}})],_C.prototype,"handlePaused"),di([cc([],"STOPPED",{sync:!0,success(A){this.emit(mo.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:A})}})],_C.prototype,"handleStopped");var Vh="trtc_autoplay",Qk="".concat(Vh,"_mask"),pM="".concat(Vh,"_wrapper"),mM="".concat(Vh,"_header"),fM="".concat(Vh,"_content"),Ow="".concat(Vh,"_action_wrapper"),AA="".concat(Vh,"_question"),Z="".concat(Vh,"_collapse"),hA="".concat(Vh,"_action_confirm"),bA="".concat(Vh,"_detail"),Ie="#2473E8",ye="dialog",Me="".concat(ye,"-show"),ke="".concat(ye,"-1"),et="".concat(ye,"-2"),Ye=!1,Tt=!1,mi=()=>Tt,wi="".concat(kh,"/").concat(Ud()?"zh-cn":"en","/tutorial-21-advanced-auto-play-policy.html"),ys="
").concat(Ud()?"其他方案?":"Any other solution?",""),Tn="".concat(Ud()?"浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。".concat(ys):"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(ys)),ta=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),Ud()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!Ye){let A=document.createElement("style");A.innerHTML=".".concat(Qk,"{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(Qk," div:not(.").concat(Ow,"){display:block !important;}.").concat(pM,"{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.").concat(pM," a{color:").concat(Ie,";}.").concat(mM,"{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.").concat(fM,"{margin:8px 0;}.").concat(Ow,"{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(fM,",.").concat(AA,"{font-size:14px;}@media screen and (max-width:750px){.").concat(pM,"{width:80vw;}}"),document.head.appendChild(A),Ye=!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=Ud()?"恢复播放":"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(Ud()?"详情 >":"Detail >"),a.onclick=this.onCollapseClick.bind(this);let c=A.content.firstChild,d=c.querySelector(".".concat(Ow));return d.appendChild(a),d.appendChild(o),d.appendChild(e),c}addDiaLog(){mi()||(Tt=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(".".concat(pM)).onclick=A=>A.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",QA.info("show autoplay dialog"),on.uploadEvent({log:Me}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,Tt=!1),Fc=null}onConfirm(){QA.warn("confirm clicked, try resume stream"),U.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||on.uploadEvent({log:ke}),this._isCollapseClicked=!0}onQuestionClick(){window.open(wi,"_blank"),this._isQuestionClicked||on.uploadEvent({log:et}),this._isQuestionClicked=!0}},Fc=null;function TC(){Fc||(Fc=new ta)}var Ei,Mo=class f6 extends _C{constructor(e){super(e,VA.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,xe(e.viewMirror)||(this.viewMirror=e.viewMirror),xe(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(VA.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,Ja&&(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(mo.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=hp,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(VA.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(VA.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(VA.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(VA.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===VA.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(mo.ENTER_FULL_SCREEN)):(this._log.info("leave fullscreen"),this.emit(mo.LEAVE_FULL_SCREEN))}handleVolumeChange(){var e;(this.isPictureInPicture()||this.isFullscreen())&&this.emit(mo.VOLUME_CHANGE,{muted:(e=this.element)==null?void 0:e.muted})}handleElementEvent(e){var o,a,c,d,C,f;if(this.mode===2)return;super.handleElementEvent(e);let S=e.type,b=this.isPictureInPicture(),V=this.isFullscreen(),J=e.isTrusted&&(b&&hg||V);if(S===VA.PLAYING&&J&&!this._isResettingSrcObject&&(this._log.warn("user resume in ".concat(V?"fullscreen":"pip")),this.emit(mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),S===VA.PAUSE&&(J&&(this._log.warn("user pause in ".concat(V?"fullscreen":"pip")),this.emit(mo.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)),SC(500).then(()=>{var cA;(cA=this.container)!=null&&cA.isConnected&&(this._pausedRetryCount=hp,this._log.info("view container ".concat(this.container.id," is in dom, reset pausedRetryCount")))})),this._pausedRetryCount>0&&!mi()&&!this.isPausedByUserCall&&!J&&(this._log.info("[".concat(hp-this._pausedRetryCount+1,"/").concat(hp,"] ").concat(this.kind," player auto resume when paused")),this.doResume(),this._pausedRetryCount--),Ag&&!J&&(this._interval=_r.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===VA.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=cA.replace("scaleX(-1)",""):S===VA.LEAVE_PICTURE_IN_PICTURE&&!cA.includes("scaleX")&&(this.element.style.transform="".concat(cA," scaleX(-1)"))}S===VA.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=((f=this.element)==null?void 0:f.videoWidth)||0,this.emit(mo.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height})),S===VA.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(mo.LEAVE_PICTURE_IN_PICTURE)),S===VA.ENTER_PICTURE_IN_PICTURE&&this.emit(mo.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Ja&&Wf&&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||!hg&&!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,f=1;if(this._useWrapper){let S=parseInt(d.zIndex,10);isNaN(S)||(f=S+1)}c.style.cssText=this._useWrapper?"grid-area:1/1;z-index:".concat(f,";width:100%;height:100%;object-fit:").concat(C,";"):"position:absolute;top:0;left:0;width:100%;height:100%;object-fit:".concat(C,";"),c.onload=()=>jA(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),HS()&&Od<=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&&(HS()&&Od<=17&&this.elementToRender&&(this.elementToRender.style.visibility=""),this.posterImg.remove(),URL.revokeObjectURL(this.posterImg.src),!this._useWrapper&&this.container&&!xe(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 jA(this,null,function*(){MI(f6.prototype,this,"pause").call(this),!this.isPictureInPicture()&&!this.hasPoster&&(Wf||e&&(er||hg))&&(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&&Wf&&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(VA.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(xe(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(mo.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(Fp()&&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 jA(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(Ag&&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 jA(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 jA(this,null,function*(){this.isFullscreen()?yield this.exitFullscreen():yield this.enterFullscreen()})}enterPictureInPicture(){return jA(this,null,function*(){this.enterPIPPromise=this._enterPictureInPicture();try{return yield this.enterPIPPromise}finally{delete this.enterPIPPromise}})}_enterPictureInPicture(){return jA(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 jA(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=hp,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 jA(this,null,function*(){this.isPictureInPicture()?yield this.exitPictureInPicture():yield this.enterPictureInPicture()})}};function Yg(A,e){return jA(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"?Ei=AudioContext:typeof webkitAudioContext<"u"?Ei=webkitAudioContext:typeof mozAudioContext<"u"&&(Ei=mozAudioContext);var Ln,ru=1500,xd=-1,xp=0,zE=-1,TI=!1,i2=0,Pw=-1,pk=-1;(function A(){try{if(Ln)return;(Ln=new Ei({sampleRate:48e3})).onstatechange=()=>{QA.info("context state: ".concat(Ln.state).concat(Ln.state!=="running"?" visibilityState: ".concat(document.visibilityState):"")),xw()},clearTimeout(xd)}catch(e){QA.error("initAudioContext failed: ".concat(e," typeof AudioContextClass: ").concat(typeof Ei)),xd=setTimeout(A,1e3)}})();var xw=()=>{Ln.state==="suspended"?(xp=bo(),zE===-1&&(zE=setTimeout(()=>{Ln.state==="suspended"&&(TI=!0,U.emit("155",{isSuspended:!0}))},ru)),mk(),document.addEventListener("click",xw)):Ln.state==="interrupted"?mk():(xp&&(Ai.addNumber({key:507800,value:bo()-xp,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),xp=0),zE!==-1&&(clearTimeout(zE),zE=-1,TI&&(TI=!1,U.emit("155",{isSuspended:!1}))),document.removeEventListener("visibilitychange",xw),document.removeEventListener("click",xw))},kq=0,Lq=-1;function mk(){return new Promise((A,e)=>{if(Ln.state==="running")return A();Date.now()-kq<1e3?(clearTimeout(Lq),Lq=setTimeout(()=>{kq=Date.now(),Ln.resume().then(A,e)},1e3)):(clearTimeout(Lq),kq=Date.now(),Ln.resume().then(A,e))}).catch(A=>{QA.warn("context resume failed: ".concat(A)),document.addEventListener("visibilitychange",xw)})}document.addEventListener("click",xw);var NI=A=>Ln,GI=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(),Ai.addSuccessEvent({key:502701})}catch(a){QA.error(a),Ai.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(),Ai.addSuccessEvent({key:502702})}catch(e){QA.error(e),Ai.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}},eAA=class extends GI{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]}},xW=new WeakMap;function o2(A){try{let e=xW.get(A);if(e)return e;let o=NI();if(A instanceof HTMLAudioElement)e=o.createMediaElementSource(A);else{if(!(A instanceof MediaStreamTrack))return A;e=o.createMediaStreamSource(new MediaStream([A]))}return xW.set(A,e),e}catch(e){if(!(er&&e instanceof Error&&e.name==="NotSupportedError"))throw e;QA.warn(e)}}var s2=class Wp{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,U.on(nA.AUDIO_LEVEL_INTERVAL,this.handleAudioLevelInterval,this)}static get isRunning(){return Date.now()-Wp.lastMessageTime<2e3}get node(){return this._audioWorkletNode||this._scriptProcessorNode}preload(){if(!Wp.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);';Wp.workletReady=Yg(Wp.audioContext,URL.createObjectURL(new Blob([e],{type:"application/javascript"})))}return Wp.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(Wp.audioContext,"volume-meter");let e=!1;this._audioWorkletNode.port.onmessage=o=>{Wp.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)),on.logFailedEvent({userId:this._log.userId,eventType:Va.LOAD_WORKLET,error:e}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=NI().createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=e=>{Wp.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()}}},n2=YW,iAA=ac(Jl(),1),JW=A=>e=>e.deviceId===A,Uq=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&&fk(this.devices[0])||e&&(o.forEach(a=>{if(a.deviceId&&!this.devices.find(JW(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(JW(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)}},oAA=class extends iAA.EventEmitter{constructor(){super(),Y(this,"audioInputs",new Uq(VA.AUDIO,"Input")),Y(this,"videoInputs",new Uq(VA.VIDEO,"Input")),Y(this,"audioOutputs",new Uq(VA.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||_r.run("interval",()=>{this.update()},{delay:1e4}))}init(){r2().then(A=>{this.audioInputs.update(A),this.videoInputs.update(A),this.audioOutputs.update(A)})}update(){return jA(this,arguments,function(){var A=this;let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){let o=yield r2(e);return A.audioInputs.update(o,A),A.videoInputs.update(o,A),A.audioOutputs.update(o,A),A}()})}hasBlueTooth(){var A;if(1e3*((A=NI())==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)))}},Oc=L0||k0?null:new oAA;function fk(A){return A.deviceId===A.groupId&&A.groupId===""}function r2(){return jA(this,arguments,function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function*(){if(nu()||!Ak())return[];let e=yield navigator.mediaDevices.enumerateDevices();if(A!==0){let o={audio:!1,video:!1};if(e.forEach(a=>{fk(a)&&(a.kind===VA.AUDIO_INPUT?o.audio=!0:a.kind===VA.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&&mk()}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&&Fq.add("".concat(o.deviceId,"_").concat(o.kind)),o.getCapabilities&&(c.getCapabilities=()=>o.getCapabilities()),c})}()})}function Yp(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Oc.update(A?1:0).then(e=>e.audioInputs.devices)}function Vp(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return Oc.update(A?2:0).then(e=>e.videoInputs.devices)}var HW=!1;function yM(){let A=arguments.length>0&&arguments[0]!==void 0&&arguments[0];return jA(this,null,function*(){return(Ag||hg)&&(A=!1),Oc.update(A?1:0).then(e=>e.audioOutputs.devices)})}var Fq=new Set;function qW(A,e){return jA(this,null,function*(){let o=(yield Yp()).find(a=>a.deviceId===NS);return!e&&o?.groupId===A||o?.groupId===A&&o.label===e})}var a2,sAA=class extends OW{constructor(A){super(),this.log=A,Y(this,"volumeMeter"),Y(this,"volumeMeterAfter3A"),Y(this,"volumeDestination"),Y(this,"analyser",new eAA),this.volumeMeter=new VW({log:this.log}),this.volumeMeterAfter3A=new VW({log:this.log}),this.volumeDestination=new GI,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},Oq=class y6 extends _C{constructor(e){super(e,VA.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 sAA(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((wI==="15.2"||wI==="15.3"||wI==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");let o=a2||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===a2&&(a2=void 0),this.options.enableTimeupdateEvent&&(this.element.ontimeupdate=()=>this.emit(mo.TIME_UPDATE,this.currentTime)),this.bindElementEvents()}play(e){return jA(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(NI().createAnalyser()),function(){jA(this,null,function*(){try{HW||(HW=!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)),zf(wI,"18.7",!0)&&this.bindAutoPlayEvent(),o}return MI(y6.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 jA(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()}},nAA=class extends Oq{setTrack(A){this.track!==A&&(this.unbindTrackEvents(),this.track=A,this.emit(mo.MEDIA_TRACK_CHANGED,A),A&&(this.bindTrackEvents(),this.element&&(this.element.srcObject=new MediaStream([A]))))}},KW=class extends Oq{constructor(A){super(A),Y(this,"_sourceElement"),Y(this,"_output",new GI),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(NI().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(mo.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&&!HS();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(HS()){if(!this.enableVolumeControlInIOS)return;(function(){if(!Ag||pk!==-1)return;let a=()=>{bo()-i2<500||(Ln&&Ln.state==="running"&&Ln.currentTime===Pw&&(QA.warn("context is fake running, auto resume"),Ln.suspend().catch(c=>{QA.warn("context suspend failed: ".concat(c))})),Pw=Ln.currentTime,i2=bo())};pk=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=NI().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(mo.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&&Rp&&(a2=e),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(A)}},Pq=class extends zs{constructor(A){let{userId:e,sdkAppId:o,mediaType:a,room:c,PlayerClass:d=a===1?KW:Mo}=A;var C;super(),Y(this,"id",xA()),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 wk?void 0:this.userId,sdkAppId:o,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof wk}),this.player=new d({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:c?.enableVolumeControlInIOS}),this.player.on(mo.PLAYER_STATE_CHANGED,f=>{if(U.emit(nA.PLAYER_STATE_CHANGED,pi({track:this},f)),this.emit("player-state-changed",f),f.state==="PLAYING"&&this.room){let S=!0;for(let{remoteAudioTrack:b,remoteVideoTrack:V,remoteAuxiliaryTrack:J}of[...this.room.remotePublishedUserMap.values()])if(b.isAvailable&&!b.player.isPlaying||V.isAvailable&&!V.player.isPlaying||J.isAvailable&&!J.player.isPlaying){S=!1;break}S&&mi()&&Fc&&Fc.deleteDialog()}}),this.kind===VA.VIDEO&&(this.player.on(mo.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(mo.LOADED_DATA),U.emit(nA.VIDEO_LOADED_DATA,{track:this})}),this.player.on(mo.LOADED_META_DATA,()=>{this.emitFirstVideoFrameEvent(mo.LOADED_META_DATA)}),this.player.on(mo.MEDIA_TRACK_CHANGED,f=>{var S;(S=this.subVideoPlayerMap)==null||S.forEach(b=>b.setTrack(f))}),this.player.on(mo.RESIZE,f=>{this.emitFirstVideoFrameEvent(mo.RESIZE),this.emit("video-size-changed",pi({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},f))}),this.player.on(mo.FIRST_FRAME_RENDER,f=>{this.emit("first-frame-render",Bo(pi({},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(mo.ERROR,this.onPlayerError.bind(this)),this.player.on(mo.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||QA}get kind(){return this.mediaType===1?VA.AUDIO:VA.VIDEO}get isAudio(){return this.kind===VA.AUDIO}get strMediaType(){return this.mediaType===4?VA.VIDEO:this.mediaType===2?VA.SCREEN:VA.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 jA(this,null,function*(){let o=va(A)?A[0]:A;if(this.isPlayCalled)return this.log.info("play update options: ".concat(JSON.stringify(e))),e&&!xe(e.muted)&&this.setPlayerMute(e.muted),e&&!xe(e.objectFit)&&(this.objectFit=e.objectFit),void(this.player instanceof Mo&&(this.player.setObjectFit(this.objectFit),this.container!==o&&o&&(va(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))),va(A)&&A.length>=1&&(yield this.playSubContainer(A.slice(1),e))));if(e&&!xe(e.muted)?this.setPlayerMute(e.muted):(!this.isRemote||this.kind===VA.VIDEO)&&this.setPlayerMute(!0),e&&!xe(e.objectFit)&&(this.objectFit=e.objectFit),this.player instanceof Mo&&(xe(e?.isLiveStream)||this.player.setLiveMode(e.isLiveStream),this.player.setObjectFit(this.objectFit),e&&!xe(e.poster)&&this.player.setPoster(e.poster)),this.isPlayCalled=!0,o&&(this.container=o,this.player instanceof Mo&&this.player.setContainer(o)),U.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),va(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!==VA.VIDEO||xe(A)||A===this.mirror)return;this.mirror=A;let o=this.player;e&&(o=e);let a=this.manager;if(wr(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 jA(this,null,function*(){if(!this._outputTrack||this.kind===VA.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&&(xe(e.objectFit)||d.setObjectFit(e.objectFit)):this.subVideoPlayerMap.set(c,new Mo({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(fb(this)&&!A?this.jitterBufferDelay:0)),this.subVideoPlayerMap&&this.subVideoPlayerMap.size>0&&this.subVideoPlayerMap.forEach(e=>{e.stop()}),this.container=null)}resume(){return jA(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),U.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){WE(A,A).add(VA.MUTE,this.onTrackMuted).add(VA.UNMUTE,this.onTrackUnmuted).add(VA.ENDED,this.onTrackEnded),A.muted&&this.onTrackMuted(),A.readyState===VA.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 sQ&&pp(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 fb(this)&&this.isAudio&&(e=this.user)!=null&&e.muteState.hasAudio&&(o=this.user)!=null&&o.muteState.audioMuted?void 0:(this.player.stop(fb(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 jA(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((Sp||qB)&&(yield SC(100),(e=this.player)!=null&&e.isPlaying))return;TC()}else document.addEventListener("click",o,!0);U.once(nA.LOCAL_TRACK_CAPTURE_SUCCESS,a=>{let{track:c}=a;c.kind==="audio"&&mi()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&o()}),this.emit("error",A)})}getVideoFrame(){return this.player instanceof Mo?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===mo.RESIZE&&!d&&!C||A===mo.LOADED_META_DATA&&!d&&!C||(A===mo.LOADED_DATA&&!d&&!C&&this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,VB(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"))}};di([cc([],zs.INIT,{sync:!0})],Pq.prototype,"_toInitState");var rAA=Object.prototype.hasOwnProperty,Jp=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(eE(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(rAA.call(A,e))return!1;return!0}return!1},aAA=JS({retryFunction:function(A){return jA(this,null,function*(){let e=function(d){return{audio:gAA(d),video:cAA(d)}}(A);QA.info("getUserMedia with constraints: ".concat(JSON.stringify(e)));let o=[],a=[],c=["label","deviceId","groupId"];if(e.audio&&(o=yield Yp(),QA.info("microphones: ".concat(Fd(o.map(d=>Bo(pi({},d),{groupId:d.groupId.substring(0,8)})),{keysToInclude:c})))),e.video&&(a=yield Vp(),QA.info("cameras: ".concat(Fd(a,{keysToInclude:c}))),!wr(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 zx&&d.getTracks().forEach(C=>{var f;let S=C.getCapabilities();QA.info("".concat(C.kind," capabilities: ").concat(Fd(S,{keysToInclude:ib}))),!xe(A.echoCancellation)&&((f=S.echoCancellation)==null?void 0:f.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&&mk(),d}catch(d){let{message:C}=d;throw d.name==="NotFoundError"&&(A.video&&a&&a.length===0&&(C=Zo({key:So.CAMERA_NOT_FOUND})),A.audio&&o&&o.length===0&&(C=Zo({key:So.MICROPHONE_NOT_FOUND}))),new oi({code:lt.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,(!hg||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&&jW(c[0].microphoneId,!1),c[0].cameraId&&jW(c[0].cameraId,!0)},onRetrying:A=>{QA.warn("getUserMedia NotReadableError observed, retrying [".concat(A,"/3]"))},onRetryFailed:A=>{on.logFailedEvent({eventType:Va.GET_USER_MEDIA_RETRY,error:A})},onRetrySuccess:A=>{on.logSuccessEvent({eventType:Va.GET_USER_MEDIA_RETRY}),on.uploadEvent({log:"stat-".concat(Va.GET_USER_MEDIA_RETRY,"-success-").concat(A)})}});function jW(A,e){return jA(this,null,function*(){let o=(e?yield Vp():yield Yp()).find(a=>a.deviceId===A);o&&Ma(o.getCapabilities)&&QA.warn(Fd(o.getCapabilities(),{keysToInclude:ib}))})}function gAA(A){if(!A.audio)return!1;if(A.useTrueAsConstraint)return!0;let e={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:A.sampleRate};return!Jp(A.microphoneId)&&(e.deviceId=A.useExactDeviceId?{exact:A.microphoneId}:A.microphoneId,A.useDeviceIdOnly)?e:(bn(A.channelCount)&&(e.channelCount=A.channelCount),(wr(A.echoCancellation)||A.echoCancellation==="remote-only"||A.echoCancellation==="all")&&(e.echoCancellation=A.echoCancellation),wr(A.noiseSuppression)&&!A.noiseSuppression&&(e.noiseSuppression=!1),wr(A.autoGainControl)&&!A.autoGainControl&&(e.autoGainControl=!1),!!Jp(e)||e)}function cAA(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&&!Jp(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&&KB&&A.width&&A.height&&A.width*A.height<101376&&(o.width=A.width,o.height=A.height),A.frameRate&&(o.frameRate=A.frameRate),!!Jp(o)||o)}var lAA=aAA;function WW(A){return Hr((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)}})(),uAA=0,ZW=class{constructor(A){Y(this,"log"),Y(this,"isRunning",!1),Y(this,"queue",[]);let e="fq".concat(++uAA);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=pi({},A),d=new Promise((C,f)=>{c.resolve=C,c.reject=f});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()})}},g2=new WeakMap,c2=new WeakMap;function yk(){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=g2.get(this)||new ZW;for(var C=arguments.length,f=new Array(C),S=0;SS.push(cA)),(f=c2.get(this))==null||f.forEach(cA=>cA?.queue.forEach(CA=>S.push(CA))),S.forEach(cA=>{cA.reject(new oi({code:lt.API_CALL_ABORTED,message:A}))}),g2.delete(this),c2.delete(this),c.apply(this,V)},a}}function cy(A,e){return function(o,a,c){let d=c.value,C=f=>A(...f);return c.value=function(){for(var f=arguments.length,S=new Array(f),b=0;bfunction(){let c=A;try{for(var d=arguments.length,C=new Array(d),f=0;f(e?Ai.addSuccessEvent({key:c,cost:bo()-b}):Ai.addSuccessEvent({key:c}),V)).catch(V=>{throw Ai.addFailedEvent({key:c,error:V}),V}):(Ai.addSuccessEvent({key:c}),S)}catch(S){throw Ai.addFailedEvent({key:c,error:S}),S}})}var $W={};function eg(){}bh($W,{Events:()=>lc,Inspect:()=>Iy,LastSink:()=>l2,Sink:()=>Fs,Subscribe:()=>I2,TimeoutError:()=>t4,audit:()=>XAA,bindCallback:()=>kAA,bindNodeCallback:()=>LAA,buffer:()=>yAA,bufferCount:()=>fAA,bufferTime:()=>meA,call:()=>A4,catchError:()=>m4,combineLatest:()=>s4,concat:()=>hAA,concatMap:()=>leA,concatMapTo:()=>IeA,count:()=>OAA,create:()=>cr,debounce:()=>AeA,debounceTime:()=>eeA,defer:()=>n4,delay:()=>feA,deliver:()=>Os,dispose:()=>xq,elementAt:()=>teA,empty:()=>Kq,every:()=>reA,exhaustMap:()=>heA,exhaustMapTo:()=>BeA,expand:()=>DeA,filter:()=>SM,find:()=>ieA,findIndex:()=>oeA,first:()=>seA,fromAnimationFrame:()=>GAA,fromArray:()=>vAA,fromEvent:()=>ga,fromEventPattern:()=>RAA,fromFetch:()=>wAA,fromIterable:()=>_AA,fromPromise:()=>c4,fromReadableStream:()=>NAA,fromReader:()=>TAA,groupBy:()=>QeA,identity:()=>EAA,ignoreElements:()=>VAA,iif:()=>QAA,inspect:()=>e4,interval:()=>g4,last:()=>neA,map:()=>Wq,mapTo:()=>geA,max:()=>PAA,merge:()=>Yq,mergeMap:()=>EeA,mergeMapTo:()=>deA,min:()=>xAA,never:()=>UAA,nothing:()=>eg,of:()=>MAA,pairwise:()=>aeA,pipe:()=>Qa,race:()=>o4,range:()=>bAA,reduce:()=>l4,retry:()=>ReA,scan:()=>E4,setAsapScheduler:()=>SAA,share:()=>Dk,shareReplay:()=>BAA,skip:()=>qAA,skipUntil:()=>KAA,skipWhile:()=>jq,startWith:()=>Vq,subject:()=>oQ,subscribe:()=>Cl,sum:()=>YAA,switchMap:()=>E2,switchMapTo:()=>C2,take:()=>Vw,takeLast:()=>HAA,takeUntil:()=>oE,takeWhile:()=>JAA,tap:()=>zq,throttle:()=>zAA,throwError:()=>FAA,timeInterval:()=>peA,timeout:()=>veA,timer:()=>Hq,toPromise:()=>SeA,toReadableStream:()=>MeA,withLatestFrom:()=>mAA,zip:()=>pAA});var A4=A=>A(),EAA=A=>A;function xq(){this.dispose()}var e4=()=>typeof __FASTRX_DEVTOOLS__<"u",dAA=1,Iy=class extends Function{toString(){return"".concat(this.name,"(").concat(this.args.length?[...this.args].join(", "):"",")")}subscribe(A){let e=new CAA(A,this,this.streamId++);return lc.subscribe({id:this.id,end:!1},{nodeId:e.sourceId,streamId:e.id}),this(e),e}},l2=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=eg,this.error=eg,this.next=eg,this.dispose=eg,this.subscribe=eg,this.doDefer()}subscribe(A){return A instanceof Iy?A.subscribe(this):A(this),this}get bindSubscribe(){return A=>this.subscribe(A)}doDefer(){this.defers.forEach(A4),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}},Fs=class extends l2{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)}},I2=class extends l2{constructor(A){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:eg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:eg,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:eg;if(super(),this._next=e,this._error=o,this._complete=a,this.then=eg,A instanceof Iy){let c={toString:()=>"subscribe",id:0,source:A};this.defer(()=>{lc.defer(c,0)}),lc.create(c),lc.pipe(c),this.sourceId=c.id,this.subscribe(A),lc.subscribe({id:c.id,end:!0}),e==eg?this._next=d=>lc.next(c,0,d):this.next=d=>{lc.next(c,0,d),e(d)},a==eg?this._complete=()=>lc.complete(c,0):this.complete=()=>{this.dispose(),lc.complete(c,0),a()},o==eg?this._error=d=>lc.complete(c,0,d):this.error=d=>{this.dispose(),lc.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 Qa(A){for(var e=arguments.length,o=new Array(e>1?e-1:0),a=1;ad(c),A)}function cr(A,e,o){if(e4()){let a=Object.defineProperties(Object.setPrototypeOf(A,Iy.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}});lc.create(a);for(let c=0;c{if(d instanceof Iy){let C=cr(f=>{let S=new A(f,...a);S.sourceId=C.id,S.subscribe(d)},e,arguments);return C.source=d,lc.pipe(C),C}return C=>d(new A(C,...a))}}}function uy(A,e){window.postMessage({source:"fastrx-devtools-backend",payload:{event:A,payload:e}})}var CAA=class extends Fs{constructor(A,e,o){super(A),this.source=e,this.id=o,this.sourceId=A.sourceId,this.defer(()=>{lc.defer(this.source,this.id)})}next(A){lc.next(this.source,this.id,A),this.sink.next(A)}complete(){lc.complete(this.source,this.id),this.sink.complete()}error(A){lc.complete(this.source,this.id,A),this.sink.error(A)}},lc={addSource(A,e){uy("addSource",{id:A.id,name:A.toString(),source:{id:e.id,name:e.toString()}})},next(A,e,o){uy("next",{id:A.id,streamId:e,data:o&&o.toString()})},subscribe(A,e){let{id:o,end:a}=A;uy("subscribe",{id:o,end:a,sink:{nodeId:e&&e.nodeId,streamId:e&&e.streamId}})},complete(A,e,o){uy("complete",{id:A.id,streamId:e,err:o?o.toString():null})},defer(A,e){uy("defer",{id:A.id,streamId:e})},pipe(A){uy("pipe",{name:A.toString(),id:A.id,source:{id:A.source.id,name:A.source.toString()}})},update(A){uy("update",{id:A.id,name:A.toString()})},create(A){A.id||(A.id=dAA++),uy("create",{name:A.toString(),id:A.id})}},t4=class extends Error{constructor(A){super("timeout after ".concat(A,"ms")),this.timeout=A}},i4=class extends l2{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 Dk(){return A=>{let e=new i4(A);if(A instanceof Iy){let o=cr(a=>{e.add(a)},"share",arguments);return e.sourceId=o.id,o.source=A,lc.pipe(o),o}return cr(e.add.bind(e),"share",arguments)}}function Yq(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=new Fs(a),d=e.length;c.complete=()=>{--d===0&&a.complete()},e.forEach(c.bindSubscribe)},"merge",arguments)}function o4(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=new Map;e.forEach(d=>{let C=new Fs(a);c.set(d,C),C.complete=()=>{c.delete(d),c.size===0?a.complete():C.dispose()},C.next=f=>{c.delete(d),c.forEach(S=>S.dispose()),C.resetNext(),C.resetComplete(),C.next(f)}}),e.forEach(d=>c.get(d).subscribe(d))},"race",arguments)}function hAA(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=0,d=e.length,C=new Fs(a);C.complete=()=>{c{let o=new i4(e),a=[];return o.next=function(c){a.push(c),a.length>A&&a.shift(),this.sinks.forEach(d=>d.next(c))},cr(c=>{c.defer(()=>o.remove(c)),a.forEach(d=>c.next(d)),o.add(c)},"shareReplay",arguments)}}function QAA(A,e,o){return cr(a=>A()?e(a):o(a),"iif",arguments)}function s4(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=e.length,d=c,C=c,f=new Array(c),S=()=>{--C===0&&a.complete()};e.forEach((b,V)=>{let J=new Fs(a);J.next=cA=>{d--,J.next=CA=>{f[V]=CA,d===0&&a.next(f)},J.next(cA)},J.complete=S,J.subscribe(b)})},"combineLatest",arguments)}function pAA(){for(var A=arguments.length,e=new Array(A),o=0;o{let c=e.length,d=c,C=new Array(c),f=()=>{--d===0&&a.complete()};e.forEach((S,b)=>{let V=new Fs(a),J=[];C[b]=J,V.next=cA=>{J.push(cA),C.every(CA=>CA.length)&&a.next(C.map(CA=>CA.shift()))},V.complete=f,V.subscribe(S)})},"zip",arguments)}function Vq(){for(var A=arguments.length,e=new Array(A),o=0;ocr(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=eg,e.subscribe(s4(...a))}next(A){this.buffer&&this.sink.next([A,...this.buffer])}},"withLatestFrom"),fAA=Os(class extends Fs{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"),yAA=Os(class extends Fs{constructor(A,e){super(A),this.buffer=[];let o=new Fs(A);o.next=a=>{A.next(this.buffer),this.buffer=[]},o.complete=eg,o.subscribe(e)}next(A){this.buffer.push(A)}complete(){this.buffer.length&&this.sink.next(this.buffer),super.complete()}},"buffer"),DAA=function(A,e,o,a){return new(o||(o=Promise))(function(c,d){function C(b){try{S(a.next(b))}catch(V){d(V)}}function f(b){try{S(a.throw(b))}catch(V){d(V)}}function S(b){b.done?c(b.value):function(V){return V instanceof o?V:new o(function(J){J(V)})}(b.value).then(C,f)}S((a=a.apply(A,[])).next())})};function oQ(A){let e=arguments,o=Dk()(cr(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=eg,o.complete=eg,o.error=eg,o}function n4(A){return cr(e=>e.subscribe(A()),"defer",arguments)}var Yw={promise:A=>{Promise.resolve().then(A)},setImmediate:typeof setImmediate<"u"?A=>setImmediate(A):null,setTimeout:A=>setTimeout(A,0)},Jq=typeof Promise<"u"?Yw.promise:Yw.setImmediate?Yw.setImmediate:Yw.setTimeout,r4=A=>e=>{Jq(()=>A(e))},SAA=A=>{typeof A=="function"?Jq=A:Yw[A]&&(Jq=Yw[A])},a4=A=>r4(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 Hq(A,e){return cr(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 u2(A,e){return o=>{let a=c=>o.next(c);o.defer(()=>e(a)),A(a)}}function RAA(A,e){return cr(u2(A,e),"fromEventPattern",arguments)}function ga(A,e){if("on"in A&&"off"in A)return cr(u2(o=>A.on(e,o),o=>A.off(e,o)),"fromEvent",arguments);if("addListener"in A&&"removeListener"in A)return cr(u2(o=>A.addListener(e,o),o=>A.removeListener(e,o)),"fromEvent",arguments);if("addEventListener"in A)return cr(u2(o=>A.addEventListener(e,o),o=>A.removeEventListener(e,o)),"fromEvent",arguments);throw"target is not a EventDispachter"}function c4(A){return cr(e=>{A.then(o=>{e.next(o),e.complete()},e.error.bind(e))},"fromPromise",arguments)}function wAA(A,e){return cr(n4(()=>c4(fetch(A,e))),"fromFetch",arguments)}function _AA(A){return cr(r4(e=>{try{for(let o of A){if(e.disposed)return;e.next(o)}e.complete()}catch(o){e.error(o)}}),"fromIterable",arguments)}function TAA(A){let e=o=>DAA(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 cr(o=>{e(o)},"fromReader",arguments)}function NAA(A){return cr(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 GAA(){return cr(A=>{let e=requestAnimationFrame(function o(a){A.disposed||(A.next(a),e=requestAnimationFrame(o))});A.defer(()=>cancelAnimationFrame(e))},"fromAnimationFrame",arguments)}function bAA(A,e){return cr(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(f=>(d.next(f),d.complete()));A.apply(e,C)},"bindCallback",arguments)}function LAA(A,e){for(var o=arguments.length,a=new Array(o>2?o-2:0),c=2;c{let C=a.concat((f,S)=>f?d.error(f):(d.next(S),d.complete()));A.apply(e,C)},"bindNodeCallback",arguments)}function UAA(){return cr(()=>{},"never",arguments)}function FAA(A){return cr(e=>e.error(A),"throwError",arguments)}function Kq(){return cr(A=>A.complete(),"empty",arguments)}var Sk=class extends Fs{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)}},l4=Os(Sk,"reduce"),OAA=A=>Os(Sk,"count")((e,o)=>A(o)?e+1:e,0),PAA=()=>Os(Sk,"max")(Math.max),xAA=()=>Os(Sk,"min")(Math.min),YAA=()=>Os(Sk,"sum")((A,e)=>A+e,0),SM=Os(class extends Fs{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"),VAA=Os(class extends Fs{next(A){}},"ignoreElements"),Vw=Os(class extends Fs{constructor(A,e){super(A),this.count=e}next(A){this.sink.next(A),--this.count===0&&(this.doDefer(),this.complete())}},"take"),oE=Os(class extends Fs{constructor(A,e){super(A);let o=new Fs(A);o.next=()=>{o.doDefer(),A.complete()},o.complete=xq,o.subscribe(e)}},"takeUntil"),JAA=Os(class extends Fs{constructor(A,e){super(A),this.f=e}next(A){this.f(A)?this.sink.next(A):(this.doDefer(),this.complete())}},"takeWhile"),HAA=A=>l4((e,o)=>(e.push(o),e.length>A&&e.shift(),e),[]),qAA=Os(class extends Fs{constructor(A,e){super(A),this.count=e}next(A){--this.count===0&&(this.next=super.next)}},"skip"),KAA=Os(class extends Fs{constructor(A,e){super(A),A.next=eg;let o=new Fs(A);o.next=()=>{o.doDefer(),A.resetNext()},o.complete=xq,o.subscribe(e)}},"skipUntil"),jq=Os(class extends Fs{constructor(A,e){super(A),this.f=e}next(A){this.f(A)||(this.next=super.next,this.next(A))}},"skipWhile"),jAA={leading:!0,trailing:!1},WAA=class extends Fs{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)}},I4=class extends Fs{constructor(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:jAA;super(A),this.durationSelector=e,this.config=o,this._throttle=new WAA(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=eg,this._throttle.complete(),super.complete()}},zAA=Os(I4,"throttle"),ZAA={leading:!1,trailing:!0},XAA=A=>Os(I4,"audit")(A,ZAA),$AA=class extends Fs{next(){this.complete()}complete(){this.dispose(),this.sink.next(this.last)}},u4=class extends Fs{constructor(A,e){super(A),this.durationSelector=e,this._debounce=new $AA(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()}},AeA=Os(u4,"debounce"),eeA=A=>Os(u4,"debounceTime")(e=>Hq(A)),teA=Os(class extends Fs{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"),ieA=A=>e=>Vw(1)(jq(o=>!A(o))(e)),oeA=Os(class extends Fs{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"),seA=Os(class extends Fs{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"),neA=Os(class extends Fs{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"),reA=Os(class extends Fs{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"),E4=Os(class extends Fs{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"),aeA=Os(class extends Fs{constructor(){super(...arguments),this.hasLast=!1}next(A){this.hasLast?this.sink.next([this.last,A]):this.hasLast=!0,this.last=A}},"pairwise"),d4=class extends Fs{constructor(A,e,o){super(A),this.mapper=e,this.thisArg=o}next(A){super.next(this.mapper.call(this.thisArg,A))}},Wq=Os(d4,"map"),geA=A=>Os(d4,"mapTo")(e=>A),Mk=class extends Fs{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()}},vk=class D6 extends Fs{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===D6.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()}},C4=class extends Mk{},h4=class extends vk{next(A){this.subInner(A,C4),this.next=e=>{this.currentSink.dispose(),this.subInner(e,C4)}}},E2=Os(h4,"switchMap");function d2(A){return(e,o)=>A(()=>e,o)}var C2=d2(Os(h4,"switchMapTo")),ceA=class extends Mk{tryComplete(){this.dispose(),this.context.sources.length?this.context.subNext():(this.context.resetNext(),this.context.resetComplete())}},B4=class extends vk{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(),ceA),this.disposed&&this.sources.length===0&&this.currentSink.resetComplete()}tryComplete(){this.sources.length===0&&this.currentSink.resetComplete(),this.dispose()}},leA=Os(B4,"concatMap"),IeA=d2(Os(B4,"concatMapTo")),ueA=class extends Mk{tryComplete(){this.context.inners.delete(this),super.dispose(),this.context.inners.size===0&&this.context.resetComplete()}},Q4=class extends vk{constructor(){super(...arguments),this.inners=new Set}next(A){this.subInner(A,ueA),this.inners.add(this.currentSink)}tryComplete(){this.inners.size===1?this.inners.forEach(A=>A.resetComplete()):this.dispose()}},EeA=Os(Q4,"mergeMap"),deA=d2(Os(Q4,"mergeMapTo")),CeA=class extends Mk{dispose(){this.context.resetNext(),super.dispose()}},p4=class extends vk{next(A){this.next=eg,this.subInner(A,CeA)}},heA=Os(p4,"exhaustMap"),BeA=d2(Os(p4,"exhaustMapTo")),QeA=Os(class extends Fs{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=oQ(),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"),peA=Os(class extends Fs{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"),meA=Os(class extends Fs{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"),feA=Os(class extends Fs{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"),m4=Os(class extends Fs{constructor(A,e){super(A),this.selector=e}error(A){this.dispose(),this.selector(A)(this.sink)}},"catchError"),yeA=class extends Mk{tryComplete(){let A=this.context.inners.delete(this);super.dispose(),A&&this.context.checkComplete()}next(A){this.sink.next(A),this.context.expandValue(A)}},DeA=Os(class extends vk{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 yeA(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"),SeA=()=>A=>new Promise((e,o)=>{let a;new I2(A,c=>a=c,o,()=>e(a))}),MeA=()=>A=>{let e;return new ReadableStream({start(o){e=new I2(A,o.enqueue.bind(o),o.error.bind(o),o.close.bind(o))},cancel(){e.dispose()}})},Cl=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:eg,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:eg,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:eg;return a=>new I2(a,A,e,o)},zq=Os(class extends Fs{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"),veA=Os(class extends Fs{constructor(A,e){super(A),this.timeout=e,this.id=setTimeout(()=>this.error(new t4(this.timeout)),this.timeout)}next(A){super.next(A),clearTimeout(this.id),this.next=super.next}dispose(){clearTimeout(this.id),super.dispose()}},"timeout"),ReA=function(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1/0;return e=>{if(e instanceof Iy){let o=cr(a=>{let c=A,d=new Fs(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,lc.pipe(o),o}return o=>{let a=A,c=new Fs(o);c.error=d=>{a-- >0?e(c):o.error(d)},e(c)}}},Zq=(A=>(A[A.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",A[A.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",A))(Zq||{}),Rk=class S6 extends Pq{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(VA.MUTE,this.onTrackMuted),e.addEventListener(VA.UNMUTE,this.onTrackUnmuted),e.addEventListener(VA.ENDED,this.onTrackEnded),e.muted&&this.onTrackMuted(),e.readyState===VA.ENDED&&this.onTrackEnded()}uninstallTrackEvent(e){e.removeEventListener(VA.MUTE,this.onTrackMuted),e.removeEventListener(VA.UNMUTE,this.onTrackUnmuted),e.removeEventListener(VA.ENDED,this.onTrackEnded)}setStateToReady(){}capture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return jA(this,null,function*(){var a,c;let d=this.sourceTrack;try{let C,f=bo();U.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 lAA(e));let S=C.getTracks()[0];return yield this.setInputMediaStreamTrack(S),e.customSource||(this.sourceTrack=S,this.updateDeviceIdInUse(),this.listenDeviceChange()),U.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:bo()-f,profile:this.profile,room:(c=this.manager)==null?void 0:c.room}),C}catch(C){throw U.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=Qp(((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 jA(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)=>jA(this,null,function*(){var c,d,C,f,S;let b=()=>a(new oi({code:lt.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?o():((this.state===zs.INIT||this.state==="ready")&&b(),Qa(ga(e,"local-publish-flag-changed"),SM(()=>this.hasFlag),oE(Yq(ga(this,zs.INIT),ga(this,"ready"))),Cl(o,a,b))),(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=(f=this.mediaTrack)==null?void 0:f.stats)==null?void 0:S.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(()=>jA(this,null,function*(){var cA,CA,vA,$A,he,Oe,Se,fi;if((vA=(CA=(cA=this.room)==null?void 0:cA.networkQuality)==null?void 0:CA.hadRecentBadUplink)!=null&&vA.call(CA,2)||e.heartbeatCount-V<3)return o();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if(($A=this.mediaTrack)!=null&&$A.stats){let Ci=this.mediaTrack.stats.totalFrames||0;Ci-J===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",Ci)}let Ne=this.kind===VA.AUDIO,dt=this.stat.bytesSent>0;if(Ai[dt?"addSuccessEvent":"addFailedEvent"]({key:Ne?503700:513702}),!Ne){let Ci={H264:513704,H265:513705,VP8:513706}[((Oe=(he=this.room)==null?void 0:he.videoCodec)==null?void 0:Oe.toUpperCase())||"H264"];Ci&&Ai[dt?"addSuccessEvent":"addFailedEvent"]({key:Ci})}if(!dt){if(Ai.addEnum({key:Ne?503701:513703,value:Tp()}),on.uploadEvent({log:"stat-encode-failed-".concat(this.kind,"-").concat(ZB()||Np()),userId:this.userId}),this.log.warn(Ne?"encode failed":"".concat((fi=(Se=this.room)==null?void 0:Se.videoCodec)==null?void 0:fi.toUpperCase()," encode failed")),this.retryEncodeFailed&&(this.log.warn("retry encode"),yield this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(yield SC(5e3),this.stat.bytesSent>0||this.hasFlag)))return o();this.emit("6",this),a(new oi({message:"".concat(this.strMediaType," encode failed"),code:Ne?lt.AUDIO_ENCODE_FAILED:lt.VIDEO_ENCODE_FAILED}))}}}),1e4)}))}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),U.emit(nA.LOCAL_TRACK_UNPUBLISHED,{track:this})}updateDeviceIdInUse(){return jA(this,null,function*(){if(this.sourceTrack&&ny){let{deviceId:e,groupId:o}=this.sourceTrack.getSettings(),{label:a}=this.sourceTrack;(yield function(c){return jA(this,arguments,function(d){let{newDeviceId:C,oldDeviceId:f,oldGroupId:S,oldLabel:b,kind:V}=d;return function*(){return C===f&&(V!==VA.AUDIO||C!==NS||(yield qW(S,b)))}()})}({newDeviceId:e,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind}))||(this.deviceId=e,this.label=a,o&&(this.groupId=o),r2().then(c=>{let d=c.find(C=>{let f=C.deviceId===e;return o&&(f=f&&C.groupId===o),f});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===VA.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(VA.AUDIO_INPUT);return!!Fq.has(c)}(this.sourceTrack)||this.kind===VA.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(VA.VIDEO_INPUT);return!!Fq.has(c)}(this.sourceTrack)||this._isRecapturing||e&&KB&&hg)}onTrackMuted(){if(super.onTrackMuted(),IAA(),this.isNeedToRecapture(!0)){if(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),bS);this._onMuteTimeoutId=setTimeout(()=>jA(this,null,function*(){var e;if((e=this.sourceTrack)!=null&&e.muted){if((Ag||Ja)&&document.visibilityState!=="visible")return;this.recapture(yield this.getRecoverCaptureDeviceId())}}),5e3)}}onTrackUnmuted(){super.onTrackUnmuted(),this._onMuteTimeoutId>0&&clearTimeout(this._onMuteTimeoutId)}onTrackEnded(){return jA(this,null,function*(){if(MI(S6.prototype,this,"onTrackEnded").call(this),this.isNeedToRecapture()&&this.recaptureMode===0){if(Date.now()-this._lastRecaptureTimethis.onTrackEnded(),bS);this.emit("7"),this.recapture(yield this.getRecoverCaptureDeviceId())}})}recapture(e){let o=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return jA(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 Yp():yield Vp()).find(f=>f.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}),U.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(C=>{this._isRecapturing=!1,this.log.warn("recapture failed ".concat(C.message)),this.emit("5",C),U.emit(nA.LOCAL_TRACK_RECAPTURE,{track:this,error:C})}).finally(()=>{o&&c?.stop()})})}getRecoverCaptureDeviceId(){return jA(this,null,function*(){let e=this instanceof sQ;if(e&&this.facingMode)return this.facingMode;let{deviceId:o}=this;if(o){let a=(_k.get(o)||0)+1;if(_k.set(o,a),a>=3&&this.enableAutoSwitchWhenRecapturing){let c=e?(yield Vp()).find(d=>!_k.has(d.deviceId)):(yield Yp()).find(d=>!_k.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(),U.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()}};di([cc(zs.INIT,"ready",{ignoreError:!0,sync:!0})],Rk.prototype,"setStateToReady"),di([yk()],Rk.prototype,"capture"),di([cc("ready","publish",{ignoreError:!0,success(){U.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 oi?A:A.cause instanceof oi?A.cause:A,c=!1;a instanceof oi&&(a.message.includes("timeout")?o="timeout":a.code===lt.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)}}),ly(521714,!1)],Rk.prototype,"publish"),di([Hr(A=>function(){return jA(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)})}),cc([],"ready",{sync:!0})],Rk.prototype,"unpublish");var wk=Rk,_k=new Map;U.on(nA.SWITCH_DEVICE_SUCCESS,A=>{A.track.deviceId&&_k.delete(A.track.deviceId)});var MM=class AL extends wk{constructor(e){super(1,nAA),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 GI),Y(this,"_output",new GI),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 GI),this.manager=e,this.pipeline=new PW(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),U.on(nA.AUDIO_CONTEXT_LONG_SUSPENDED,this.handleAudioContextLongSuspended,this)}get dbVolume(){return n2.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){xe(e)||(e!==0||this.after3aSilenceStartTime?e>0&&(this.after3aSilenceStartTime=0):this.after3aSilenceStartTime=bo())}setInputMediaStreamTrack(e){return jA(this,null,function*(){let o=this.trackSettings||{};Ai.addEnum({key:501701,value:o.channelCount||0,useUV:!1}),Ai.addEnum({key:501702,value:o.sampleRate||0,useUV:!1}),Ai.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 MI(AL.prototype,this,"setInputMediaStreamTrack").call(this,e),this.updatePlayingState(!!e)})}capture(e){return jA(this,arguments,function(o){var a=this;let{deviceId:c,customSource:d,useExactDeviceId:C=!0,retryWhenExactFailed:f}=o,S=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let b=yield MI(AL.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:f,customSource:d},S);return mk(),b}()})}switchDevice(e){return jA(this,null,function*(){if(this.mediaTrack){if(this.deviceId===e&&!this.isUseCustomSource&&(e!==NS||(yield qW(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}),U.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(){Oc&&!Oc.listeners("audioInputRemoved").includes(this.handleMicrophoneRemoved)&&Oc.on("audioInputRemoved",this.handleMicrophoneRemoved,this)}handleMicrophoneRemoved(e){return jA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Zq[this.recaptureMode],". Current microphone is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Vg(this.userId,{eventId:2003,param1:6,streamType:1});let a=yield Yp();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Oc.on("audioInputAdded",this.handleMicrophoneAdded,this)}})}handleMicrophoneAdded(e){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Oc.off("audioInputAdded",this.handleMicrophoneAdded,this),this.log.warn("microphone added: ".concat(JSON.stringify(e))),this.recapture(e.deviceId))}update3A(e){return jA(this,arguments,function(o){var a=this;let{echoCancellation:c,noiseSuppression:d,autoGainControl:C}=o;return function*(){let f=a.sourceTrack||a.mediaTrack;if(!f)return;let S=f.getConstraints(),b=!1;!xe(c)&&c!==a.profile.echoCancellation&&(a.profile.echoCancellation=c,S.echoCancellation=c,b=!0),!xe(d)&&d!==a.profile.noiseSuppression&&(a.profile.noiseSuppression=d,S.noiseSuppression=d,b=!0),!xe(C)&&C!==a.profile.autoGainControl&&(a.profile.autoGainControl=C,S.autoGainControl=C,b=!0),b&&(er||hg?yield f.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&&Ai.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),U.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),U.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),U.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=o2(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),Ag&&this.player.setMuted(!0),this.earMonitorGainNode.node||(this.earMonitorGainNode.setNode(NI().createGain()),this._output.setNode(NI().destination)),this.earMonitorGainNode.node.gain.value=e}enableTrackANS(e){return this.update3A({noiseSuppression:e})}enableTrackAEC(e){if(this.sourceTrack&&!hg&&!Ag)return this.update3A({echoCancellation:e})}addDenoiser(e){var o;HE<=92&&((o=this.trackSettings)==null?void 0:o.sampleRate)!==48e3?this._log.warn("denoiser only support sampleRate 48000 before chrome 93"):(Ai.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=o2(e);if(!a)return;let c=new GI,d=NI().createGain();d.gain.value=1;let C=new GI;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(),Oc.off("audioInputAdded",this.handleMicrophoneAdded,this),Oc.off("audioInputRemoved",this.handleMicrophoneRemoved,this),U.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 jA(this,null,function*(){try{yield MI(AL.prototype,this,"recapture").call(this,e,o)}catch(a){let c=(yield Yp()).find(d=>d.deviceId!==e);if(!c)throw a;yield MI(AL.prototype,this,"recapture").call(this,c.deviceId)}})}encodeFrame(e){return this.manager?this.manager.encodePipeline.reduceRight((o,a)=>a?a({frame:o,ntp:Mf()}):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(Rp?"":", 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 h2(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 f4(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 f=C===-1?o.byteLength:C,S=f-c,b=new ArrayBuffer(S),V=new DataView(b);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}},weA=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),f=new DataView(C),S=new DataView(A.data),b=0;for(let V=0;V1&&arguments[1]!==void 0?arguments[1]:4,Mo),Y(this,"profile",pi({},MS)),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 weA),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=Ld(((a=this.room)==null?void 0:a.sdkAppId)||0)?jG:U0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(c)),this.setProfile(Bo(pi({},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(ny&&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 jA(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,MI(r_.prototype,this,"setMute").call(this,!1)}else this.muteImage&&(yield(c=this.manager)==null?void 0:c.deleteWatermark("mute"),this.muteImage=void 0),MI(r_.prototype,this,"setMute").call(this,e)})}capture(e){return jA(this,arguments,function(o){var a=this;let{deviceId:c,facingMode:d,useExactDeviceId:C=!0,customSource:f,retryWhenExactFailed:S=!0}=o;return function*(){let b={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:f};if(b.facingMode==="environment"){let V=yield a.getDeviceIdWhenUsingBackCamera();V&&(b.cameraId=V)}return MI(r_.prototype,a,"capture").call(a,b)}()})}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=Ld(((o=this.room)==null?void 0:o.sdkAppId)||0)?jG:U0;this.log.warn("Resolution is reset to 1080p, need to upgrade ability here ".concat(c)),super.setProfile(Bo(pi({},this.profile),{width:1920,height:1080}))}}applyProfile(){return jA(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,f=C.height!==this.profile.height||C.width!==this.profile.width||C.frameRate!==this.profile.frameRate;if(f&&(Od===16&&this.deviceId?yield this.recapture(this.deviceId):(pp(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:b=0}=(this.sourceTrack||this.mediaTrack).getSettings(),V=S*b;return f&&V&&d&&V===d?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:VA.VIDEO,videoType:VA.BIG})}})}get settings(){let e={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},o=this.sourceTrack||this.mediaTrack;return ny&&o&&Object.assign(e,o.getSettings()),e}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:rw(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 jA(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),U.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 jA(this,null,function*(){let e;try{if(kb&&!jf&&Zx){let o=(yield Vp(!0)).map(c=>{var d;return Bo(pi({},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,f,S;let{capabilities:b}=c;((d=b.width)!=null&&d.max&&(C=b.height)!=null&&C.max?b.width.max*b.height.max:0)>((f=a.capabilities.width)!=null&&f.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 jA(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=pi({},e);return e.width*e.height<=19200&&Ja&&tE&&(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&&Fx&&(c.width=a?1280:720,c.height=a?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),xb(wI,"14.3")&&zf(wI,"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&&(tE||er)&&!Dw()&&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(){Oc&&!Oc.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&Oc.on("videoInputRemoved",this.handleCameraRemoved,this)}handleCameraRemoved(e){return jA(this,null,function*(){if(e.deviceId===this.deviceId){let o=this.recaptureMode===1;if(this.log.warn("RecaptureMode: ".concat(Zq[this.recaptureMode],". Current camera is lost: ").concat(JSON.stringify(e))),this.recaptureMode===0){Vg(this.userId,{eventId:2003,param1:7,streamType:2});let a=yield Vp();a[0]?this.recapture(a[0].deviceId):o=!0}o&&Oc.on("videoInputAdded",this.handleCameraAdded,this)}})}handleCameraAdded(e){return jA(this,null,function*(){this.recaptureMode===1&&e.deviceId!==this.deviceId||(Oc.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 xe(this.mirror)&&!this.isScreen&&this.setMirror("view"),super.play(e,o)}close(){Oc.off("videoInputAdded",this.handleCameraAdded,this),Oc.off("videoInputRemoved",this.handleCameraRemoved,this),super.close()}recapture(e){return jA(this,null,function*(){try{yield MI(r_.prototype,this,"recapture").call(this,e)}catch(o){let a=(yield Vp()).find(c=>c.deviceId!==e);if(!a)throw o;yield MI(r_.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||xe(e)||e!==this.rotation&&(this.rotation=e,this.manager.rotation=e))}};di([DM(function(A){this.setContentHint(A.contentHint||"motion")})],y4.prototype,"capture");var sQ=y4,D4={};bh(D4,{REPORT_TYPE:()=>aw,buildSSOPackage:()=>JB,bytes2ms:()=>ew,calculateScaleResolutionDownNumber:()=>rw,concatArrayBuffers:()=>VS,convertObjectNumberToInt:()=>nw,copyProperties:()=>Ex,deepClone:()=>Pf,deepCloneBasic:()=>xf,deepMerge:()=>Fh,delay:()=>SC,fibonacci:()=>Uf,formatedTime:()=>fx,getConstructorName:()=>FS,getContainerFromElement:()=>Eb,getEnv:()=>lx,getFirst16Bits:()=>Dx,getInternalVersion:()=>px,getLast16Bits:()=>gw,getLoggerUrl:()=>kf,getMediaStreamTrackInfo:()=>Qb,getMuteStateFromFlag:()=>Qp,getNetworkType:()=>$0,getNumNetworkType:()=>Lf,getReconnectionTimeout:()=>Bp,getStringByteLength:()=>sw,getTestSignalDomain:()=>Ix,getTurnServer:()=>mx,getUint32Version:()=>Cb,getValueType:()=>dg,getViewListFromView:()=>xS,glog:()=>Cx,ipv4ToUint32:()=>PS,isArray:()=>va,isAudioWorkletSupported:()=>hx,isBoolean:()=>wr,isConstructor:()=>Of,isEmpty:()=>iw,isFunction:()=>Ma,isLangChinese:()=>Ud,isMediaStreamTrack:()=>Ib,isNumber:()=>bn,isObject:()=>xE,isOverseaSdkAppId:()=>Ld,isPlainObject:()=>eE,isPortrait:()=>db,isPromise:()=>Ff,isRemoteTrack:()=>ub,isRotate90Or270:()=>VB,isSetSinkIdSupported:()=>Bx,isString:()=>Yn,isUndefined:()=>xe,isVideoMixerOutputTrack:()=>pp,loadImage:()=>YS,loadVideo:()=>yx,ms2bytes:()=>dx,ms2samples:()=>tw,normalizeUrl:()=>Bb,performanceNow:()=>bo,promiseAny:()=>OS,samples2ms:()=>lb,setNetworkTypeFromWebRTC:()=>Aw,stringify:()=>Fd,stringifyIncludeValue:()=>ow,throttlePromise:()=>hb});var _eA=[-1,-1,1,-1,-1,1,1,1],TeA=[0,0,1,0,0,1,1,1],Tk=class Pj 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 nQ)e.ctx&&o.create2d&&(typeof OffscreenCanvas=="function"&&Od!==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(TeA),this.positionBuffer=this.createBuffer(_eA),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 oi({code:lt.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,f,S,b){let V=!(xe(C)||xe(f)||xe(S)||xe(b));return!(!this.ctx2d||!e)&&(e instanceof ImageData?(V?this.ctx2d.putImageData(e,o,a,C,f,S,b):this.ctx2d.putImageData(e,o,a),this.emit(Pj.RENDER,this.ctx2d.canvas)):(V?this.ctx2d.drawImage(e,C,f,S,b,o,a,c,d):this.ctx2d.drawImage(e,o,a,c,d),this.emit(Pj.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:f,cost:S}=this,b=Date.now(),V=(o-this.lastInfo.totalFrames)/((b-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:o,x:a,y:c,width:d,height:C,timestamp:b,fps:V,name:f,cost:S},pi({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(Tk,"RENDER","render"),di([cc(zs.INIT,"connected",{sync:!0})],Tk.prototype,"connect"),di([cc("connected",zs.INIT,{ignoreError:!0,sync:!0})],Tk.prototype,"disconnect"),di([cc([],"closed",{sync:!0})],Tk.prototype,"close");var Yd=Tk,NeA=Qa(g4(250),Wq(()=>performance.now()),Dk()),GeA=[0,1,1,1,0,0,1,0],Xq=class extends Yd{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 nQ?this.ctx2d=A.ctx||null:A.available&&e!=null&&e.mirrorUpAndDown&&this.setTexBuffer(GeA)}start(A){this.log.info("".concat(this.name," start render ").concat(A," fps")),_r.clearTask(this._intervalId),this._intervalId=_r.run("intervalInWorker",()=>{if(A!==this.context.frameRate&&(_r.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof NC){let e=this.context.ctx.getError();e&&this.context.destroy(new oi({code:lt.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(Yd.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&&(_r.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),_r.clearTask(this._intervalId)}resize(A,e){super.resize(A,e),this.context.setSize(A,e)}close(){super.close(),_r.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},$q=class extends Xq{constructor(A,e){super(A,e),Y(this,"_videoTrack"),Y(this,"_muteOb"),Y(this,"_closedOb",ga(this,"closed")),Y(this,"_subscription"),Y(this,"_canvasContainer"),Number(jB)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=A.canvas.captureStream().getVideoTracks(),this._muteOb=ga(this._videoTrack,"mute"),Qa(ga(this._videoTrack,"ended"),oE(this._closedOb),Cl(()=>{this.context.destroy(new oi({code:lt.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){var A;this._subscription=Qa(this._muteOb,oE(this._closedOb),C2((A=5e3,e=>{let o=performance.now();Qa(NeA,jq(a=>a-o{var e;return!((e=this._videoTrack)==null||!e.muted||document.hidden)}),Cl(()=>{this.context.destroy(new oi({code:lt.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()}},beA=class extends $q{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(Yd.RENDER,this.context._canvas2d)}else this.emit(Yd.RENDER,this.context._canvas);return o}},keA=class extends $q{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))}},S4=class extends Yd{constructor(A,e){super(A,pi({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,Od===16&&(this._canvasRendered=oQ(),Qa(this._canvasRendered,Vq(this._image),E2(o=>o instanceof HTMLCanvasElement?ga(o,"rendered"):Kq()),oE(ga(this,"closed")),Cl(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;let A=this.image;this.videoCallbackId&&A.cancelVideoFrameCallback(this.videoCallbackId),Fp()&&!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)}},M4=class extends S4{constructor(A,e,o){super(A,o),this._player=e,this.name="videoPlayerSource",Qa(ga(this._player,mo.PLAYER_STATE_CHANGED),oE(ga(this,"closed")),SM(a=>{let{state:c}=a;return c==="PLAYING"}),Cl(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},Jw=class extends M4{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(A,e,o){super(A,new Mo({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()}},LeA=class extends Yd{constructor(A,e,o){super(A,Bo(pi({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 f=0;f0&&arguments[0]!==void 0&&arguments[0];if(this._canvas||(this._canvas=document.createElement("canvas"),this._canvas.id="trtc_".concat(this.name,"_").concat(Nk._ids++)),A&&(this._canvas2d=document.createElement("canvas")),this.ctx=this._canvas.getContext("webgl2",ob),!this.ctx)throw new oi({code:lt.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; +varying vec2 v_texCoord; + +void main() { + gl_Position = a_position; + v_texCoord = a_texCoord; +} +`),this.defaultFShader=this.createShader(this.ctx.FRAGMENT_SHADER,` +// 片元着色器 +precision mediump float; +varying vec2 v_texCoord; +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 oi({code:lt.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(A){let e="";return A&&(e=A.message,this.error=A,Ai.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(Gk,"UNAVAILABLE","unavailable"),di([cc(zs.INIT,"created",{sync:!0,fail(A){this.log.error("video gl context create failed",A.cause),Ai.addFailedEvent({key:512700,error:A.cause||A})},success(){this.log.info("video context created use webgl"),Ai.addSuccessEvent({key:512700})}})],Gk.prototype,"create"),di([cc("created",zs.INIT,{ignoreError:!0,sync:!0,success(A){A&&this.emit(Gk.UNAVAILABLE,A),this.removeAllListeners()}})],Gk.prototype,"destroy");var NC=Gk,nQ=class extends Nk{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(Nk._ids++),this.ctx=this._canvas.getContext("2d",{alpha:A.alpha,willReadFrequently:A.willReadFrequently}),!this.ctx)throw new oi({code:lt.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,Ai.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(),Ai.addSuccessEvent({key:512703})}};function UeA(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),f=o/C,S=a/C;d.sx=(A-f)/2,d.sy=(e-S)/2,d.sWidth=f,d.sHeight=S;break}}return d}di([cc(zs.INIT,"created",{sync:!0,fail(A){this.log.error("video 2d context create failed",A.cause),Ai.addFailedEvent({key:512701,error:A.cause||A})},success(){this.log.info("video context created use 2d"),Ai.addSuccessEvent({key:512701})}})],nQ.prototype,"create"),di([cc("created",zs.INIT,{ignoreError:!0,sync:!0})],nQ.prototype,"destroy");var FeA=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}},v4=class extends Yd{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 FeA(A,e);this.inputs.splice(o,0,c)}changeInputLayout(A,e){let o=this.inputs.findIndex(cA=>cA.node===A);if(o<0)return;let{x:a,y:c,width:d,height:C,zIndex:f,fillMode:S,rotation:b,hidden:V}=e;if(!xe(f)&&this.inputs.some(cA=>cA.layout.zIndex===f&&cA.node!==A))throw new Error("input already exists at zIndex ".concat(e.zIndex));let J=this.inputs[o];xe(a)||(J.layout.x=a),xe(c)||(J.layout.y=c),xe(d)||(J.layout.width=d),xe(C)||(J.layout.height=C),xe(b)||(J.layout.rotation=b),xe(V)||(J.layout.hidden=V),S&&(J.layout.fillMode=S),!xe(f)&&f!==J.layout.zIndex&&(J.layout.zIndex=f,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,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 NC&&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(),f=(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:f,name:d},pi({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 NC)try{(e=this.context.ctx)==null||e.deleteBuffer(A.positionBuffer)}catch{}})}close(){super.close(),this.removeAllInputs()}},OeA=[1,0,0,0,1,1,0,1],Ey=class extends Yd{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 NC)try{this.setTexBuffer(OeA)}catch(c){A.destroy(new oi({code:lt.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){VB(this.rotation)&&([A,e]=[e,A]),super.resize(A,e)}},AK=class extends wk{constructor(A){super(arguments.length>1&&arguments[1]!==void 0?arguments[1]:4,Mo),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(Yd.RENDER,e=>{this.emit("render",e)}),this.mixNode=new v4(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=_r.run("interval",()=>{this.destination&&this.log.debug(this.destination.getInfo())},{delay:A})}create2dVideoContext(){this.videoContext?this.videoContext.destroy():this.videoContext=new nQ({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 jA(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),Rp&&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,WE(this,Oc).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=Od===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(Od===16&&o instanceof CanvasCaptureMediaStreamTrack)if(d instanceof Jw){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 Jw)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:f}=o.getSettings();C&&f&&d.resize(C,f)}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&&(xe(o)||(C.content=o),xe(a)||(C.font=a),xe(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 Ey(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 Ey&&(xe(o)||(c.mirror=o),xe(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 Ey&&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 Ey&&o.output.close(),o.close(),this.screenNodeMap.delete(A)),this.checkAfterRemove(!0)}removeTextSource(A){let e=this.textNodeMap.get(A);e&&(e.output instanceof Ey&&e.output.close(),e.close(),this.textNodeMap.delete(A)),this.checkAfterRemove()}removeImageSource(A){let e=this.imageNodeMap.get(A);e&&(e.output instanceof Ey&&e.output.close(),e.close(),this.imageNodeMap.delete(A)),this.checkAfterRemove()}removeVideoSource(A){let e=this.videoNodeMap.get(A);e&&(e.output instanceof Ey&&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(),_r.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")}},eK=xA();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:eK,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var PeA=function(A){return jA(this,null,function*(){let e=null,o=function(d){let C={preferCurrentTab:d.preferDisplaySurface==="current-tab"||!!d.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},f={width:hg?{max:d.width}:{ideal:d.width,max:d.width},height:hg?{max:d.height}:{ideal:d.height,max:d.height},frameRate:d.frameRate,displaySurface:d.preferDisplaySurface||"monitor"};if(C.video=f,d.systemAudio){let{echoCancellation:S=!0,noiseSuppression:b=!1,autoGainControl:V=!1}=d;C.audio={echoCancellation:S,noiseSuppression:b,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&&(fw&&HE<74||hg||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 jA(this,null,function*(){var f;if("CropTarget"in window&&"fromElement"in CropTarget&&Ma(d.cropTo))try{if(((f=d.getCaptureHandle())==null?void 0:f.handle)!==eK)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 f={echoCancellation:C.echoCancellation,autoGainControl:C.autoGainControl,noiseSuppression:C.noiseSuppression,sampleRate:C.sampleRate,channelCount:C.channelCount};return xe(C.microphoneId)||(f.deviceId=C.microphoneId),{audio:f,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})},vM=class extends sQ{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 eK===((e=(A=this.mediaTrack)==null?void 0:A.getCaptureHandle())==null?void 0:e.handle)}catch{return}}capture(A){return jA(this,arguments,function(e){var o=this;let{systemAudio:a=!1,autoGainControl:c,echoCancellation:d,noiseSuppression:C,audioTrack:f,videoTrack:S,captureElement:b,preferDisplaySurface:V}=e;return function*(){var J;try{let cA,CA=bo();return S||f?(cA=new MediaStream,S&&cA.addTrack(S),f&&cA.addTrack(f)):(cA=yield PeA({audio:!1,systemAudio:a,width:o.profile.width,height:o.profile.height,frameRate:o.profile.frameRate,autoGainControl:c,echoCancellation:d,noiseSuppression:C,captureElement:b,preferDisplaySurface:V}),o.sourceTrack=cA.getVideoTracks()[0]),yield o.setInputMediaStreamTrack(cA.getVideoTracks()[0]),U.emit(nA.LOCAL_TRACK_CAPTURE_SUCCESS,{track:o,cost:bo()-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 oi?cA:new oi({code:lt.INITIALIZE_FAILED,name:cA.name,message:cA.message})}}()})}switchDevice(A){return jA(this,null,function*(){throw new Error("Method not implemented.")})}};di([DM(function(A){this.setContentHint(A.contentHint||"detail")})],vM.prototype,"capture");var tK,iK=class extends MM{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 oK(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 jA(this,null,function*(){let c=NI();tK||(tK=Yg(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;tf.connect(C,0,S)),new ReadableStream({start(f){C.port.onmessage=S=>{f.enqueue(S.data)}},cancel(){A.forEach(f=>f.disconnect(C)),C.port.close()}})})}var xeA=class extends tAA{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=[],f=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)=>C[CA]=C[CA]?C[CA].concat(cA[0]):[cA[0]])}}),d).catch(J=>S));return{then:b.then.bind(b),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:f=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 b,V,J=Math.floor(.04*C),cA=new Float32Array(J),CA=new Float32Array(J),vA=0,$A=new AbortController,he=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(he)return oK([NI().createMediaStreamSource(new MediaStream([he]))],C,f,S).then(Oe=>Oe.pipeTo(new WritableStream({write(Se){Se[0][0]&&(vA+Se[0][0].length>J?(cA.set(Se[0][0].subarray(0,J-vA),vA),b=Se[0][0].subarray(J-vA),Se[0][1]&&(CA.set(Se[0][1].subarray(0,J-vA),vA),V=Se[0][1].subarray(J-vA)),vA+=J-vA):(b&&(cA.set(b,vA),vA+=b.length,b=void 0),V&&(CA.set(V,vA),V=void 0),cA.set(Se[0][0],vA),Se[0][1]&&CA.set(Se[0][1],vA),vA+=Se[0][0].length),vA>=J&&(vA=0,A({userId:e,sampleRate:C,channelCount:f,data:f===1?cA:[cA,CA]}),cA=new Float32Array(J),CA=new Float32Array(J)))}}),$A).catch(Se=>this.log.warn("stop getPCM reason:".concat(Se)))),$A;this.log.info("getPCM failed: ".concat(e||"local"," has no audio track"))}get hasScreenAudioTrack(){return!xe(this._localScreenAudioTrack)}get hasAudioTrack(){return!xe(this._localAudioTrack)}changeInput(A){var e,o;return A instanceof iK?(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 MM?(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 p2?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 iK?delete this._localScreenAudioTrack:A instanceof MM&&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 f;(f=this._localAudioTrack)==null||f.mixAudioReference(d,C)})),this.isScreenAudioNeedAudioProcess&&this._localScreenAudioTrack&&a&&((c=this._localScreenAudioTrack)==null||c.addAudioProcessor(a,A,e),this.audioReferenceMap.forEach((d,C)=>{var f;(f=this._localScreenAudioTrack)==null||f.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 f;(f=this.room)==null||f.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(){U.on("113",this.handleLocalTrackStarted,this),U.on("114",this.handleLocalTrackStopped,this),U.on("115",this.handleRemoteTrackStarted,this),U.on("116",this.handleRemoteTrackStopped,this)}uninstallEvent(){U.off("113",this.handleLocalTrackStarted),U.off("114",this.handleLocalTrackStopped),U.off("115",this.handleRemoteTrackStarted),U.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||xe(c))return;this.setAudioReferenceVolume(a,c)}}};function Q2(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:30,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:2;return Hr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;C{let b=setTimeout(()=>{let V=new oi({code:lt.API_CALL_TIMEOUT,message:"checkPendingPromise ".concat(a,"() timeout ").concat(A,"s")});(this.log||this._log||QA).warn(V),e===2?S(V):e===1&&f()},1e3*A);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(b),o.apply(this,d).then(f,S).finally(()=>{clearTimeout(b),this._checkPendingPromiseSet&&b&&this._checkPendingPromiseSet.delete(b)})})})}var RM=class xj extends Pq{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",oQ(ga(this,xj.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"),Qa(Yq(ga(this,zs.STATECHANGED),ga(this.remotePublishState,zs.STATECHANGED)),Wq(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Cl(f=>{this.availableState.state!==(f?zs.ON:zs.OFF)&&(this.availableState.state=f?zs.ON:zs.OFF),(!this.isRemotePublished||!this.ignoreUpdatePlayingState)&&this.updatePlayingState(f)}));let c=Qa(ga(this.player,mo.ERROR),SM(f=>f.code===MediaError.MEDIA_ERR_DECODE)),d=Qa(Hq(5e3),SM(()=>!!(!this.ignoreDecodeError&&this.isSubscribed&&this.isPlayCalled&&this.stat.bytesReceived&&this.isRemotePublished)&&(!this.player.isPlaying&&!(this.kind===VA.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0)||(this.reportDecodeResult(!0),!1)))),C=Qa(o4(c,d),oE(ga(this,zs.INIT)));Qa(this._triggerCheckDecodeSubject,SM(()=>!this.ignoreDecodeError),C2(C),Cl(f=>{this.reportDecodeResult(!1,f)}))}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===xj.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===VA.AUDIO;if(Ai[e?"addSuccessEvent":"addFailedEvent"]({key:d?504700:514702}),!d){let C=((a=this.room)==null?void 0:a.downlinkVideoCodec.toUpperCase())||"H264";Ai[e?"addSuccessEvent":"addFailedEvent"]({key:oy["DECODE_".concat(C,"_RESULT")]}),e||this.log.warn("".concat((c=this.room)==null?void 0:c.downlinkVideoCodec," decode failed"))}e||(Ai.addEnum({key:d?504701:514703,value:Tp()}),on.uploadEvent({log:"stat-decode-failed-".concat(this.kind,"-").concat(ZB()||Np()),userId:this.room.userId}),this._log.warn("decode failed: isPlaying: ".concat(this.player.isPlaying," ").concat(this.kind===VA.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(RM,"STATE_SUBSCRIBE","subscribe"),di([Q2(5,1)],RM.prototype,"waitHasMediaTrack"),di([cc(zs.INIT,RM.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),U.emit(nA.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),ly(521716,!1)],RM.prototype,"subscribe"),di([cc(RM.STATE_SUBSCRIBE,zs.INIT,{sync:!0,success(){this.log.info("unsubscribed"),U.emit(nA.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],RM.prototype,"unsubscribe");var R4=RM,p2=class extends R4{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 n2.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&&bw().AudioDecoder&&Up)}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:f,hasLeavingTag:S}=d;this.emit("audio-frame-with-ntp",{ntp:C,frame:f,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}},YeA=class extends Yd{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",oQ()),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(),Ai.addEnum({key:515700,value:1}),this.draggable&&Ai.addEnum({key:515700,value:11})}bindDragEvents(){let A=this.context._canvas;if(A)if(this.draggable){let e=oE(this.end);Qa(ga(A,"mousedown"),zq(this.startDrag.bind(this)),E2(()=>Qa(ga(window,"mousemove"),oE(ga(window,"mouseup")))),e,Cl(this.doDrag.bind(this))),Qa(ga(A,"dblclick"),e,Cl(this.resetPosition.bind(this))),Qa(ga(A,"wheel"),e,Cl(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,f=this.context._canvas;if(!C||!f)return!1;let S=super.draw2d(A,e,o,a,c),b=C.getImageData(0,0,a,c),{data:V}=b,J=!1;if(this.initStat.alphaStitchingType===1){let cA=Math.floor(a/2);for(let CA=0;CA=100;V[$A+3]=Se?255:0}J=super.draw2d(b,0,0,0,0,cA,c),f.width=cA}else if(this.initStat.alphaStitchingType===2){let cA=Math.floor(c/2);for(let CA=0;CA=100;V[$A+3]=Se?255:0}J=super.draw2d(b,0,0,0,0,a,cA),f.height=cA}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()}},bk=class extends R4{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(),U.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=ty[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 nQ({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 Xq(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 YeA(e,this.log,this.shouldBeDraggable,a,{alphaStitchingType:A});this.source.connect(c),c.connect(o),this.alphaNode=c}else this.source.connect(o);Fp()||(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),U.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),f=d<=2.5?"debug":"info";this.log[f](C),this._keyFrameCountLogged=!0}}},w4=class extends bk{constructor(A,e){super(A,e,2),Y(this,"mediaType",2),Y(this,"objectFit","contain")}get isRemotePublished(){return this.user.muteState.hasAuxiliary}},Hw=new Map;function Vg(A,e){let o=Bo(pi({},e),{timestamp:Mf()});Hw.has(A)?Hw.get(A).push(o):Hw.set(A,[o])}function _4(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,C=new Array(d),f=0;fOf(b)?FS(b):Yn(b)?b:dg(b))},fnName:c,value:o},link:{className:d,fnName:c}})})}else if(!xe(e.type)&&dg(o)!==e.type)throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.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)),b=Yn(o)&&o.trim()==="";if(S||b)throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.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 oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.CANNOT_LESS_THAN_ZERO,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});if(!xe(e.min)&&bn(o)&&oe.max)throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.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 oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.INVALID_PARAMETER_INSTANCE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})})}else if(Ma(e.instanceOf)&&!(o instanceof e.instanceOf))throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.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 oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.INVALID_PARAMETER_RANGE,data:{key:a,rule:e,fnName:c,value:o},link:{className:d,fnName:c}})});let{properties:C}=e;eE(C)&&xE(o)&&Object.keys(C).forEach(S=>{m2.call(this,{rule:C[S],value:o&&o[S],key:"".concat(a,".").concat(S),fnName:c,className:d})});let{arrayItem:f}=e;eE(f)&&va(o)&&o.forEach((S,b)=>{m2.call(this,{rule:f,value:S,key:"".concat(a,"[").concat(b,"]"),fnName:c,className:d})}),Ma(e.validate)&&e.validate.call(this,o,a,c,d,this)}U.on(nA.JOIN_SUCCESS,A=>{let{room:e}=A;Vg(e.userId,{eventId:32788})}),U.on(nA.LEAVE_START,A=>{let{room:e}=A;Vg(e.userId,{eventId:32789})}),U.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),Vg(e.room.userId,{eventId:o})}}),U.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),Vg(e.room.userId,{eventId:o})}}),U.on(nA.TRACK_MUTED,A=>{let{track:e}=A;e.room&&(e.kind===VA.AUDIO?Vg(e.room.userId,{eventId:e.isRemote?32785:32772,remoteUserId:e.isRemote?e.userId:void 0}):Vg(e.room.userId,{eventId:e.isRemote?32784:32773,remoteUserId:e.isRemote?e.userId:void 0}))}),U.on(nA.TRACK_UNMUTED,A=>{let{track:e}=A;e.room&&(e.kind===VA.AUDIO?Vg(e.room.userId,{eventId:e.isRemote?32787:32774,remoteUserId:e.isRemote?e.userId:void 0}):Vg(e.room.userId,{eventId:e.isRemote?32786:32775,remoteUserId:e.isRemote?e.userId:void 0}))}),U.on(nA.REMOTE_TRACK_SUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Vg(e.room.userId,{eventId:32777,remoteUserId:e.userId}),e.mediaType===4&&Vg(e.room.userId,{eventId:32776,remoteUserId:e.userId}),e.mediaType===8&&Vg(e.room.userId,{eventId:32803,remoteUserId:e.userId}))}),U.on(nA.REMOTE_TRACK_UNSUBSCRIBED,A=>{let{track:e}=A;e.room&&(e.mediaType===1&&Vg(e.room.userId,{eventId:32779,remoteUserId:e.userId}),e.mediaType===4&&Vg(e.room.userId,{eventId:32778,remoteUserId:e.userId}),e.mediaType===8&&Vg(e.room.userId,{eventId:32804,remoteUserId:e.userId}))}),U.on(nA.SWITCH_DEVICE_SUCCESS,A=>{let{track:e}=A;e.room&&Vg(e.room.userId,{eventId:e.kind===VA.VIDEO?32780:32781})}),U.on(nA.LOCAL_TRACK_REPLACED,A=>{let{track:e}=A;e.room&&Vg(e.room.userId,{eventId:e.kind===VA.VIDEO?32782:32783})}),U.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&&Vg(o.userId,{eventId:e})}),U.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&&Vg(o.userId,{eventId:e,remoteUserId:d})}),U.on(nA.VIDEO_CODEC_IMPLEMENTATION_CHANGED,A=>{let{implementation:e,userId:o,remoteUserId:a,codec:c,isHWCodec:d,prevImplementation:C,streamType:f}=A,S=d?1:0;C||(S=d?3:2);let b={H264:0,H265:1,VP8:2}[c.toUpperCase()],V={eventId:4004,param1:S,param2:b,streamType:f||2};a&&(V.remoteUserId=a,V.eventId=4005),Vg(o,V),Ai.addEnum({key:a?514701:513701,value:S}),Ai.addEnum({key:a?514700:513700,value:b})}),U.on(nA.LOCAL_TRACK_RECAPTURE,A=>{let{track:e,error:o}=A;if(e.userId){let a={eventId:2003,param1:0};e.kind===VA.AUDIO?(a.streamType=1,o&&(a.param1=2)):(a.streamType=e.streamType==="auxiliary"?7:2,o&&(a.param1=8)),Vg(e.userId,a)}});var JeA=ac(Jl(),1),HeA=class extends JeA.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===K0)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,"]");xe(e)||(a+=":".concat(rx[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:f}=e,S=Qp(c,d),b=(o=this.remotePublishedUserMap.get(a))==null?void 0:o.muteState;if(b){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:b,muteState:S,flag:c}))}else this._log.info("remote publish. state: ".concat(JSON.stringify(S))),this.addUser({userId:d,tinyId:C,role:20,fromType:f}),this.emit("3",e),this.emit("6",{prevMuteState:Qp(0,d),muteState:S,flag:c})})}clear(){this.userMap.clear(),this.remotePublishedUserMap.clear()}},qeA=ac(Jl(),1),KeA=class extends qeA.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 T4(A){let{timesInSecond:e,maxSizeInSecond:o,getSize:a}=A;return Hr((c,d)=>{let C=new WeakMap;return U.on(nA.ROOM_DESTROY,f=>{let{room:S}=f;return C.delete(S)}),function(){let f=C.get(this);for(var S=arguments.length,b=new Array(S),V=0;V1e3&&(f.timestamp=Date.now(),f.callCountInSecond=0,f.totalSizeInSecond=0),a&&(f.totalSizeInSecond+=a(...b)),f.timestamp!==0&&Date.now()-f.timestamp<1e3&&(f.callCountInSecond>=e||f.totalSizeInSecond>o))throw new oi({code:lt.INVALID_OPERATION,message:Zo({key:So.CALL_FREQUENCY_LIMIT,data:{isTimes:f.callCountInSecond>=e,isSize:f.totalSizeInSecond>o,name:d,timesInSecond:e,maxSizeInSecond:o}})});f.callCountInSecond++,c.call(this,...b)}})}var pt,N4=!0,kk={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"},vo={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},f2=((pt=f2||{})[pt.INVALID_PARAMETER=5e3]="INVALID_PARAMETER",pt[pt.INVALID_PARAMETER_REQUIRED=5001]="INVALID_PARAMETER_REQUIRED",pt[pt.INVALID_PARAMETER_TYPE=5002]="INVALID_PARAMETER_TYPE",pt[pt.INVALID_PARAMETER_EMPTY=5003]="INVALID_PARAMETER_EMPTY",pt[pt.INVALID_PARAMETER_INSTANCE=5004]="INVALID_PARAMETER_INSTANCE",pt[pt.INVALID_PARAMETER_RANGE=5005]="INVALID_PARAMETER_RANGE",pt[pt.INVALID_PARAMETER_LESS_THAN_ZERO=5006]="INVALID_PARAMETER_LESS_THAN_ZERO",pt[pt.INVALID_PARAMETER_MIN=5007]="INVALID_PARAMETER_MIN",pt[pt.INVALID_PARAMETER_MAX=5008]="INVALID_PARAMETER_MAX",pt[pt.INVALID_ELEMENT_ID=5009]="INVALID_ELEMENT_ID",pt[pt.INVALID_ELEMENT_ID_TYPE=5010]="INVALID_ELEMENT_ID_TYPE",pt[pt.INVALID_STREAM_ID=5011]="INVALID_STREAM_ID",pt[pt.INVALID_ROOM_ID_STRING=5012]="INVALID_ROOM_ID_STRING",pt[pt.INVALID_ROOM_ID_INTEGER=5013]="INVALID_ROOM_ID_INTEGER",pt[pt.INVALID_STREAM_TYPE=5014]="INVALID_STREAM_TYPE",pt[pt.INVALID_ROOM_ID_REQUIRED=5015]="INVALID_ROOM_ID_REQUIRED",pt[pt.INVALID_ROOM_ID_INTEGER_STRING=5016]="INVALID_ROOM_ID_INTEGER_STRING",pt[pt.INVALID_BUFFER_EMPTY=5017]="INVALID_BUFFER_EMPTY",pt[pt.INVALID_BUFFER_OVERSIZE=5018]="INVALID_BUFFER_OVERSIZE",pt[pt.INVALID_ROOM_ID_TYPE_MISMATCH=5019]="INVALID_ROOM_ID_TYPE_MISMATCH",pt[pt.INVALID_ROOM_ID_DUPLICATE=5020]="INVALID_ROOM_ID_DUPLICATE",pt[pt.INVALID_OPERATION=5100]="INVALID_OPERATION",pt[pt.INVALID_OPERATION_NOT_JOINED=5101]="INVALID_OPERATION_NOT_JOINED",pt[pt.INVALID_OPERATION_REMOTE_USER_NOT_EXIST=5102]="INVALID_OPERATION_REMOTE_USER_NOT_EXIST",pt[pt.INVALID_OPERATION_STREAM_TYPE_NOT_EXIST=5103]="INVALID_OPERATION_STREAM_TYPE_NOT_EXIST",pt[pt.INVALID_OPERATION_REPEAT_CALL=5104]="INVALID_OPERATION_REPEAT_CALL",pt[pt.INVALID_OPERATION_NEED_VIDEO=5105]="INVALID_OPERATION_NEED_VIDEO",pt[pt.INVALID_OPERATION_NEED_AUDIO=5106]="INVALID_OPERATION_NEED_AUDIO",pt[pt.INVALID_ROLE_AUDIENCE=5107]="INVALID_ROLE_AUDIENCE",pt[pt.INVALID_NOT_ENABLE_SEI=5108]="INVALID_NOT_ENABLE_SEI",pt[pt.INVALID_NEED_CALL_PUBLISHED=5109]="INVALID_NEED_CALL_PUBLISHED",pt[pt.ENV_NOT_SUPPORTED=5200]="ENV_NOT_SUPPORTED",pt[pt.NOT_SUPPORTED_HTTP=5201]="NOT_SUPPORTED_HTTP",pt[pt.NOT_SUPPORTED_WEBRTC=5202]="NOT_SUPPORTED_WEBRTC",pt[pt.NOT_SUPPORTED_H264_ENCODE=5203]="NOT_SUPPORTED_H264_ENCODE",pt[pt.NOT_SUPPORTED_H264_DECODE=5204]="NOT_SUPPORTED_H264_DECODE",pt[pt.NOT_SUPPORTED_SCREEN_SHARE=5205]="NOT_SUPPORTED_SCREEN_SHARE",pt[pt.NOT_SUPPORTED_SMALL_VIDEO=5206]="NOT_SUPPORTED_SMALL_VIDEO",pt[pt.NOT_SUPPORTED_SEI=5207]="NOT_SUPPORTED_SEI",pt[pt.NOT_SUPPORTED_WEBGL=5208]="NOT_SUPPORTED_WEBGL",pt[pt.NOT_SUPPORTED_CHROME_VERSION=5209]="NOT_SUPPORTED_CHROME_VERSION",pt[pt.NOT_SUPPORTED_PLUGIN=5210]="NOT_SUPPORTED_PLUGIN",pt[pt.DEVICE_ERROR=5300]="DEVICE_ERROR",pt[pt.DEVICE_NOT_FOUND_ERROR=5301]="DEVICE_NOT_FOUND_ERROR",pt[pt.DEVICE_NOT_ALLOWED_ERROR=5302]="DEVICE_NOT_ALLOWED_ERROR",pt[pt.DEVICE_NOT_READABLE_ERROR=5303]="DEVICE_NOT_READABLE_ERROR",pt[pt.DEVICE_OVERCONSTRAINED_ERROR=5304]="DEVICE_OVERCONSTRAINED_ERROR",pt[pt.DEVICE_INVALID_STATE_ERROR=5305]="DEVICE_INVALID_STATE_ERROR",pt[pt.DEVICE_SECURITY_ERROR=5306]="DEVICE_SECURITY_ERROR",pt[pt.DEVICE_ABORT_ERROR=5307]="DEVICE_ABORT_ERROR",pt[pt.CAMERA_RECOVER_FAILED=5308]="CAMERA_RECOVER_FAILED",pt[pt.MICROPHONE_RECOVER_FAILED=5309]="MICROPHONE_RECOVER_FAILED",pt[pt.NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX=5310]="NOT_SUPPORTED_MISMATCH_SAMPLE_RATE_IN_FIREFOX",pt[pt.SERVER_ERROR=5400]="SERVER_ERROR",pt[pt.NEED_TO_BUY=5401]="NEED_TO_BUY",pt[pt.ACCOUNT_NO_MONEY=-100013]="ACCOUNT_NO_MONEY",pt[pt.OPERATION_FAILED=5500]="OPERATION_FAILED",pt[pt.FIREWALL_RESTRICTION=5501]="FIREWALL_RESTRICTION",pt[pt.REJOIN_FAILED=5502]="REJOIN_FAILED",pt[pt.EVENT_HANDLER_ERROR=5503]="EVENT_HANDLER_ERROR",pt[pt.VIDEO_CONTEXT_ERROR=5504]="VIDEO_CONTEXT_ERROR",pt[pt.VIDEO_ENCODE_FAILED=5505]="VIDEO_ENCODE_FAILED",pt[pt.AUDIO_ENCODE_FAILED=5506]="AUDIO_ENCODE_FAILED",pt[pt.VIDEO_DECODE_FAILED=5507]="VIDEO_DECODE_FAILED",pt[pt.AUDIO_DECODE_FAILED=5508]="AUDIO_DECODE_FAILED",pt[pt.OPERATION_ABORT=5998]="OPERATION_ABORT",pt[pt.UNKNOWN_ERROR=5999]="UNKNOWN_ERROR",pt),G4=Bo(pi({},gc),{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(dg(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(dg(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=wM(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=wM(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=wM(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=wM(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=wM(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=wM(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=wM(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 wM(A){if(!A)return"camera";let e=A.toLowerCase();return e.includes("screen")?"screen share":e.includes("audio")?"microphone":"camera"}var jeA=class Q1 extends Error{constructor(e){let{code:o,extraCode:a,message:c="",messageParams:d,fnName:C="",originError:f,data:S}=e;var b;let V;V=c||function(J){let cA,{code:CA,params:vA,enableDocLink:$A=!1}=J,he="",Oe=f2[CA];try{cA=G4[Oe]}catch{cA=G4.UNKNOWN_ERROR}return Ma(cA)?he=cA(vA):Yn(cA)&&(he=cA),vA.fnName&&!he.includes(vA.fnName)&&(he[he.length-1]!=="."&&(he+="."),he+=" thrown from ".concat(vA.fnName,"()")),$A&&(he+=" doc:"),he}({code:o===vo.SERVER_ERROR?o:a||o,params:pi({fnName:C,error:f},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=f2[o],this.code=o,this.extraCode=a,this.functionName=C,this.originError=f,this.message=V,this.data=S,this.extraCode===5302&&(b=this.originError)!=null&&b.message.includes("system")&&(this.handler=()=>{let J=document.createElement("a");qf?J.href="ms-settings:privacy-".concat({startLocalVideo:"webcam",startLocalAudio:"microphone"}[this.functionName]):KB&&(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 oi){let{stack:d}=e,C={code:vo.UNKNOWN_ERROR,fnName:o,originError:e};switch(e.getCode()){case lt.INVALID_PARAMETER:C.code=vo.INVALID_PARAMETER,C.message=e.message;break;case lt.INVALID_OPERATION:C.code=vo.INVALID_OPERATION,C.message=e.message;break;case lt.NOT_SUPPORTED:case lt.NOT_SUPPORTED_H264:C.code=vo.ENV_NOT_SUPPORTED,e.getCode()===lt.NOT_SUPPORTED_H264&&(C.extraCode=e.message.includes(gc.NOT_SUPPORTED_H264ENCODE)?5203:5204);break;case lt.JOIN_ROOM_FAILED:C.messageParams={fnParams:a};case lt.SERVER_TIMEOUT:case lt.SWITCH_ROLE_FAILED:case lt.SWITCH_ROOM_FAILED:C.code=vo.SERVER_ERROR,C.extraCode=e.getExtraCode();break;case lt.API_CALL_ABORTED:C.code=vo.OPERATION_ABORT;break;case lt.DEVICE_NOT_FOUND:case lt.DEVICE_AUTO_RECOVER_FAILED:case lt.INITIALIZE_FAILED:C.code=5300,e.name&&(C.extraCode=function(f){let S;switch(f){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 lt.VIDEO_ENCODE_FAILED:C.extraCode=5505;case lt.AUDIO_ENCODE_FAILED:C.extraCode=5506,C.code=vo.OPERATION_FAILED;break;case lt.UNKNOWN:break;default:C.code=vo.OPERATION_FAILED}c=new Q1(C),d&&(c.stack+=d.substr(d.indexOf(` +`)))}else{if(e instanceof Q1)return e;c=new Q1({code:vo.UNKNOWN_ERROR,fnName:o,originError:e})}return c}},Ro=jeA;function Vd(A){return A==="sub"?"auxiliary":A==="auxiliary"?"sub":"main"}function y2(A){return A===kk.QOS_PREFERENCE_CLEAR?"detail":A===kk.QOS_PREFERENCE_SMOOTH?"motion":""}function D2(A,e){let o=e?zP:MS;return vx(A)?pi(pi({},o),A):DC[A]?DC[A]:o}var b4={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}}},k4={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}}},qw={type:["string",HTMLElement,null,"array"],arrayItem:{instanceOf:HTMLElement},validate(A,e,o){if(Yn(A)&&!document.getElementById(A))throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5009,fnName:o,messageParams:{key:e}})}},L4={name:"userId",required:!0,type:"string"},U4={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 Kw(A,e){if(!A)throw new Ro({code:vo.INVALID_OPERATION,extraCode:5101,fnName:e})}function F4(A,e,o){if(!A)throw new Ro({code:vo.INVALID_OPERATION,extraCode:5102,fnName:e,messageParams:{value:o}})}function O4(A,e,o){if(!(/^[1-9]\d*$/.test(String(A))&&A<4294967295))throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5013,fnName:e,messageParams:{key:o}})}function P4(A,e,o){if(!/^[A-Za-z\d\s!#$%&()+\-:;<=.>?@[\]^_{}|~,]{1,64}$/.test(A))throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5012,fnName:e,messageParams:{key:o}})}function x4(A){var e;if((e=A?.option)==null||!e.small)return;if(!uM())return QA.warn("small stream is not supported"),void delete A.option.small;let o=D2(A.option.profile),a=D2(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 WeA={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 Ro({code:vo.INVALID_OPERATION,extraCode:5104,fnName:o});if(A.roomId){if(Yn(A.roomId))throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5016,fnName:o,messageParams:{key:e}});O4(A.roomId,o,e)}else{if(!A.strRoomId)throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5015,fnName:o});P4(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:qw,mute:{type:["boolean","string"]},publish:{type:"boolean"},capture:{required:!1,type:"boolean"},option:b4},validate(A){var e,o;if(((e=A?.option)==null||!e.videoTrack)&&nu())throw new Ro({code:vo.ENV_NOT_SUPPORTED,extraCode:5201});(o=A?.option)!=null&&o.small&&x4(A)}},updateLocalVideo:{name:"updateLocalVideoConfig",type:"object",required:!0,properties:{view:Bo(pi({},qw),{required:!1}),publish:{type:"boolean"},capture:{required:!1,type:"boolean"},mute:{type:["boolean","string"]},option:b4},validate(A){var e;(e=A?.option)!=null&&e.small&&x4(A)}},startLocalAudio:{name:"LocalAudioConfig",type:"object",properties:{publish:{type:"boolean"},mute:{type:["boolean","string"],values:[!0,!1,"microphone"]},muteKeepVolumeDetection:{type:"boolean"},option:U4},validate(A){var e;if(((e=A?.option)==null||!e.audioTrack)&&nu())throw new Ro({code:vo.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:U4}},startScreenShare:{name:"ScreenShareConfig",type:"object",properties:{view:qw,publish:{type:"boolean"},option:k4},validate(A,e,o,a,c){var d;if((d=A?.option)==null||!d.videoTrack){if(nu())throw new Ro({code:vo.ENV_NOT_SUPPORTED,extraCode:5201});if(!Lp())throw new Ro({code:vo.ENV_NOT_SUPPORTED,fnName:o,extraCode:5205})}}},updateScreenShare:{name:"updateScreenShareConfig",type:"object",required:!0,properties:{view:qw,publish:{type:"boolean"},option:k4}},muteRemoteAudio:[L4,{name:"mute",required:!0,type:"boolean"}],setRemoteAudioVolume:[L4,{name:"volume",required:!0,type:"number",min:0}],startRemoteVideo:{name:"startRemoteVideoConfig",type:"object",required:!0,properties:{view:qw,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){Kw(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(F4(!!a,o,A),a&&(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary))throw new Ro({code:vo.INVALID_OPERATION,extraCode:5103,fnName:o,messageParams:{value:A}})}},updateRemoteVideo:{name:"updateRemoteVideoConfig",type:"object",required:!0,properties:{view:Bo(pi({},qw),{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){Kw(this._room.isJoined,o);let a=this._room.remotePublishedUserMap.get(A.userId);if(F4(!!a,o,A),a){if(A.streamType==="main"&&!a.muteState.videoAvailable||A.streamType==="sub"&&!a.muteState.hasAuxiliary)throw new Ro({code:vo.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 Ro({code:vo.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!=="*"&&xe(A.streamType))throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5014,fnName:o})}},switchRole:{name:"role",required:!0,values:["anchor","audience"],validate(A,e,o){Kw(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(!lk)throw new Ro({code:vo.ENV_NOT_SUPPORTED,fnName:o,extraCode:5207});if(!this._room.enableSEI)throw new Ro({code:vo.INVALID_OPERATION,fnName:o,extraCode:5108});if(A.byteLength>1e3)throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5017,messageParams:{key:e},fnName:o});Kw(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 Ro({code:vo.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 Ro({code:vo.INVALID_PARAMETER,extraCode:5018,fnName:o});if(A.byteLength===0)throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5017,fnName:o,messageParams:{key:e}})}}},validate(A,e,o){if(Kw(this._room.isJoined,o),this._room.scene==="live"&&this._room.role==="audience")throw new Ro({code:vo.INVALID_OPERATION,extraCode:5107,fnName:o,messageParams:{key:e}})}},switchRoom:{name:"switchRoomConfig",type:"object",required:!0,validate(A,e,o){if(Kw(this._room.isJoined,o),this._room.useStringRoomId&&A.strRoomId===this._room.roomId||!this._room.useStringRoomId&&A.roomId===Number(this._room.roomId))throw new Ro({code:vo.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 Ro({code:vo.INVALID_PARAMETER,extraCode:5019,fnName:o,messageParams:{key:this._room.useStringRoomId?"strRoomId":"roomId"}});if(A.roomId)O4(A.roomId,o,e);else{if(!A.strRoomId)throw new Ro({code:vo.INVALID_PARAMETER,extraCode:5015,fnName:o});P4(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}}}},Kl={TRTC:WeA},Jd=class extends Error{};function zeA(A,e){let o=Pf(A);for(let a=0;a!0),Y(this,"mergeUpdate",zeA);let a=a_.instances.get(e);a?a.set(o,this):a_.instances.set(e,new Map([[o,this]]))}static get(e,o){if(!o)return;let a=a_.instances.get(e);return a&&a.get(o)||new a_(e,o)}static gets(e,o){let a=a_.instances.get(e),c=[];return a&&a.forEach((d,C)=>{o.test(C)&&c.push(d)}),c}action(e,o,a){let c=f=>{var S;return e===0?this.started=!0:e===3&&(this.started=!1),this.ops.shift(),(S=this.currentOp)==null||S.action(),f},d=f=>{var S,b;throw this.ops.shift(),e===0&&((S=this.currentOp)==null?void 0:S.type)===2&&this.ops.shift().reject(new Jd("start failed")),(b=this.currentOp)==null||b.action(),f},C={type:e,action:()=>o(...C.args).then(c,d),args:a,resolve:ZeA,reject:XeA};try{switch(this.state){case 1:if(e===0)throw new Jd("already started");break;case 4:if(e===2)throw new Jd("not started");break;default:return this.cacheOp(C)}}catch(f){return Promise.reject(f)}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 Jd("already start");break;case 3:switch(e.type){case 2:throw new Jd("update not allowed when stopping");case 3:return this.currentOp.promise}break;default:throw new Jd("unknown state")}else switch(e.type){case 3:if(this.lastOpType===3)return this.lastOp.promise;{let a=new Jd("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 Jd("update not allowed after stop")}break;case 0:switch(this.lastOpType){case 2:throw new Jd("start not allowed after update");case 0:throw new Jd("duplicate start");case 3:if(this.startSame(this.currentOp.args,e.args))throw this.ops.pop().reject(new Jd("keep start")),new Jd("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(Y4,"instances",new WeakMap);var Lk=Y4,S2=new WeakMap,M2=(A,e)=>{if(e instanceof Jd){let{stack:o}=e;e=new Ro({code:vo.OPERATION_ABORT,message:"".concat(A," abort: ").concat(e.message),fnName:A}),o&&(e.stack+=o.substr(o.indexOf(` +`)))}throw e};function _M(A,e){return Hr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;Cfunction(){for(var C=arguments.length,f=new Array(C),S=0;S{var vA,$A;let he=(vA=S2.get(this))==null?void 0:vA.get(J(...f));if(he){let{timeoutId:Se,resolve:fi}=he;clearTimeout(Se),fi()}let Oe=setTimeout(()=>{if(b.state===3||b.state===4)return cA();b.action(2,c.bind(this),f).catch(M2.bind(null,d)).then(cA,CA)},V);S2.has(this)?($A=S2.get(this))==null||$A.set(J(...f),{timeoutId:Oe,resolve:cA}):S2.set(this,new Map([[J(...f),{timeoutId:Oe,resolve:cA}]]))})}return b.action(2,c.bind(this),f).catch(M2.bind(null,d))})}function TM(A){return Hr((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 f=Lk.get(this,C);return f?f.action(3,e.bind(this),c).catch(M2.bind(null,o)):e.apply(this,c)})}function NM(){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(kh,"/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"},$eA=new Set([Hi.AUDIO_VOLUME,Hi.AUDIO_FRAME,Hi.NETWORK_QUALITY,Hi.STATISTICS,Hi.SEI_MESSAGE,Hi.CUSTOM_MESSAGE,Hi.LAYER_DATA]),V4={};bh(V4,{ScheduleRequestType:()=>q4,getAbilityConfig:()=>AtA,getScheduleDomain:()=>nK,isNeedToSchedule:()=>Uk,scheduleProxy:()=>Hp,sendScheduleRequest:()=>H4,setIsNeedToSchedule:()=>rQ,setScheduleProxy:()=>sK});var v2=null,R2=0,J4=72e5,w2="trtc_schedule_cache",Uk=!0;function rQ(A){wr(A)&&A!==Uk&&(Uk=A,QA.info("setIsNeedToSchedule ".concat(A)),A?function(){if(typeof window<"u"&&typeof localStorage<"u")try{localStorage.removeItem(w2)}catch(e){QA.error("clearScheduleCache error",e)}}():R2=Date.now()+J4)}function H4(A){return jA(this,arguments,function(e){let{userId:o,sdkAppId:a,useStringRoomId:c,roomId:d,userSig:C,version:f,frameWorkType:S,role:b,latencyLevel:V}=e;return function*(){var J;if(!Uk&&v2&&R2>Date.now())return{isCached:!0,result:v2};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(c)),CA.append("groupId",String(d)),CA.append("sdkVersion",f),CA.append("userSig",String(C));let vA=((J=yield iM())==null?void 0:J.model)||Vb();vA&&CA.append("model",vA);let $A=Np();$A&&CA.append("osString",$A);let he=_p();he&&CA.append("gpu",he),b&&CA.append("role",String(b)),V&&CA.append("latencyLevel",String(V)),S&&CA.append("frameWorkType",String(S));let Oe=bo(),Se=yield function(Ne,dt,Ci){return new Promise((yi,Yo)=>{let Vo=null;OS([K4(Qn=>dt.count[0]=Qn+1,Qn=>{let{error:Jo,retry:Ts,retriedCount:Qg,retryFuncArgs:ma}=Qn;dt.msg[0]=Jo.message,Vo||(Qg>=1&&(ma[0]=dy(Ci,"config",VA.MAIN,!0)),Ts())})(dy(Ci,"config",VA.MAIN),Ne,{get timeout(){return 1e3*Uf(2+dt.count[0])}}),K4(Qn=>dt.count[1]=Qn+1,Qn=>{let{error:Jo,retry:Ts,retriedCount:Qg,retryFuncArgs:ma}=Qn;dt.msg[1]=Jo.message,Vo||(Qg>=2&&(ma[0]=dy(Ci,"config",VA.BACKUP,!0)),Ts())})(dy(Ci,"config",VA.BACKUP),Ne,{get timeout(){return 1e3*Uf(2+dt.count[1])}})]).then(Qn=>{Vo=Qn,yi(Vo)}).catch(Yo)})}(CA,cA,a);Se.config&&(Se.config.loggerDomain&&DS(Se.config.loggerDomain),wr(Se.config.scheduleCache)&&rQ(!Se.config.scheduleCache)),cA.delta=bo()-Oe;let fi=function(Ne,dt,Ci){let yi={totalCost:0,local:0,dns:0,tcp:0,tls:0,request:0,response:0};try{let Yo=performance.getEntriesByType("resource"),Vo=dy(Ne,"config",VA.MAIN),Qn=dy(Ne,"config",VA.BACKUP);for(let Jo of Yo)if(Jo.startTime>=Ci&&(Jo.name===Vo||Jo.name===Qn)&&Jo.transferSize>0){let Ts=Jo.name===Vo?VA.MAIN:VA.BACKUP,Qg=Math.round(Jo.duration),ma=Math.round(Jo.domainLookupStart-Jo.startTime),gu=Jo.redirectStart>0?Math.round(Jo.redirectEnd-Jo.redirectStart):0,Yk=Jo.fetchStart>0?Math.round(Jo.domainLookupStart-Jo.fetchStart):0,$w=Math.round(Jo.domainLookupEnd-Jo.domainLookupStart),q5=Math.round(Jo.requestStart-Jo.secureConnectionStart),K5=Math.round(Jo.secureConnectionStart-Jo.connectStart),j5=Math.round(Jo.responseStart-Jo.requestStart),W5=Math.round(Jo.responseEnd-Jo.responseStart),viA=[$w,q5,K5,j5,W5];on.uploadEvent({log:"stat-schedule-net:".concat(Qg,"(").concat(ma,"(").concat(gu,"->").concat(Yk,")->").concat(viA.join("->"),") ").concat(Ts),userId:dt}),yi=Bo(pi({},yi),{totalCost:Qg,local:ma,dns:$w,tcp:K5,tls:q5,request:j5,response:W5});break}}catch(Yo){QA.error("getScheduleDetailCost error",Yo)}return yi}(Number(a),o,Oe);return v2=Se,function(Ne){if(typeof window<"u"&&typeof localStorage<"u")try{let dt=Date.now()+J4;localStorage.setItem(w2,JSON.stringify({result:Ne,expireIn:dt})),R2=dt}catch(dt){QA.error("saveScheduleToLocalStorage error",dt)}}(Se),{isCached:!1,result:Se,detailCost:fi}}catch(CA){let vA=va(CA)?CA[0]:CA,$A=bn(vA.code)?vA.code:0,he="schedule failed".concat(vA.message?": ".concat(vA.message):""),Oe=new oi({code:lt.SCHEDULE_FAILED,extraCode:$A,message:Zo({key:So.JOIN_ROOM_FAILED,data:{error:he,code:$A}})});throw QA.error(he,$A),Oe}}()})}typeof document<"u"&&document.head.insertAdjacentHTML("beforeend",Object.values(YB).map(A=>'')).join(`\r +`)),function(){if(typeof window<"u"&&typeof localStorage<"u")try{let A=localStorage.getItem(w2);if(A){let{result:e,expireIn:o}=JSON.parse(A);o>Date.now()?(v2=e,R2=o,Uk=!1):localStorage.removeItem(w2)}}catch(A){QA.error("loadScheduleFromLocalStorage error",A)}}(),U.on("28",()=>rQ(!0)),U.on("63",()=>rQ(!0)),U.on("84",()=>rQ(!0)),U.on("201",A=>{A.state==="RECONNECTING"&&rQ(!0)}),U.on("202",A=>{A.state==="RECONNECTING"&&rQ(!0)});var Hp={main:"",backup:""};function sK(A){va(A)?(Hp.main=A[0],Hp.backup=A[1]):(Hp.main=A,Hp.backup=A)}var q4=(A=>(A.CONFIG="config",A.TRTC_AUTO_CONF="trtcAutoConf",A.AUDIO_AI_AUTH="audioAiAuth",A))(q4||{});function dy(A,e){let o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:VA.MAIN,a=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return"https://".concat(Hp[o]||nK(A,o,a),"/api/v1/").concat(e)}function AtA(A,e,o){let a=dy(A,e),c=dy(A,e,VA.BACKUP),d=new URLSearchParams(o).toString(),C=fetch("".concat(a,"?").concat(d)).then(S=>S.json()),f=fetch("".concat(c,"?").concat(d)).then(S=>S.json());return OS([C,f])}function nK(A){let e,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:VA.MAIN,a=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return e=Ld(A)?a?o===VA.MAIN?YB.MAIN_OVERSEA_BACKUP:YB.BACKUP_OVERSEA:o===VA.MAIN?YB.MAIN_OVERSEA:YB.BACKUP_OVERSEA:o===VA.MAIN?YB.MAIN:YB.BACKUP,e}function etA(A,e,o){return new Promise((a,c)=>{HB({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 K4=(A,e)=>JS({retryFunction:etA,settings:{retries:3,timeout:0},onError:e,onRetrying:A}),rK=class{constructor(){Y(this,"_log"),this._log=QA.createLogger({id:"fd"})}download(A,e){return jA(this,null,function*(){let{type:o="blob"}=e||{};A=Bb(A);try{let a,c=bo();if(a=Ma(fetch)?yield this.downloadWithFetch(A,o):yield this.downloadWithXHR(A,o),!a||!a.data)throw new Error("data is empty");let d=bo()-c;return this._log.info("downloaded: ".concat(A,", return type: ").concat(o,", cost: ").concat(d,"ms")),Ai.addSuccessEvent({key:522700,cost:bo()-c}),a.data}catch(a){throw this._log.error("failed to download: ".concat(A,", error: ").concat(a)),Ai.addFailedEvent({key:522700,error:a}),a}})}downloadWithFetch(A,e){return jA(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 jA(this,null,function*(){this._log.info("loadWasm ".concat(A,", importObject: ").concat(JSON.stringify(e)));let o=bo(),a=null,c=null;if(Ma(WebAssembly.instantiateStreaming)&&!A.startsWith("data:application/octet-stream;base64,")&&!(d=>d.startsWith("file://"))(A)&&Ma(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=bo()-o;return this._log.info("loadedWasm ".concat(A,", cost: ").concat(d,"ms")),Ai.addSuccessEvent({key:522701,cost:d}),a}throw this._log.error("failed to loadWasm ".concat(A,", error: ").concat(c)),Ai.addFailedEvent({key:522701,error:c}),c})}loadScript(A){this._log.info("loadScript ".concat(A));let e=bo();return new Promise((o,a)=>{let c=document.createElement("script");c.type="text/javascript",c.onload=()=>{this._log.info("loadedScript ".concat(A,", cost: ").concat(bo()-e,"ms")),Ai.addSuccessEvent({key:522702,cost:bo()-e,split:1e3}),o(c)},c.onerror=d=>{this._log.error("failed to loadScript ".concat(A,", error: ").concat(d?.message||JSON.stringify(d))),Ai.addFailedEvent({key:522702}),a(d)},c.crossOrigin="anonymous",c.src=A,document.head.append?document.head.append(c):document.getElementsByTagName("head")[0].appendChild(c)})}};di([Yh({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))}})],rK.prototype,"download"),di([Yh({settings:{timeout:3e3,retries:3},onRetrying(A){this._log.warn("loadScript retrying: ".concat(A))}})],rK.prototype,"loadScript");var aK=new rK;function j4(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),f=new DataView(C),S=new DataView(e.data),b=0;for(let V=0;Vc.isSEI);o?.(a.reverse())}catch{}return e}function A5(A){let{seiMessageList:e,isAudio:o,getNtpTime:a,isMain:c}=A;return new TransformStream({transform(d,C){let f=d;o?audioEncodePipeline.forEach(S=>{f=S({frame:f,ntp:a(),onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:f.data,userId:""})}})}):videoEncodePipeline.forEach(S=>{f=S({frame:f,seiMessageList:e,onDump:()=>{self.postMessage({type:"dump",isAudio:o,data:f.data,userId:"",streamType:c?"main":"auxiliary"})}})}),C.enqueue(f)}})}function e5(A){let{userId:e,streamType:o,isAudio:a}=A;return new TransformStream({transform(c,d){let C=c;a?(audioDecodePipeline.forEach(f=>{C=f({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(f=>{C=f({frame:C,onSEI:S=>{S.forEach(b=>{self.postMessage({type:"sei",seiPayloadType:b.seiPayloadType,data:b.seiPayload.buffer,userId:e,streamType:o})})},onDump:()=>{self.postMessage({type:"dump",isAudio:a,data:C.data,userId:e,streamType:o})}})}),d.enqueue(C)}})}function t5(A){let e=[B2],o=[Z4,W4,f4,z4,j4,A5,e5,gw,VS,h2],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(` +`),` +`).concat(o.map(S=>S.toString()).join(` +`),";(").concat(()=>{let S=[],b=[],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)):b.push(cA.data.data);break;case"ntp-offset":J=cA.data.data}},self.onrtctransform=cA=>{let{options:CA}=cA.transformer,vA=CA.isReceiver?e5({userId:CA.userId,streamType:CA.streamType,isAudio:CA.isAudio}):A5({getNtpTime:()=>Date.now()+J,isAudio:CA.isAudio,isMain:CA.isMain,seiMessageList:CA.isMain?CA.small?V:S:b});cA.transformer.readable.pipeThrough(vA).pipeTo(cA.transformer.writable)}},")();").concat(a,"})()"),d=new Blob([c],{type:"text/javascript"}),C=URL.createObjectURL(d),f=new Worker(C);return URL.revokeObjectURL(C),f}var i5,gK=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(mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.on(mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.on(mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.on(mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.on(mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.on(mo.VOLUME_CHANGE,this.handleVolumeChange,this)}handleUserResumeInPIPOrFullScreen(){this.audioPlayer.isPaused&&(this.log.warn("resume audio in ".concat(this.videoPlayer.isPictureInPicture()?"pip":"fullscreen")),this.audioPlayer.doResume()),Ja&&Wf&&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"),Ja&&Wf?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(mo.USER_RESUME_IN_PIP_OR_FULL_SCREEN,this.handleUserResumeInPIPOrFullScreen,this),this.videoPlayer.off(mo.USER_PAUSE_IN_PIP_OR_FULL_SCREEN,this.handleUserPauseInPIPOrFullScreen,this),this.videoPlayer.off(mo.ENTER_PICTURE_IN_PICTURE,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mo.ENTER_FULL_SCREEN,this.handleEnterPIPOrFullScreen,this),this.videoPlayer.off(mo.LEAVE_PICTURE_IN_PICTURE,this.handleLeavePIP,this),this.videoPlayer.off(mo.LEAVE_FULL_SCREEN,this.handleLeaveFullScreen,this),this.videoPlayer.off(mo.VOLUME_CHANGE,this.handleVolumeChange,this)}},o5=!1;function ttA(A){var e=this;let{TRTC:o,room:a,errorModule:c,assetsPath:d}=A;return{TRTC:o,LocalMixVideoTrack:AK,LocalVideoTrack:sQ,LocalScreenTrack:vM,room:a,assetsPath:d,fileDownloader:aK,innerEmitter:U,INNER_EVENT:nA,constants:HP,environment:Rx,utils:D4,eventLogger:on,log:this.room.getLogger(),loggerManager:QA,errorModule:c,kvStatManager:Ai,rtcDectection:te,trtc:this,rx:$W,enums:be,schedule:V4,getDevices:r2,initVisionTaskRegistry:function(C,f){let S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"/mediapipe/vision.js";return jA(e,null,function*(){!window.VisionTaskRegistry&&!o5&&(o5=!0,i5=aK.loadScript("".concat(C,"/").concat(S).replace(/([^:]\/)\/+/g,"$1"))),yield i5,yield(yield window.VisionTaskRegistry.getInstance(C)).preloadModels(f)})},audioContext:NI(),deviceDetector:Oc,AudioPlayer:Oq,RemoteAudioPlayer:KW,VideoPlayer:Mo,showAutoPlayDialog:TC,Timer:_r,clearStarted:(C,f)=>{let S=C.getAlias(),b=Lk.instances.get(this);if(b)if(f){let V=b.get(S+f);if(!V)return;V.started=!1}else b.forEach((V,J)=>{J.startsWith(S)&&(V.started=!1)})},startGetPCM:oK,createAudioNode:o2,getNetworkTimeOffset:VP,validateSourceNode:()=>{var C;if(er&&((C=this.room.audioManager._localAudioPipline)==null||!C.source.node))throw new Ro({code:vo.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:t5,AVPlayerStateSyncManager:gK,PlayerEvent:mo}}var Ww=new WeakMap,s5="5.15.3-beta.12";function au(){for(var A=arguments.length,e=new Array(A),o=0;ofunction(){for(var d=arguments.length,C=new Array(d),f=0;ffunction(){for(var d=arguments.length,C=new Array(d),f=0;fOf(V)?FS(V):Yn(V)?V:dg(V))},value:o}})}else if(!xe(e.type)&&dg(o)!==e.type)throw new Ro(C(5002));if(e.allowEmpty===!1){let b=bn(o)&&(o===0||Number.isNaN(o)),V=Yn(o)&&o.trim()==="";if(b||V)throw new Ro(C(5003))}if(e.notLessThanZero&&bn(o)&&o<0)throw new Ro(C(5006));if(!xe(e.min)&&bn(o)&&oe.max)throw new Ro(C(5008));if(Yn(e.instanceOf)){if(!o||o._name!==e.instanceOf)throw new Ro(C(5004))}else if(Ma(e.instanceOf)&&!(o instanceof e.instanceOf))throw new Ro(C(5004));if(Array.isArray(e.values)&&!e.values.includes(o))throw new Ro(C(5005));let{properties:f}=e;eE(f)&&xE(o)&&Object.keys(f).forEach(b=>{_2.call(this,{rule:f[b],value:o&&o[b],key:"".concat(b),fnName:c,className:d})});let{arrayItem:S}=e;eE(S)&&va(o)&&o.forEach((b,V)=>{_2.call(this,{rule:S,value:b,key:"".concat(a,"[").concat(V,"]"),fnName:c,className:d})}),Ma(e.validate)&&e.validate.call(this,o,a,c,d,this)}var itA=0;function pa(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{getRemoteId:e=()=>"",replaceArg:o,getKVReportKey:a,ignoreLog:c,ignoreErrorLog:d}=A;return Hr((C,f)=>function(){for(var S=arguments.length,b=new Array(S),V=0;V0?$A.info("".concat(f,"() ").concat(he," ").concat(JSON.stringify(b,(fi,Ne)=>vA(fi,Ne,["userSig","privateMapKey"])))):$A.info("".concat(f,"() ").concat(he));let Oe=a?a(...b):Jx[f],Se=d?.(...b)||!1;try{let fi=C.apply(this,b),Ne=bo();if(Ff(fi)){let dt="".concat(f.includes("Plugin")?"".concat(((cA=(J=b[0]).getName)==null?void 0:cA.call(J))||""," "):" ");return fi.then(Ci=>($A.info("".concat(f,"() success ").concat(he," ").concat(dt).concat(e.call(this,...b))),Ai.addSuccessEvent({key:Oe,cost:bo()-Ne}),Ci)).catch(Ci=>{var yi;let Yo=(Ci=Ro.convertFrom.call(this,Ci,f,b.length===1?b[0]:b)).extraCode||Ci.code,Vo=(yi=Ci.message)!=null&&yi.includes(Yo)?"":" code:".concat(Yo),Qn=Ci?.code===vo.OPERATION_ABORT;throw Se||$A[Qn?"warn":"error"]("".concat(f,"() failed ").concat(he," ").concat(dt).concat(e.call(this,...b)," ").concat(Ci).concat(Vo," params: ").concat(JSON.stringify(b,vA))),Ai.addFailedEvent({key:Oe,error:Ci}),Ci})}return Ai.addSuccessEvent({key:Oe}),fi}catch(fi){let Ne=(fi=Ro.convertFrom.call(this,fi,f)).extraCode||fi.code,dt=(CA=fi.message)!=null&&CA.includes(Ne)?"":" code:".concat(Ne),Ci=fi?.code===vo.OPERATION_ABORT;throw Se||$A[Ci?"warn":"error"]("".concat(f,"() failed ").concat(he," ").concat(fi).concat(dt," params: ").concat(JSON.stringify(b,vA))),Ai.addFailedEvent({key:Oe,error:fi}),fi}})}var lK,IK=A=>Hr((e,o)=>function(a,c){return jA(this,null,function*(){let d=this._plugins.get(a);if(!d)throw this._log.error("plugin ".concat(String(a)," is not found")),new Ro({code:vo.OPERATION_ABORT,message:"plugin ".concat(String(a)," is not found"),fnName:o});if(Ma(d.constructor.isSupported)&&!d.constructor.isSupported())throw this._log.error("plugin ".concat(String(a)," is not supported")),new Ro({code:vo.ENV_NOT_SUPPORTED,message:"plugin ".concat(String(a)," is not supported"),extraCode:5210,fnName:o});return cK.call(this,d.getValidateRule(A),[c],o,"TRTC"),e.call(this,d,c)})}),uK=0,T2=class eL{constructor(e){this.core=e,Y(this,"log"),Y(this,"customAudioReferenceMap",new Map),Y(this,"audioRefId",0),Y(this,"audioContext",NI()),Y(this,"localAudioWorkletNode"),Y(this,"screenAudioWorkletNode"),Y(this,"mixNode"),Y(this,"silentNode"),uK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(uK)}),this.log.info("created id=".concat(this.getAlias()).concat(uK)),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 Ro({code:vo.INVALID_OPERATION,extraCode:5106,fnName:c})}}}preload(e){return lK||(lK=this.doPreload(e)),lK}doPreload(e){return jA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Yg(this.audioContext,a)}catch(c){this.log.error("preload audioProcessor failed. ".concat(c))}finally{URL.revokeObjectURL(a)}})}getName(){return eL.Name}getAlias(){return"ap"}getGroup(){return"ap"}getValidateRule(e){switch(e){case"start":return eL.getStartValidateRule(this.core);case"update":return eL.updateValidateRule;case"stop":return eL.stopValidateRule}}start(e){return jA(this,null,function*(){var o,a,c,d;let{room:C}=this.core,{sdkAppId:f,userId:S,userSig:b,assetsPath:V=this.core.assetsPath,audioReference:J,processLevel:cA,enableDump:CA,isLocalAudioNeedAudioProcess:vA=!0,isScreenAudioNeedAudioProcess:$A=!1}=e;if(this.core.room.audioManager.isLocalAudioNeedAudioProcess=vA,this.core.room.audioManager.isScreenAudioNeedAudioProcess=$A,!V)throw new Ro({code:vo.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")),vA&&!this.localAudioWorkletNode){let{sign:he,status:Oe,timestamp:Se}=yield this.getAuthData(f,S,b);this.localAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.localAudioWorkletNode,"localAudio",f,S,Se,he,Oe,C)}if($A&&!this.screenAudioWorkletNode){let{sign:he,status:Oe,timestamp:Se}=yield this.getAuthData(f,S,b);this.screenAudioWorkletNode=new AudioWorkletNode(this.audioContext,"trtc-audio-processor",{numberOfInputs:2,numberOfOutputs:1}),this.initWorkletNode(this.screenAudioWorkletNode,"screenAudio",f,S,Se,he,Oe,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),xe(J)||J.forEach(he=>{this.customAudioReferenceMap.set(he,"o-".concat(this.audioRefId++)),this.core.room.audioManager.updateAudioReference({type:"add",audioReference:he,refId:"o-".concat(this.audioRefId++)})}),xe(cA)||(c=this.localAudioWorkletNode)==null||c.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:cA}}),xe(CA)||(d=this.localAudioWorkletNode)==null||d.port.postMessage({type:"dump",data:{enable:CA}})})}update(e){return jA(this,null,function*(){var o,a,c;let{audioReference:d,enableDump:C,processLevel:f}=e;xe(d)||(this.customAudioReferenceMap.forEach((S,b)=>{this.customAudioReferenceMap.delete(b),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++)})})),xe(f)||(o=this.localAudioWorkletNode)==null||o.port.postMessage({type:"setConfig",data:{aecEnable:1,aecNlpLevel:f}}),xe(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 jA(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 jA(this,null,function*(){let c=String(Date.now()).slice(0,-3),{auth:d,sign:C,status:f,message:S}=yield function(b){return jA(this,arguments,function(V){let{sdkAppId:J,userId:cA,userSig:CA,timestamp:vA}=V;return function*(){let $A="".concat(function(Yo){let Vo=arguments.length>1&&arguments[1]!==void 0?arguments[1]:VA.MAIN;return"https://".concat(Hp[Vo]||nK(Yo,Vo),"/api/v1/audioAiAuth")}(J),"?sdkAppId=").concat(J,"&userId=").concat(cA,"&userSig=").concat(CA,"×tamp=").concat(vA),he=yield fetch($A),{data:{errCode:Oe,errMsg:Se,sign:fi,status:Ne}}=yield he.json();if(Ne==="1")return{auth:!0,sign:fi,status:Ne,message:Se};let dt=Ld(J)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",Ci="Init RTCAudioProcessor failed.",yi="";switch(Oe){case 1:yi="Please check your params.";break;case 2:yi="You need to buy packages. Refer to: ".concat(dt);break;case 3:yi="Server is invalid. Please contact our engineer. ";break;case 4:yi="Your packages is not active. Refer to: ".concat(dt);break;case 5:yi="Your packages is expired. Refer to: ".concat(dt);break;case 6:yi="Your version is not supported."}return{auth:!1,status:Ne,message:Se?"".concat(Ci," Reason: ").concat(Se,". ").concat(yi):"".concat(Ci,", ").concat(yi)}}()})}({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 Ro({code:vo.INVALID_PARAMETER,message:S});return{sign:C,status:f,timestamp:c}})}initWorkletNode(e,o,a,c,d,C,f,S){e.port.postMessage({type:"init",data:{sdkAppId:String(a),userId:c,timestamp:d,sign:C,status:f}}),e.port.onmessage=b=>{var V;let{data:J}=b;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(HG(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 U.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(Dw()?ZB():Np()))}}}handleLocalAudioStarted(e){return jA(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 jA(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(T2,"updateValidateRule",{type:"object"}),Y(T2,"stopValidateRule",{type:"object"}),Y(T2,"Name","AudioProcessor");var otA=T2,EK=0,stA=class{constructor(A,e){Y(this,"audioObjectURL"),Y(this,"player"),Y(this,"publisher"),Y(this,"mixInput"),this.mixInput=new PW(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&&(xe(A.volume)||(this.volume=A.volume),xe(A.loop)||(this.loop=A.loop),xe(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 jA(this,null,function*(){if(A.url){let e=yield aK.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 zw(A,e){if(e&&typeof e!="function")throw new Ro({code:vo.INVALID_PARAMETER,message:"start audioMixer plugin: param ".concat(A," should be a function.")})}var Fk=class tL{constructor(e){this.core=e,Y(this,"log"),Y(this,"mixedMusicMap",new Map),Y(this,"cacheMusicMap",new Map),EK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(EK)}),this.log.info("created id=".concat(this.getAlias()).concat(EK))}getName(){return tL.Name}getAlias(){return"ax"}getGroup(e){return e?.id}getValidateRule(e){switch(e){case"start":return tL.startValidateRule;case"update":return tL.updateValidateRule;case"stop":return tL.stopValidateRule}}start(e){return jA(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 stA(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.")),Ai.addEnum({key:502700,value:3}),this.kvUpload(e)})}handleAutoPlayFailed(e,o,a){return jA(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(()=>{U.off("154",c,this)})};U.on("154",c,this),TC()}else this.core.trtc.emit(Hi.AUTOPLAY_FAILED,{userId:"",mediaType:"audio",resume:()=>jA(this,null,function*(){return e.play()})})}})}update(e){return jA(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),xe(a)||C.setOperation(a),xe(c)||C.seek(c),this.kvUpload(e)):this.log.warn("update music source failed, music id: ".concat(o," not found."))})}stop(e){return jA(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:f,onTimeUpdate:S,onDurationChange:b,onEnded:V}=e;o&&Ai.addCount({key:502009}),a&&Ai.addCount({key:502001}),c&&Ai.addCount({key:502002}),d&&Ai.addCount({key:502003}),C&&Ai.addCount({key:502004}),f&&Ai.addCount({key:502005}),typeof S!="function"&&Ai.addCount({key:502007}),typeof V!="function"&&Ai.addCount({key:502008}),typeof b!="function"&&Ai.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(Fk,"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,f=a.startsWith("blob"),S=a.startsWith("data");if(!(C||f||S))throw new Ro({code:vo.INVALID_PARAMETER,message:"start audioMixer plugin: music url is invalid, please check your file format.",fnName:o})}if(!A.url&&!A.track)throw new Ro({code:vo.INVALID_PARAMETER,message:"start audioMixer plugin: param url or track is required.",fnName:o});zw("onTimeUpdate",A.onTimeUpdate),zw("onEnded",A.onEnded),zw("onDurationChange",A.onDurationChange)}}),Y(Fk,"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){zw("onTimeUpdate",A.onTimeUpdate),zw("onEnded",A.onEnded),zw("onDurationChange",A.onDurationChange)}}),Y(Fk,"stopValidateRule",{name:"options",type:"object",required:!0,properties:{id:{type:"string",required:!0}}}),Y(Fk,"Name","AudioMixer");var dK,ntA=Fk,CK=0,N2=class iL{constructor(e){this.core=e,Y(this,"log"),Y(this,"audioContext",NI()),Y(this,"workletNode"),Y(this,"config",{enableFarFieldReduce:!1,farFieldReduceThreshold:.5}),CK+=1,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(CK)}),this.log.info("created id=".concat(this.getAlias()).concat(CK))}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 Ro({code:vo.INVALID_OPERATION,extraCode:5106,fnName:c})}}}preload(e){return dK||(dK=this.doPreload(e)),dK}doPreload(e){return jA(this,null,function*(){let o=yield this.core.fileDownloader.download(e,{type:"blob"}),a=URL.createObjectURL(o);try{yield Yg(this.audioContext,a)}catch(c){throw this.log.error("load worklet failed",c),c}finally{URL.revokeObjectURL(a)}})}getName(){return iL.Name}getAlias(){return"ad"}getGroup(){return"AIDenoiser"}getValidateRule(e){switch(e){case"start":return iL.startValidateRule(this.core);case"update":return iL.updateValidateRule;case"stop":return iL.stopValidateRule}}start(e){return jA(this,null,function*(){let{room:o,schedule:a}=this.core,{assetsPath:c=this.core.assetsPath}=e;if(!c)throw new Ro({code:vo.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(dM()?"":"-nosimd",".js")),!this.workletNode){let d=String(Date.now()).slice(0,-3),{auth:C,sign:f,status:S,message:b}=yield function(V,J){return jA(this,arguments,function(cA,CA){let{sdkAppId:vA,userId:$A,userSig:he,timestamp:Oe}=CA;return function*(){try{let{data:{errCode:Se,errMsg:fi,sign:Ne,status:dt}}=yield cA.getAbilityConfig(vA,cA.ScheduleRequestType.AUDIO_AI_AUTH,{sdkAppId:vA,userId:$A,userSig:he,timestamp:Oe});if(dt==="1")return{auth:!0,sign:Ne,status:dt,message:fi};let Ci=Ld(vA)?"https://trtc.io/document/42734?platform=web&product=rtcengine&menulabel=coresdk":"https://cloud.tencent.com/document/product/647/44247",yi="Init RTCAIDenoiser failed.",Yo="";switch(Se){case 1:Yo="Please check your params.";break;case 2:Yo="You need to buy packages. Refer to: ".concat(Ci);break;case 3:Yo="Server is invalid. Please contact our engineer. ";break;case 4:Yo="Your packages is not active. Refer to: ".concat(Ci);break;case 5:Yo="Your packages is expired. Refer to: ".concat(Ci);break;case 6:Yo="Your version is not supported."}return{auth:!1,status:dt,message:fi?"".concat(yi," Reason: ").concat(fi,". ").concat(Yo):"".concat(yi,", ").concat(Yo)}}catch(Se){return{auth:!1,status:"0",message:"Init RTCAIDenoiser failed. All requests failed. ".concat(Se)}}}()})}(a,Bo(pi({},e),{timestamp:d}));if(!C)throw this.log.info("RTCAIDenoiser: ".concat(e.userId," auth result: ").concat(C,". Message: ").concat(b)),new Ro({code:vo.INVALID_PARAMETER,message:b});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:f,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(HG(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 jA(this,null,function*(){this.updateConfig(e)})}stop(){return jA(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;xe(e.mode)||(e.mode===0?this.config.enableFarFieldReduce=!1:e.mode===1&&(this.config.enableFarFieldReduce=!0),o=!0),xe(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(N2,"updateValidateRule",{type:"object",properties:{mode:{type:"number",required:!1,values:[0,1]},farFieldReduceThreshold:{type:"number",required:!1,min:0,max:1}}}),Y(N2,"stopValidateRule",{type:"object"}),Y(N2,"Name","AIDenoiser");var rtA=N2,atA=ac(Jl(),1),gtA=class extends atA.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 jA(this,null,function*(){if(!this.observer)try{"PressureObserver"in window&&!Ja&&(this.observer=new PressureObserver(this.onPressureChange),yield this.observer.observe("cpu",{sampleInterval:2e3}))}catch(A){on.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){on.uploadEvent({log:"stat-pressure-detector-destroy-failed",error:e})}}},r5=new gtA,hK=0,BK=class M6{constructor(e){this.core=e,Y(this,"log"),Y(this,"_seiMessageList",[]),Y(this,"_smallSeiMessageList",[]),Y(this,"_subStreamSeiMessageList",[]),hK++,this.log=e.log.createChild({id:"".concat(this.getAlias()).concat(hK)}),this.log.info("[sei] created id=".concat(this.getAlias()).concat(hK)),this.encode=this.encode.bind(this),this.decode=this.decode.bind(this)}encode(e){let{frame:o,mediaType:a}=e;try{return X4({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 $4({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:Up?this.encode:X4,type:2}),this.core.room.videoManager.addDecodeProcessor({processor:Up?this.decode:$4,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 M6.Name}getAlias(){return"sei"}getGroup(){return"sei"}};Y(BK,"autoStart",!0),Y(BK,"Name","SEI");var G2,ctA=BK,ltA=0,QK=class v6{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(++ltA)}),this.log.info("created")}getName(){return v6.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 jA(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 jA(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 jA(this,null,function*(){var e;if(!this.dialog)try{if(G2)yield G2;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(kd,"/assets/debug-dialog.js");G2=this._core.fileDownloader.loadScript(o),yield G2}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(QK,"Name","Debug"),Y(QK,"autoStart",!0);var ItA=QK,a5=A=>{switch(A){case"webCodecs":return 504703;case"wasm":return 504704}throw new Error("decoder type not supported")},g5=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=ga(e,zs.INIT),this.stopOB=oQ(),this.startOB=oQ(),o.type==="auto"?this.type="webCodecs":this.type=o.type;let d=oQ();Qa(this.startOB,Vq(0),E2(C=>{let f=this.pipe(e);return d.next("STARTING"),e.log.info("decoder type: ".concat(this.type)),Qa(f,oE(this.stopOB),Cl(()=>{},S=>{e.log.error(S),a.addFailedEvent({key:a5(this.type),error:S}),C>4?this.startOB.error(S):this.startOB.next(C+1)})),Qa(f,Vw(1),m4(Kq))}),oE(this.stopOB),Cl(()=>{e.player.setOutput(),d.next("STARTED")},C=>{d.next("FAILED")},()=>{a.addSuccessEvent({key:a5(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 Dk()(e=>jA(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"}))}},utA={type:"object"},c5=class Yj{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 Yj.Name}getGroup(e){return e.track.userId+e.track.streamType}getName(){return Yj.Name}getValidateRule(e){return utA}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 g5(this.core,c,e);return Qa(d.trackDoneOB,Vw(1),Cl(()=>{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 g5(this.core,e.track,e))}}};Y(c5,"Name","TRTCAudioDecoder");var l5=c5,EtA={rttPoorLimit:150,lossPoorLimit:20,rttGoodLimit:100,lossGoodLimit:10,fpsPoorLimit:5,cooldownTime:1e4,poorCount:3,goodCount:5,maxUpgradeFailCount:3},dtA=class{constructor(){Y(this,"log"),Y(this,"autoMode",{enabled:!1,instance:null,config:EtA,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=f?.video)==null||!o.length)return;let S=C==="sub"?"sub":"big",b=f.video.find(V=>V.videoType===S);b?(this.networkMetrics.frameRate=b.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 f=(e=d.streamType)!=null?e:"main";if((f==="sub"?C.remoteAuxiliaryTrack:C.remoteVideoTrack).isPlayCalled){let S=(o=a._remoteVideoConfigMap.get("".concat(d.userId,"_").concat(f)))==null?void 0:o.config;if(S)return{userId:d.userId,streamType:f,config:S}}}return null}switchPlaybackQuality(A){return jA(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(vA=>{var $A;return Bo(pi({},vA),{streamType:($A=vA.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(vA=>vA.name===c);if(!C)return void this.log.warn('switchPlaybackQuality: quality "'.concat(c,'" not found in streamList'));let f=this.getCurrentPlayingStream(o);if(this.log.info("currentPlaying userId: ".concat(f?.userId,", streamType: ").concat(f?.streamType)),!f)return;let S=(e=C.streamType)!=null?e:"main";if(f.userId===C.userId&&f.streamType===S)return void this.log.info("switchPlaybackQuality: already playing target stream");let b=pi({},f.config);b.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(b.userId,!0));let V,J=new Promise(vA=>{V=vA}),cA=vA=>{vA.userId===C.userId&&vA.streamType===S&&vA.state==="PLAYING"&&vA.reason==="playing"&&V("success")};o.on(Hi.VIDEO_PLAY_STATE_CHANGED,cA);let CA=new Promise(vA=>setTimeout(()=>vA("timeout"),1e4));try{if(yield o.startRemoteVideo(Bo(pi({},f.config),{userId:C.userId,streamType:S,option:Bo(pi({},f.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 b.streamType==="main"&&S==="main"&&(yield o.muteRemoteAudio(b.userId,!1).catch($A=>{this.log.warn("switchPlaybackQuality: rollback muteRemoteAudio failed",$A)})),new oi({code:lt.SUBSCRIPTION_TIMEOUT,message:Zo({key:So.SWITCH_PLAYBACK_QUALITY_TIMEOUT,data:{userId:C.userId}})})}let vA=o.stopRemoteVideo(b);b.streamType==="main"&&S==="main"?yield Promise.all([o.muteRemoteAudio(C.userId,!1).catch($A=>{this.log.warn("muteRemoteAudio(new, false) failed",$A)}),vA]):yield vA,d._currentLiveUserId=C.userId,d._currentLiveStreamType=S}finally{o.off(Hi.VIDEO_PLAY_STATE_CHANGED,cA)}})}startAutoMode(A){return jA(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(f=>{var S;return f.userId===c&&((S=f.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,f=this.networkMetrics.loss>=e.lossPoorLimit||this.networkMetrics.rtt>=e.rttPoorLimit,S=C&&f;this.counters.downgradeCondition=S?this.counters.downgradeCondition+1:0;let b=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=f.getPCM(cA=>{e.emit(Hi.AUDIO_FRAME,cA)},V.userId);S.set(V.userId,J)}});else{if(S.get(a))return;let V=f.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,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 jA(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 oi({code:lt.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 oi({code:lt.INVALID_OPERATION,message:"no available remote video"}))}switchPlaybackQuality(A){return jA(this,null,function*(){let e=A.trtcInstance;return e._playbackQualitySwitcher||(e._playbackQualitySwitcher=new dtA),e._playbackQualitySwitcher.switchPlaybackQuality(A)})}prelink(A){return jA(this,null,function*(){let{trtcInstance:e}=A;return A.enable?e.room.prelink(A.sdkAppId,A.userId,A.userSig,Pk.frameWorkType,A.roomId,A.strRoomId):e.room.closePrelink()})}};di([_4({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"}}})],pK.prototype,"enableAudioFrameEvent"),di([_4({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"}}})],pK.prototype,"prelink");var CtA=new pK,htA=ac(Jl(),1),BtA=class extends htA.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 jA(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 jA(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={}}},b2=new BtA,I5=0,Ok=new Set,jl=null;qP(s5),WA.checkStorage();var Ds=class zp extends aq.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(++I5)})),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(pi({logger:this._log,frameWorkType:zp.frameWorkType},o)),this._room.videoDecodeFallbackType=o.videoDecodeFallback,wr(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(ntA,o.assetsPath),this._use(otA,o.assetsPath),this._use(rtA,o.assetsPath),this._use(l5,o.assetsPath),this._use(ItA),o.enableSEI&&lk&&this._use(ctA),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 f;let S=C.userId===""?this._localAudioTrack:(f=this.room.remotePublishedUserMap.get(C.userId))==null?void 0:f.remoteAudioTrack;S&&(C.volume=S.dbVolume)}),o.enableDbVolume&&a.forEach(C=>{var f;let S=C.userId===""?this._localAudioTrack:(f=this.room.remotePublishedUserMap.get(C.userId))==null?void 0:f.remoteAudioTrack;S&&(C.volume=S.dbVolume)}),this.emit(Hi.AUDIO_VOLUME,{result:a.sort((C,f)=>f.volume-C.volume)})}),this._room.videoManager.on("error",a=>{this._log.error(new Ro({code:vo.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,f=new Array(C),S=0;S{f&&QA.info(MC)})}})();let a=new zp(e,o||{});return Ok.add(a),a.__v_skip=!0,a}get room(){return this._room}_listenEvents(){WE(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=>{rQ(!0),this._exitRoom().finally(()=>{this.emit(Hi.KICKED_OUT,{reason:e.reason})})}).add("error",e=>{this._exitRoom().finally(()=>{this.emit(Hi.ERROR,Ro.convertFrom(e))})}).add("signal-connection-state-changed",e=>{this.emit(Hi.CONNECTION_STATE_CHANGED,e)}).add("network-quality",e=>{this._networkQuality=e;let o=Bo(pi({},e),{uplinkRTT:Math.min(e.uplinkRTT,q0),downlinkRTT:Math.min(e.downlinkRTT,q0)});this.emit(Hi.NETWORK_QUALITY,o)}).add("remote-published",e=>{[e.remoteAudioTrack,e.remoteVideoTrack,e.remoteAuxiliaryTrack].forEach(o=>{WE(o,o).add("player-state-changed",a=>{let c=Bo(pi({},a),{userId:e.userId});o.kind===VA.VIDEO&&(c.streamType=Vd(o.streamType)),this.emit(o.kind===VA.AUDIO?Hi.AUDIO_PLAY_STATE_CHANGED:Hi.VIDEO_PLAY_STATE_CHANGED,c)}).add("error",a=>{a.getCode()===lt.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:f,videoAvailable:S}=a;f||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!==f&&(f?this._onAudioAvailable({userId:c}):this._onAudioUnavailable({userId:c,muteState:a}),this.emit(f?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,Bo(pi({},e),{streamType:Vd(e.streamType)}))}).add("firewall-restriction",()=>{this.emit(Hi.ERROR,new Ro({code:vo.OPERATION_FAILED,extraCode:5501}))}).add("heartbeat-report",e=>{var o,a,c,d,C,f,S;let b={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,q0),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:(((f=e.msg_up_stream_info.msg_audio_status)==null?void 0:f.uint32_audio_codec_bitrate)||0)/1e3,audioLevel:(((S=e.msg_up_stream_info.msg_audio_status)==null?void 0:S.uint32_audio_level)||0)/qE},video:e.msg_up_stream_info.msg_video_status.filter(J=>b[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:b[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)/qE,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:b[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(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,Bo(pi({},e),{streamType:Vd(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:f}=e;if(f.sender==="")return;let S={segmentId:(o=f.payload)==null?void 0:o.roundid,speakerUserId:f.sender,sourceText:(a=f.payload)==null?void 0:a.text,translationTexts:(c=f.payload)==null?void 0:c.translate_msg,timestamp:(d=f.payload)==null?void 0:d.start_utc_ms,isCompleted:(C=f.payload)==null?void 0:C.end,robotId:f.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})}),WE(this,Oc).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=>jA(this,null,function*(){if(this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"add",device:e}),jl&&jl.deviceId===H0){let o=(yield yM()).find(a=>a.deviceId===H0);o&&jl.groupId!==o.groupId&&(jl=o,this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))}})).add("audioOutputRemoved",e=>jA(this,null,function*(){this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"remove",device:e});let o=(yield yM())[0];if(!o||!jl||jl.groupId===o.groupId)return;let a=jl.deviceId===e.deviceId,c=jl.deviceId===H0&&jl.deviceId===o.deviceId;(a||c)&&(jl=o,this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}))})),WE(this,b2).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 Mf()}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(ttA.call(this,{TRTC:zp,room:this._room,assetsPath:o,errorModule:{RtcError:Ro,ErrorCode:vo,CoreErrorCode:lt,ErrorCodeDictionary:f2}}));return this._plugins.set(e.Name,c),c.__v_skip=!0,e.autoStart&&this.startPlugin(e.Name),c}enterRoom(e){return jA(this,null,function*(){var o,a;this.enterRoomParams=e;let{scene:c="rtc",enableAutoPlayDialog:d=!0,autoReceiveAudio:C=!0,autoReceiveVideo:f=!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=f,wr(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,zp.frameWorkType),this._checkTrackToPublish(),r5.start()})}exitRoom(){return jA(this,null,function*(){return yield this._exitRoom()})}switchRoom(e){return jA(this,null,function*(){if(this.room.isSwitchRoomSupported())try{this._clearRemoteTracks(),yield this._room.switchRoom(e)}catch(o){if(!(o instanceof xP)||o.code!==lt.API_CALL_TIMEOUT&&o.code!==lt.SWITCH_ROOM_FAILED)throw o;this._log.warn("switchRoom ".concat(o.code===lt.API_CALL_TIMEOUT?"timeout":"failed",", fallback to exitRoom() and enterRoom()")),yield this._rejoinRoom(e)}else yield this._rejoinRoom(e)})}_rejoinRoom(e){return jA(this,null,function*(){yield this.exitRoom();let o=pi(pi({},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=Ww.get(e);o&&(o.forEach(a=>clearTimeout(a)),Ww.delete(e))}(this),this._room.remotePublishedUserMap.forEach(e=>{kn(e.remoteAudioTrack),kn(e.remoteVideoTrack),kn(e.remoteAuxiliaryTrack)})}switchRole(e,o){return jA(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(),Ok.delete(this),Ok.size===0&&r5.destroy(),this._localAudioTrack&&this.stopLocalAudio(),this._localVideoTrack&&this.stopLocalVideo(),this._localScreenTrack&&this.stopScreenShare(),U.off("102",this._onLocalTrackCaptured,this)}startLocalAudio(){return jA(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,f=new MM(e._room.audioManager),S={},b={muted:!0};C&&(xe(C.microphoneId)?xe(C.audioTrack)||(S.customSource=C.audioTrack):S.deviceId=C.microphoneId,C&&bn(C.captureVolume)&&f.setCaptureVolume(C.captureVolume),xe(C.profile)||(Yn(C.profile)?dp[C.profile]&&f.setProfile(dp[C.profile]):f.setProfile(C.profile)),bn(C.earMonitorVolume)&&(b.muted=!(C.earMonitorVolume>0),b.volume=C.earMonitorVolume),xe(C.echoCancellation)||(f.profile.echoCancellation=C.echoCancellation),xe(C.noiseSuppression)||(f.profile.noiseSuppression=C.noiseSuppression),xe(C.autoGainControl)||(f.profile.autoGainControl=C.autoGainControl),wr(e._enableAutoSwitchWhenRecapturing)&&(f.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),f.on("5",V=>{e.emit(Hi.ERROR,new Ro({code:vo.DEVICE_ERROR,extraCode:5309,messageParams:{error:V}}))}),f.on("2",V=>{e.emit(Hi.DEVICE_CHANGED,{type:"microphone",action:"active",device:V})}),f.on("4",V=>{let J;V.error&&(J=Ro.convertFrom(V.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Bo(pi({},V),{error:J}))}),f.on("6",()=>{}),e._listenOutputTrackChanged(f),e._speakerId&&f.setAudioOutput(e._speakerId),yield f.capture(S),xe(c)||f.setMute(c,d),WE(f,f).add("player-state-changed",V=>{e.emit(Hi.AUDIO_PLAY_STATE_CHANGED,Bo(pi({},V),{userId:""}))}),a&&e._room.isJoined&&e._room.publish(f).catch(()=>{}),e._localAudioTrack=f,e._room.capturedLocalMainAudioTrack=f,e._localAudioConfig=Bo(pi({},o),{publish:a}),yield e._updateAudioPlayOption({playOption:b,track:f}),U.emit("113",{userId:"",room:e.room})}()})}updateLocalAudio(e){return jA(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):xe(d.audioTrack)||(yield this._localAudioTrack.setInputMediaStreamTrack(d.audioTrack)),xe(d.captureVolume)||this._localAudioTrack.setCaptureVolume(d.captureVolume),xe(d.earMonitorVolume)||(C.muted=!(d.earMonitorVolume>0),C.volume=d.earMonitorVolume),yield this._localAudioTrack.update3A(d)),this._room.isJoined&&!xe(o)&&(o&&!this._localAudioConfig.publish&&this._room.publish(this._localAudioTrack).catch(()=>{}),this._localAudioConfig.publish&&!o&&this._room.unpublish(this._localAudioTrack).catch(()=>{})),xe(a)||this._localAudioTrack.setMute(a,c),yield this._updateAudioPlayOption({playOption:C,track:this._localAudioTrack,prevConfig:this._localAudioConfig}),Fh(this._localAudioConfig,e)})}stopLocalAudio(){return jA(this,null,function*(){this._localAudioTrack&&(this._room.isJoined&&(yield this._room.unpublish(this._localAudioTrack).catch(()=>{})),U.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 jA(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:f=!0,capture:S=!0,mute:b,option:V,forcePublish:J=!1}=o,cA=f||J,CA=S,vA=new sQ(e._room.videoManager),$A={},he={};if(V&&(wr(V.avoidCropping)&&(vA.avoidCropping=V.avoidCropping),V.cameraId?$A.deviceId=V.cameraId:xe(V.useFrontCamera)?xe(V.videoTrack)||($A.customSource=V.videoTrack):$A.facingMode=V.useFrontCamera?VA.FACING_MODE_USER:VA.FACING_MODE_ENVIRONMENT,xe(V.retryWhenExactFailed)||($A.retryWhenExactFailed=V.retryWhenExactFailed),V.qosPreference&&($A.contentHint=y2(V.qosPreference)),xe(V.profile)||(Yn(V.profile)?DC[V.profile]&&vA.setProfile(DC[V.profile]):vA.setProfile(V.profile)),xe(V.fillMode)||(he.objectFit=V.fillMode),xe(V.mirror)||(he.mirror=V.mirror),xe(V.small)||(xe(V.smallMode)||(e._room.smallMode=V.smallMode),wr(V.small)&&V.small===!1?vA.stopSmall():vA.updateSmallConfig(D2(V.small,!0))),xe(V.rotation)||vA.setRotation(V.rotation),wr(e._enableAutoSwitchWhenRecapturing)&&(vA.enableAutoSwitchWhenRecapturing=e._enableAutoSwitchWhenRecapturing)),vA.once("first-video-frame",Oe=>{e.emit(Hi.FIRST_VIDEO_FRAME,Bo(pi({},Oe),{streamType:Vd(Oe.streamType)}))}),vA.on("5",Oe=>{e.emit(Hi.ERROR,new Ro({code:vo.DEVICE_ERROR,extraCode:5308,messageParams:{error:Oe}}))}),vA.on("2",Oe=>{e.emit(Hi.DEVICE_CHANGED,{type:"camera",action:"active",device:Oe})}),vA.on("4",Oe=>{let Se;Oe.error&&(Se=Ro.convertFrom(Oe.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Bo(pi({},Oe),{error:Se}))}),vA.on("6",()=>{}),e._listenOutputTrackChanged(vA),$A.customSource&&pp($A.customSource)?(vA.setOutputMediaStreamTrack($A.customSource),CA=!1):CA?yield vA.capture($A):(a=vA.manager)==null||a.changeInput(vA),xe(b)||(yield vA.setMute(b)),WE(vA,vA).add("player-state-changed",Oe=>{e.emit(Hi.VIDEO_PLAY_STATE_CHANGED,Bo(pi({},Oe),{userId:"",streamType:"main"}))}).add("video-size-changed",Oe=>{e.emit(Hi.VIDEO_SIZE_CHANGED,Bo(pi({},Oe),{streamType:Vd(Oe.streamType)}))}),cA){let Oe=e._localScreenTrack&&((c=e._localScreenConfig)==null?void 0:c.publish)&&e._localScreenConfig.streamType==="main";e._room.isJoined?!Oe||J?(e._room.publish(vA).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")):Oe&&(cA=!1)}e._localVideoTrack=vA,e._room.capturedLocalMainVideoTrack=vA,e._localVideoConfig=Bo(pi({},o),{view:C,publish:cA,capture:CA}),yield e._updateVideoPlayOption({view:C,playOption:he,track:vA})}()})}updateLocalVideo(e){return jA(this,null,function*(){var o,a,c,d,C,f,S;if(!this._localVideoTrack||!this._localVideoConfig)return;let{view:b,publish:V=!0,mute:J,capture:cA,option:CA,forcePublish:vA=!1}=e,$A=V||vA,he=cA,Oe={};if(!this._localVideoConfig.capture&&pp((o=this.localVideoTrack)==null?void 0:o.outMediaTrack)&&(CA!=null&&CA.cameraId||CA!=null&&CA.videoTrack)&&this._localVideoTrack.outMediaTrack!==CA?.videoTrack&&(he=!0),this._localVideoConfig.capture)he!==!1?CA!=null&&CA.cameraId?yield this._localVideoTrack.switchDevice(CA?.cameraId):xe(CA?.useFrontCamera)?xe(CA?.videoTrack)||(pp(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?VA.FACING_MODE_USER:VA.FACING_MODE_ENVIRONMENT):this._localVideoTrack.stopCapture();else if(he){let Se={};Se.deviceId=CA?.cameraId||((c=this._localVideoConfig.option)==null?void 0:c.cameraId),Se.facingMode=CA!=null&&CA.useFrontCamera||(d=this._localVideoConfig.option)!=null&&d.useFrontCamera?VA.FACING_MODE_USER:VA.FACING_MODE_ENVIRONMENT,Se.customSource=CA!=null&&CA.videoTrack||!Se.deviceId?(C=this._localVideoConfig.option)==null?void 0:C.videoTrack:void 0,yield this._localVideoTrack.capture(Se)}CA&&(xe(CA.profile)||(Yn(CA.profile)?DC[CA.profile]&&this._localVideoTrack.setProfile(DC[CA.profile]):this._localVideoTrack.setProfile(CA.profile),(!CA.cameraId||!this._localVideoTrack.isNeedToSwitchDevice(CA.cameraId||CA.useFrontCamera?VA.FACING_MODE_USER:VA.FACING_MODE_ENVIRONMENT))&&(yield this._localVideoTrack.applyProfile())),xe(CA.fillMode)||(Oe.objectFit=CA.fillMode),xe(CA.mirror)||(Oe.mirror=CA.mirror),xe(CA.rotation)||this._localVideoTrack.setRotation(CA.rotation),CA.qosPreference&&this._localVideoTrack.mediaTrack&&this._localVideoTrack.setContentHint(y2(CA.qosPreference)),xe(CA.small)||(wr(CA.small)&&!CA.small?this._localVideoTrack.stopSmall():this._localVideoTrack.updateSmallConfig(D2(CA.small,!0)))),this._room.isJoined&&xe($A)&&this._localVideoConfig.publish&&he&&!this._localVideoConfig.capture&&this._room.publish(this._localVideoTrack).catch(()=>{}),this._room.isJoined&&(($A??this._localVideoConfig.publish)||vA?this._localScreenTrack&&((f=this._localScreenConfig)!=null&&f.publish)&&this._localScreenConfig.streamType==="main"&&!vA?($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(()=>{})),xe(J)||(yield this._localVideoTrack.setMute(J)),yield this._updateVideoPlayOption({view:b,playOption:Oe,track:this._localVideoTrack,prevConfig:this._localVideoConfig}),Fh(this._localVideoConfig,Bo(pi({},e),{publish:$A,capture:he}))})}stopLocalVideo(){return jA(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 jA(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:f=!0,muteSystemAudio:S,option:b}=o,V=f,J=new vM(e._room.videoManager);J.on("4",he=>{let Oe;he.error&&(Oe=Ro.convertFrom(he.error)),e.emit(Hi.PUBLISH_STATE_CHANGED,Bo(pi({},he),{error:Oe}))}),J.once("first-video-frame",he=>{e.emit(Hi.FIRST_VIDEO_FRAME,Bo(pi({},he),{streamType:Vd(he.streamType)}))}),e._listenOutputTrackChanged(J),o.streamType==="main"&&(J.mediaType=4);let cA=null,CA={},vA={};b&&(xe(b.profile)||(Yn(b.profile)?WG[b.profile]&&J.setProfile(WG[b.profile]):J.setProfile(b.profile)),b.systemAudio&&(CA.systemAudio=!0,CA.echoCancellation=b.echoCancellation,CA.noiseSuppression=b.noiseSuppression,CA.autoGainControl=b.autoGainControl),xe(b.fillMode)||(vA.objectFit=b.fillMode),b.videoTrack&&(CA.videoTrack=b.videoTrack),b.audioTrack&&(CA.audioTrack=b.audioTrack),b.captureElement&&(CA.captureElement=b.captureElement),b.preferDisplaySurface&&(CA.preferDisplaySurface=b.preferDisplaySurface),b.qosPreference&&(CA.contentHint=y2(b.qosPreference)));let $A=yield J.capture(CA);if(J.mediaTrack.addEventListener(VA.ENDED,()=>{e._stopScreenShare(),e.emit(Hi.SCREEN_SHARE_STOPPED)}),$A.getAudioTracks()[0]){cA=new iK(e._room.audioManager);let he=$A.getAudioTracks()[0];(a=o.option)!=null&&a.systemAudio&&!((c=o.option)!=null&&c.audioTrack)&&(cA.sourceTrack=he),yield cA.setInputMediaStreamTrack(he),wr(S)&&cA.mediaTrack&&(cA.mediaTrack.enabled=!S),e._speakerId&&cA.setAudioOutput(e._speakerId)}if(WE(J,J).add("player-state-changed",he=>{e.emit(Hi.VIDEO_PLAY_STATE_CHANGED,Bo(pi({},he),{userId:"",streamType:"sub"}))}),V){let he=e._localVideoTrack&&((d=e._localVideoConfig)==null?void 0:d.publish),Oe=!(o.streamType==="main"&&he);e._room.isJoined?(Oe?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(()=>{}))):Oe||(V=!1)}e._localScreenTrack=J,e._room.capturedLocalAuxVideoTrack=J,e._localScreenAudioTrack=cA,e._localScreenConfig=Bo(pi({},o),{view:C,publish:V}),yield e._updateVideoPlayOption({view:C,playOption:vA,track:J})}()})}updateScreenShare(e){return jA(this,null,function*(){var o,a;if(!this._localScreenTrack||!this._localScreenConfig)return;let{view:c,publish:d,muteSystemAudio:C,option:f}=e,S=d,b={};if(f){if(xe(f.fillMode)||(b.objectFit=f.fillMode),f.qosPreference){let V=y2(f.qosPreference);this._localScreenTrack.setContentHint(V)}f.videoTrack&&this._localScreenTrack.setInputMediaStreamTrack(f.videoTrack),f.audioTrack&&this._localScreenAudioTrack&&this._localScreenAudioTrack.setInputMediaStreamTrack(f.audioTrack)}if(this._room.isJoined&&!xe(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&&wr(C)&&(this._localScreenAudioTrack.mediaTrack.enabled=!C),yield this._updateVideoPlayOption({view:c,playOption:b,track:this._localScreenTrack,prevConfig:this._localScreenConfig}),Fh(this._localScreenConfig,Bo(pi({},e),{publish:S}))})}stopScreenShare(){return jA(this,null,function*(){return yield this._stopScreenShare()})}startRemoteVideo(e){return jA(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 f=this._room.remotePublishedUserMap.get(a);if(!f)return;let S={},b=c==="main"?f.remoteVideoTrack:f.remoteAuxiliaryTrack,V=this._bindRemoteVideoTrackEvents(b);this._listenOutputTrackChanged(b),d&&(xe(d.fillMode)||(S.objectFit=d.fillMode),xe(d.mirror)||(S.mirror=d.mirror),xe(d.poster)||(S.poster=d.poster),S.canvasRender=d.canvasRender,c==="main"&&!xe(d.small)&&(!f.remoteVideoTrack.isSubscribing&&!f.remoteVideoTrack.isSubscribed&&f.remoteVideoTrack.setMediaType(d.small?8:4),this._room.changeType(d.small,b.user)),xe(d.draggable)||b.setDraggable(d.draggable)),S.isLiveStream=!!this._playbackQualityList.find(J=>J.userId===a&&J.streamType===c),yield this._room.subscribe(b),yield this._enableVideoDecodeFallback(b,c),yield this._updateVideoPlayOption({view:o,playOption:S,track:b}),this._emitTrackEvent(b),this._remoteVideoConfigMap.set(C,{config:e,handlers:V}),d&&!xe(d.receiveWhenViewVisible)&&this._observeView({remoteTrack:b,view:o,receiveWhenViewVisible:d.receiveWhenViewVisible,viewRoot:d?.viewRoot})})}updateRemoteVideo(e){return jA(this,null,function*(){var o,a;let{view:c,userId:d,streamType:C,option:f,mute:S}=e,b="".concat(d,"_").concat(C),V=this._remoteVideoConfigMap.get(b);if(!V||!this._room.remotePublishedUserMap.has(d))return;let J={};f&&(xe(f.fillMode)||(J.objectFit=f.fillMode),xe(f.mirror)||(J.mirror=f.mirror));let cA=null,CA=this._room.remotePublishedUserMap.get(d);if(C==="main"&&CA!=null&&CA.muteState.hasVideo&&(cA=CA.remoteVideoTrack),C==="sub"&&CA!=null&&CA.muteState.hasAuxiliary&&(cA=CA.remoteAuxiliaryTrack),!cA)return;let{config:vA}=V;C==="main"&&f&&!xe(f.small)&&this._room.changeType(f.small,cA.user),f&&!xe(f.draggable)&&cA.setDraggable(f.draggable),f&&(wr(f.pictureInPicture)&&(f.pictureInPicture?yield cA.player.enterPictureInPicture():yield cA.player.exitPictureInPicture()),wr(f.fullScreen)&&(f.fullScreen?yield cA.player.enterFullscreen():yield cA.player.exitFullscreen())),wr(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:c,playOption:J,track:cA,prevConfig:vA}),Fh(vA,e);let $A=xe(f?.receiveWhenViewVisible)?(o=vA.option)==null?void 0:o.receiveWhenViewVisible:f.receiveWhenViewVisible,he=xe(c)?vA.view:c,Oe=xe(f?.viewRoot)?(a=vA.option)==null?void 0:a.viewRoot:f.viewRoot;this._observeView({remoteTrack:cA,view:he,receiveWhenViewVisible:$A,viewRoot:Oe})})}stopRemoteVideo(e){return jA(this,null,function*(){return this._stopRemoteVideo(e)})}_stopRemoteVideo(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return jA(this,null,function*(){let a=[],c=this._room.remotePublishedUserMap.get(e.userId);if(c){let{muteState:d,remoteVideoTrack:C,remoteAuxiliaryTrack:f}=c;e.streamType==="main"&&(C.stop(),d.hasVideo&&a.push(C)),e.streamType==="sub"&&(f.stop(),d.hasAuxiliary&&a.push(f))}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:()=>jA(this,null,function*(){yield e.player.enterPIPPromise,this.emit(Hi.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:Vd(e.streamType),userId:e.userId,isPictureInPicture:!0,pictureInPictureWindow:e.player.pipWindow})}),onLeavePIP:()=>{this.emit(Hi.PICTURE_IN_PICTURE_STATE_CHANGED,{streamType:Vd(e.streamType),userId:e.userId,isPictureInPicture:!1})},onEnterFullScreen:()=>{this.emit(Hi.FULL_SCREEN_STATE_CHANGED,{streamType:Vd(e.streamType),userId:e.userId,isFullScreen:!0})},onLeaveFullScreen:()=>{this.emit(Hi.FULL_SCREEN_STATE_CHANGED,{streamType:Vd(e.streamType),userId:e.userId,isFullScreen:!1})},onDecodeFailed:()=>{this.emit(Hi.ERROR,new Ro({code:vo.OPERATION_FAILED,extraCode:5507,message:"video decode failed"}))},onVideoSizeChanged:a=>{this.emit(Hi.VIDEO_SIZE_CHANGED,Bo(pi({},a),{streamType:Vd(a.streamType)}))}};return e.player.on(mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.on(mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.on(mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.on(mo.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(mo.ENTER_PICTURE_IN_PICTURE,o.onEnterPIP),e.player.off(mo.LEAVE_PICTURE_IN_PICTURE,o.onLeavePIP),e.player.off(mo.ENTER_FULL_SCREEN,o.onEnterFullScreen),e.player.off(mo.LEAVE_FULL_SCREEN,o.onLeaveFullScreen),e.off("decode-failed",o.onDecodeFailed),e.off("video-size-changed",o.onVideoSizeChanged)}muteRemoteAudio(e,o){return jA(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!==vo.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 jA(this,null,function*(){return e.start(o)})}updatePlugin(e,o){return jA(this,null,function*(){return e.update(o)})}stopPlugin(e,o){return jA(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 jA(this,null,function*(){(yield yM()).forEach(o=>{o.deviceId===e&&(this._setCurrentSpeaker(e),this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o}),jl=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(kh,"/en/TRTC.html#.setCurrentSpeaker"))})}_startRemoteAudio(e){return this._doStartRemoteAudio(e)}_doStartRemoteAudio(e){return jA(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",f=>{this.emit(Hi.ERROR,new Ro({code:vo.OPERATION_FAILED,extraCode:5508,message:"audio decode failed"}))}),this._listenOutputTrackChanged(C),this._speakerId&&C.setAudioOutput(this._speakerId);try{let f=(o=this._remoteAudioVolumeMap.get(a))!=null?o:this._remoteAudioVolumeMap.get("*"),S=bn(f)?f:100;d.volume=S,this._remoteAudioConfigMap.set(a,e),yield this._room.subscribe(C),Qa(ga(C,"decode-failed"),oE(ga(C,zs.INIT)),Cl(()=>{this.startPlugin(l5.Name,{track:C,type:"auto",config:{codec:"opus",sampleRate:48e3,numberOfChannels:1}})})),yield this._updateAudioPlayOption({playOption:d,track:C}),U.emit("115",{userId:a,room:this.room}),C.outMediaTrack&&this.room.audioManager.updateAudioReference({type:"add",audioReference:C.outMediaTrack,refId:"ra-".concat(a)})}catch(f){throw this._remoteAudioConfigMap.delete(a),f}this._emitTrackEvent(C)})}_stopRemoteAudio(e){let o=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return jA(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)),U.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),Qa(ga(e,"decode-failed"),oE(ga(e,zs.INIT)),zq(()=>{this._room.downlinkVideoCodec!=="h265"&&this.startPlugin("TRTCVideoDecoder",{type:"auto",renderer:"videoFrame",track:e,config:{codec:"avc1.420028"},fallback:c})}),C2(ga(e,"decode-downgrade-state-changed")),Cl(d=>{a=d.state,this.emit(Hi.VIDEO_DECODE_DOWNGRADE_STATE_CHANGED,Bo(pi({},d),{streamType:o,userId:e.userId}))},d=>{e.log.error("fallback",d)},()=>{a==="STARTED"&&e.log.info("fallback complete")})))}_updateVideoPlayOption(e){return jA(this,arguments,function(o){let{view:a,playOption:c,track:d,prevConfig:C}=o;return function*(){if(d.setMirror(c.mirror),xe(a)&&C&&C.view&&!iw(c)){let f=xS(C.view);f.length>0&&(yield d.play(f,c))}if(!xe(a)){let f=xS(a);f.length>0?yield d.play(f,c):d.stop()}}()})}_updateAudioPlayOption(e){return jA(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(xe(c.muted)||d.setPlayerMute(c.muted),xe(c.volume)||d.setAudioVolume(c.volume/100),d instanceof MM&&d.mediaTrack){let f=c.muted===!1&&!xe(c.volume)&&c.volume>0?"add":"remove";a.room.audioManager.updateAudioReference({type:f,audioReference:d.mediaTrack,refId:"em"})}else if(d instanceof p2){let f=c.muted?0:c.volume;if(xe(f))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:Vd(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(xe(a)||xe(c))return;let C=this._remoteVideoConfigMap.get("".concat(o.userId,"_").concat(Vd(o.streamType)));if(!C)return;let f=C.observer||void 0;if(a===null||va(a)&&a.length===0||!c)return f?.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,b=-1;(!f||f.root!==d)&&(f?.disconnect(),S.clear(),f=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(b),b=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(xS(a));S.forEach((J,cA)=>{V.has(cA)||(f.unobserve(cA),S.delete(cA))}),V.forEach(J=>{S.set(J,!0),f.observe(J)}),f.takeRecords().forEach(J=>{S.set(J.target,J.isIntersecting)}),C.visibleViewMap=S,C.observer=f}_exitRoom(){return jA(this,null,function*(){this._room.isJoined&&(yield this._room.leave()),this._clearRemoteTracks()})}_stopScreenShare(){return jA(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 jA(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"&&(!jl||fk(jl))&&(this._initActiveSpeaker(),U.off("102",this._onLocalTrackCaptured,this))}_initActiveSpeaker(){return jA(this,null,function*(){if(jl&&!fk(jl))this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:jl});else{let e=yield yM();e[0]&&!fk(e[0])?(jl=e[0],this.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:e[0]})):U.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:Bo(pi({seiPayloadType:243},o),{small:!((a=this._localVideoTrack)==null||!a.small)})}),Ai.addCount({key:5e5,useUV:!0}))}sendCustomMessage(e){var o,a;(a=(o=this._room).sendCustomMessage)==null||a.call(o,e),Ai.addCount({key:500001,useUV:!0})}callExperimentalAPI(e,o){return jA(this,null,function*(){return this._log.info("callExperimentalAPI(".concat(e,", ").concat(JSON.stringify(o),")")),CtA.call(e,pi({trtcInstance:this},o))})}static setLogLevel(e,o){QA.setLogLevel(e),xe(o)||(o?QA.enableUploadLog():QA.disableUploadLog())}static isSupported(){return tk(zp.frameWorkType)}static getPermissions(e){return jA(this,arguments,function(o){let{request:a=!0,types:c=["camera","microphone"]}=o;return function*(){a&&(yield b2.request(c).catch(f=>{var S;return QA.error("getPermissions request failed, error: ".concat((S=f?.message)!=null?S:f))}));let[d,C]=yield Promise.all([b2.get("camera"),b2.get("microphone")]);return{camera:d,microphone:C}}()})}static getCameraList(){return Vp(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])}static getMicrophoneList(){return Yp(!(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 jA(this,null,function*(){if(Ja&&(e===kk.SPEAKER||e===kk.HEADSET)){let o=yield zp.getMicrophoneList(),a="";return o.forEach(c=>{c.label===e&&(a=c.deviceId)}),a?void Ok.forEach(c=>jA(null,null,function*(){c._localAudioTrack&&(yield c.updateLocalAudio({option:{microphoneId:a}}))})):void 0}(yield yM()).forEach(o=>{o.deviceId===e&&(Ok.forEach(a=>{a._setCurrentSpeaker(e),a.emit(Hi.DEVICE_CHANGED,{type:"speaker",action:"active",device:o})}),jl=o)})})}static _addKVStat(e){let{type:o,key:a,value:c,base:d,useUV:C,version:f,max:S}=e;switch(f&&(Ph.version=f),o){case"count":Ph.addCount({key:a,useUV:C});break;case"enum":Ph.addEnum({key:a,value:c,useUV:C});break;case"number":Ph.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(Ds,"VERSION",s5),Y(Ds,"_loggerManager",QA),Y(Ds,"EVENT",Hi),Y(Ds,"ERROR_CODE",vo),Y(Ds,"TYPE",kk),Y(Ds,"frameWorkType",30),di([pa({replaceArg:A=>({argIndex:0,value:{name:"plugin"in A?A.plugin.Name:A.Name,assetsPath:"assetsPath"in A?A?.assetsPath:"default"}})})],Ds.prototype,"use"),di([au(Kl.TRTC.enterRoom),_M("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}),Hr(A=>function(e){return this._log.setUserId(e.userId),this._log.setSdkAppId(e.sdkAppId),A.call(this,e)}),pa()],Ds.prototype,"enterRoom"),di([pa()],Ds.prototype,"exitRoom"),di([au(Kl.TRTC.switchRoom),pa(),yk()],Ds.prototype,"switchRoom"),di([au(Kl.TRTC.switchRole),jw("room",{merge:(A,e)=>e}),pa()],Ds.prototype,"switchRole"),di([pa()],Ds.prototype,"destroy"),di([au(Kl.TRTC.startLocalAudio),_M("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)}),pa()],Ds.prototype,"startLocalAudio"),di([au(Kl.TRTC.updateLocalAudio),jw("audio",{debounce:{delay:200,getKey:()=>"".concat(I5,"-localAudio"),isNeedToDebounce:A=>{var e;return!xe((e=A.option)==null?void 0:e.captureVolume)}}}),pa()],Ds.prototype,"updateLocalAudio"),di([TM("audio"),pa()],Ds.prototype,"stopLocalAudio"),di([au(Kl.TRTC.startLocalVideo),_M("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)}),pa()],Ds.prototype,"startLocalVideo"),di([au(Kl.TRTC.updateLocalVideo),jw("video"),pa()],Ds.prototype,"updateLocalVideo"),di([TM("video"),pa()],Ds.prototype,"stopLocalVideo"),di([au(Kl.TRTC.startScreenShare),_M("screen",()=>!0),pa()],Ds.prototype,"startScreenShare"),di([au(Kl.TRTC.updateScreenShare),jw("screen"),pa()],Ds.prototype,"updateScreenShare"),di([pa()],Ds.prototype,"stopScreenShare"),di([au(Kl.TRTC.startRemoteVideo),_M(A=>"v".concat(A.userId).concat(A.streamType),()=>!0),pa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ds.prototype,"startRemoteVideo"),di([au(Kl.TRTC.updateRemoteVideo),jw(A=>"v".concat(A.userId).concat(A.streamType)),pa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ds.prototype,"updateRemoteVideo"),di([au(Kl.TRTC.stopRemoteVideo),Hr(A=>function(e){return jA(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)})}),pa({getRemoteId:A=>"".concat(A.userId,"_").concat(A.streamType)})],Ds.prototype,"stopRemoteVideo"),di([TM(A=>"v".concat(A.userId).concat(A.streamType))],Ds.prototype,"_stopRemoteVideo"),di([au(...Kl.TRTC.muteRemoteAudio),pa({getRemoteId:A=>A})],Ds.prototype,"muteRemoteAudio"),di([n5(...Kl.TRTC.setRemoteAudioVolume),function(A,e){return Hr((o,a)=>function(){for(var c=arguments.length,d=new Array(c),C=0;C{var J;(J=Ww.get(this))==null||J.delete(S)},A);f.set(S,V)}else{clearTimeout(b);let V=window.setTimeout(()=>{var J;o.apply(this,d),(J=Ww.get(this))==null||J.delete(S)},A);f.set(S,V)}})}(200,A=>A),pa({getRemoteId:A=>A})],Ds.prototype,"setRemoteAudioVolume"),di([IK("start"),DM(A=>{var e;return(e=A.afterStart)==null?void 0:e.call(A)}),_M((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e)),pa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>Hx[A.getName()],ignoreLog:A=>A.getName()==="Debug",ignoreErrorLog:A=>A.getName()==="AudioProcessor"})],Ds.prototype,"startPlugin"),di([IK("update"),jw((A,e)=>A.disableRandomCall?null:A.getAlias()+A.getGroup(e),{merge:(A,e)=>(Fh(A[1],e[1]),A)}),pa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>iy[A.getName()]})],Ds.prototype,"updatePlugin"),di([IK("stop"),TM((A,e)=>{if(A.disableRandomCall)return null;let o=A.getGroup(e),a=A.getAlias();return o==="*"?new RegExp("".concat(a,".*")):a+o}),pa({replaceArg:A=>({argIndex:0,value:A.getName()}),getKVReportKey:A=>_w[A.getName()]})],Ds.prototype,"stopPlugin"),di([n5(...Kl.TRTC.enableAudioVolumeEvaluation)],Ds.prototype,"enableAudioVolumeEvaluation"),di([pa()],Ds.prototype,"getVideoSnapshot"),di([pa()],Ds.prototype,"_setCurrentSpeaker"),di([_M(A=>"a".concat(A.userId),()=>!0)],Ds.prototype,"_startRemoteAudio"),di([Hr(A=>function(e){return jA(this,null,function*(){return e.userId==="*"?Promise.all([...this._room.remotePublishedUserMap.values()].map(o=>this._stopRemoteAudio(Bo(pi({},e),{userId:o.userId})).catch(()=>{}))):A.call(this,e)})}),TM(A=>"a".concat(A.userId))],Ds.prototype,"_stopRemoteAudio"),di([TM("room")],Ds.prototype,"_exitRoom"),di([TM("screen")],Ds.prototype,"_stopScreenShare"),di([au(...Kl.TRTC.sendSEIMessage),T4({timesInSecond:30,maxSizeInSecond:8e3,getSize:function(){for(var A=arguments.length,e=new Array(A),o=0;oA.data.byteLength})],Ds.prototype,"sendCustomMessage"),di([pa()],Ds.prototype,"callExperimentalAPI"),di([NM()],Ds,"create"),di([au(Kl.TRTC.create)],Ds,"_create"),di([NM()],Ds,"setLogLevel"),di([NM()],Ds,"isSupported"),di([NM(),pa()],Ds,"getPermissions"),di([NM()],Ds,"getCameraList"),di([NM()],Ds,"getMicrophoneList"),di([NM()],Ds,"getSpeakerList");var Pk=Ds,QtA=class{constructor(){Y(this,"_set",new Set),U.on(nA.LEAVE_SUCCESS,this.delete,this),U.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 ptA(){return jA(this,null,function*(){let A,e;try{let CA=yield Yp();A=CA&&CA.length}catch{}try{let CA=yield Vp();e=CA&&CA.length}catch{}let o={microphone:A,camera:e},{isH264EncodeSupported:a,isVp8EncodeSupported:c,isH264DecodeSupported:d,isVp8DecodeSupported:C,isH265EncodeSupported:f,isH265DecodeSupported:S}=this.checkSystemResult.detail,b=te.basis(),V={webRTC:b.isWebRTCSupported,getUserMedia:b.isGetUserMediaSupported,webSocket:b.isWebSocketsSupported,screenShare:b.isScreenShareSupported,webAudio:b.isWebAudioSupported,h264Encode:a,h264Decode:d,vp8Encode:c,vp8Decode:C,h265Encode:f,h265Decode:S},J={browser:b.browser,os:b.os,trtc:V,devices:o},cA={isWebCodecSupported:b.isWebCodecSupported,isMediaSessionSupported:b.isMediaSessionSupported,isWebTransportSupported:b.isWebTransportSupported};on.uploadEvent({log:"trtcstats-".concat(JSON.stringify(J)),userId:this.userId}),this._log.info("TrtcStats-".concat(JSON.stringify(J))),on.uploadEvent({log:"trtcadvancedstats-".concat(JSON.stringify(cA)),userId:this.userId}),CM()})}var mtA=ac(Jl()),u5="1",mK="2",xk="3",ftA="4",k2="5",ytA="6",L2="7",E5="8",Jh={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},DtA=[Jh.UPDATE_REMOTE_MUTE_STAT,Jh.UPLINK_NETWORK_STATS,Jh.USER_LIST_RES,Jh.MUTE_RESULT,Jh.SERVER_FIRST_PACKAGE_RECEIVED,Jh.RECEIVE_CUSTOM_MSG,Jh.UPDATE_NETWORK_TIME_RESULT],cs={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"},d5="publish_change",StA="join",MtA="leave",vtA="quality_report",C5="mute_uplink",h5="publish",fK="publish_state_change",U2="unpublish",B5="subscribe",yK="unsubscribe",DK="subscribe_change",RtA="start_publishing",wtA="stop_publishing",_tA="start_push_user_cdn",TtA="stop_push_user_cdn",NtA="start_mcu_mix",GtA="stop_mcu_mix",btA="start_publish_cdn_stream",ktA="update_publish_cdn_stream",LtA="stop_publish_cdn_stream",UtA="get_user_list",FtA="change_role",SK="update_constraint_config",OtA="rebuild_pc",PtA="join/v2",Q5="publish/v2",p5="subscribe/v3",xtA="ability_status_report",YtA="reconnect",VtA="channel_msg",JtA="switch_room",HtA="update_network_time",qtA=new Set([h5,d5,fK,U2,B5,DK,yK,Q5,p5]),F2=new Set,KtA=["autoTest","relayInnerIp","relayOuterIp","mcd","newRelay","clientIp"],jtA=0,m5=class extends mtA.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-F2.size>0&&this.room.enableSPC&&(this.keepAlive=!0,F2.add(this)),this.url=A.url,this.backupUrl=A.backupUrl,this._seq=0,this._log=QA.createLogger({parent:this.room.getLogger(),id:"ws".concat(++jtA),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 KtA.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 jA(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=bo();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 OS(o),A.unbindAndCloseSocket(A._socketInUse===A._socket?VA.BACKUP:VA.MAIN),A._isFirstConnect&&(Ai.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,f)=>{c.onclose=f,c.onerror=f,c.onopen=()=>C(c),o&&(d=setTimeout(()=>{this.unbindAndCloseSocket(a?VA.MAIN:VA.BACKUP),f(new oi({code:lt.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===VA.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(k2,new oi({code:lt.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(VA.MAIN),this.unbindAndCloseSocket(VA.BACKUP),this._socketInUse=null,this.reconnect()),this.room.isJoining&&this.emit(k2,new oi({code:lt.SIGNAL_CHANNEL_SETUP_FAILED,message:"websocket onerror"}))}onmessage(A){if(!this.isConnected)return;let{isOnline:e}=this;this._lastMessageTime=Date.now(),e||this.emit(E5),this.bytesReceived+=sw(A.data);let o=JSON.parse(A.data),{cmd:a,data:c}=o,d=Object.values(Jh),C=Object.keys(Jh)[d.indexOf(a)],f=cs[C]||a;switch(DtA.includes(a)||(this._log.debug("received ".concat(a," msg: ").concat(A.data)),f&&this._log.info("Received event: [ ".concat(f," ]"))),a){case Jh.CHANNEL_SETUP_RESULT:if(o.code===0)this._signalInfo.clientIp=c.clientIp,this._signalInfo.signalIp=c.signalInnerIp,c.svrTime&&UB(c.svrTime-new Date().getTime()),this._log.info("ChannelSetup Success ".concat(bo()-this._connectStartTime)),Ai.addSuccessEvent({key:521701,cost:bo()-this._connectStartTime}),this._connectStartTime=-1,this.room.firewallDetector.resetTimeoutCount(),this.emit(u5,{signalInfo:this._signalInfo});else{let S=new oi({code:lt.SIGNAL_CHANNEL_SETUP_FAILED,extraCode:o.code,message:Zo({key:So.SIGNAL_CHANNEL_SETUP_FAILED,data:{errorCode:o.code,errorMsg:o.message}})});this._log.error("".concat(o.code,", ").concat(o.message)),this.close(),Ai.addFailedEvent({key:521701,error:S}),this.emit(k2,S)}break;case Jh.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(f,{data:o});break;default:this.emit(String(f),{data:o})}}reGetSignalChannelUrl(){return jA(this,null,function*(){try{if(!this.room.joinParams)return;rQ(!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?VA.MAIN:VA.BACKUP),this._socketInUse=null,this.emitConnectionStateChanged("DISCONNECTED"),this.reconnect()}reconnect(){return jA(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:YtA,data:{roomId:A,useStringRoomId:e,relayInnerIp:a,relayOuterIp:o,relayPort:c},responseCommand:cs.CHANNEL_RECONNECT_RESULT});d.code===0?(this._log.warn("reconnect success"),this.stopReconnection(),Ai.addSuccessEvent({key:521702,cost:bo()-this._connectStartTime}),this._connectStartTime=-1,this.room.syncUserList(),this.room.checkConnectionsToReconnect()):(Ai.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),qtA.has(A)&&this._log.info("send",A,e),this.bytesSent+=sw(a),o.seq}}sendWaitForResponse(A){let{command:e,data:o,timeout:a=5e3,responseCommand:c,commandDesc:d,enableLog:C=!0,addReceiveTime:f=!1}=A;return new Promise((S,b)=>{let V=()=>{clearTimeout(J),b(new oi({code:lt.API_CALL_ABORTED,message:"".concat(e," aborted due to connection closed")}))};this.once(L2,V);let J=setTimeout(()=>{this.off(c,cA),this.off(L2,V);let vA=new oi({code:lt.API_CALL_TIMEOUT,message:Zo({key:So.API_CALL_TIMEOUT,data:{commandDesc:d,command:e}})});C&&this._log.warn(vA),b(vA)},a),cA=vA=>{vA.data.seq===CA&&(clearTimeout(J),this.off(c,cA),this.off(L2,V),f&&(vA.data.receiveTime=Date.now()),S(vA))};this.on(c,cA);let CA=this.send(e,o)})}sendWaitForResponseWithRetry(A){let{commandDesc:e,command:o,retries:a=0,retryTimeout:c=0}=A;return JS({retryFunction:this.sendWaitForResponse,onError:d=>{let{retry:C,reject:f,error:S}=d;!this.room.isJoined||this.destroyed||S.code===lt.API_CALL_ABORTED?f(S):this.isOnline?C():(this._log.warn("retry ".concat(o," when connected")),this.once(E5,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),F2.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(VA.MAIN),this.unbindAndCloseSocket(VA.BACKUP),this.emitConnectionStateChanged("DISCONNECTED"),this.emit(L2)}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(cs.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopKeepAlive clear timeout"),clearTimeout(this.stopKeepAliveTimeout),this.off(cs.JOIN_ROOM_RESULT,e))};this.on(cs.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(cs.JOIN_ROOM_RESULT,e)},1e3*A);let e=o=>{o.data.code===0&&(this._log.info("stopPrelink clear timeout"),clearTimeout(this.stopPrelinkTimeout),this.off(cs.JOIN_ROOM_RESULT,e))};this.on(cs.JOIN_ROOM_RESULT,e)}markPrelinkConnected(A){this._prelinkConfig=Bo(pi({},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(mK,e),this._currentState=A,A==="CONNECTED"?this.emit(xk):A==="DISCONNECTED"&&this.emit(ytA)}};di([Yh({settings:{retries:1/0,timeout:2e3},onError(A,e){!this.room.isDestroyed&&!this.destroyed&&(this._isFirstConnect&&(Ai.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())}})],m5.prototype,"connect");var WtA=ac(Jl()),f5=!1,qp=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 WtA.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=bo())}afterConnect(){try{this._isFirstConnection?(this._isFirstConnection=!1,Ai.addSuccessEvent({key:521705,cost:Math.min(bo()-this._prevTime,3e4)})):this._isReconnecting&&Ai.addSuccessEvent({key:521706,cost:bo()-this._prevTime}),this._prevTime=-1}catch(A){throw this._isFirstConnection?(this._isFirstConnection=!1,Ai.addFailedEvent({key:521705,error:A})):this._isReconnecting&&this._reconnectionCount>=3&&Ai.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 oi({code:lt.API_CALL_ABORTED,message:"connection closed"}))}getDTLSTransportState(){if(!this._peerConnection)return Lh;let A=null;if(this._isUplink){if(!_I()||this._peerConnection.getSenders().length===0)return Lh;A=this._peerConnection.getSenders()[0].transport}else{if(!sy()||this._peerConnection.getReceivers().length===0)return Lh;A=this._peerConnection.getReceivers()[0].transport}return A?A.state:Lh}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===Eo.CONNECTING&&this.emitConnectionStateChangedEvent("CONNECTING"),A.target.connectionState===Eo.FAILED||A.target.connectionState===Eo.CLOSED){let a="connection ".concat(A.target.connectionState,". ICE Transport state: ").concat(e,", DTLS Transport state: ").concat(o),c=new oi({message:a,code:lt.ICE_TRANSPORT_ERROR});this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection(),this._isErrorObserved||this._emitter.emit("error",c)}(A.target.connectionState===Eo.CONNECTED||A.target.connectionState===Eo.COMPLETED)&&(this.logSelectedCandidate(),on.logSuccessEvent({userId:this._room.userId,eventType:Va.ICE_CONNECTION_STATE}),this.emitConnectionStateChangedEvent("CONNECTED"))}emitConnectionStateChangedEvent(A){return A!==this._currentState&&(A==="CONNECTED"&&(this._room.firewallDetector.resetTimeoutCount(),f5=!0),U.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 jA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[,e]of A)if(lM(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:f}=C;f===this._room&&(clearTimeout(d),c(),e(new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.CONNECTION_ABORTED,data:"leave room"})})))},c=()=>{U.off(nA.LEAVE_SUCCESS,a,this),this._emitter.off("connection-state-changed",o,this)},d=setTimeout(()=>{c();let C=new oi({code:lt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(C)},tb);U.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(xk,this.reconnect,this)}beforeReconnect(){if(this._reconnectionTimer!==-1)return this._log.warn("reconnect() is reconnecting, ignore"),-1;if(this._reconnectionCount>=Tf()){this._log.warn("SDK has tried reconnect for ".concat(this._reconnectionCount," times, but all failed, please check your network")),this.stopReconnection();let A=new oi({code:this._isUplink?lt.UPLINK_RECONNECTION_FAILED:lt.DOWNLINK_RECONNECTION_FAILED,message:Zo({key:this._isUplink?So.UPLINK_RECONNECTION_FAILED:So.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(xk,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)}};di([ly(521712,!1)],qp.prototype,"setOffer"),di([ly(521713,!1)],qp.prototype,"setAnswer");var y5=ac(VG()),Ic=function(A){return y5.default.parse(A)},Cy=function(A){return y5.default.write(A)};function MK(A){return Object.keys(A).filter(e=>A[e])}var O2=class R6 extends qp{constructor(e){super(Bo(pi({},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 p2(this._room,this),this.remoteVideoTrack=e.remoteVideoTrack||new bk(this._room,this),this.remoteAuxiliaryTrack=e.remoteAuxiliaryTrack||new w4(this._room,this),this.avPlayerStateSyncManager=new gK({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 Qp(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===VA.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===ou?VA.MAIN:VA.AUXILIARY;this._log.debug("ontrack ".concat(c," ").concat(a.kind));let d=VA.AUDIO;a.kind===VA.VIDEO&&(d=c===VA.MAIN?VA.VIDEO:VA.AUXILIARY);let C=this.remoteAudioTrack;d===VA.VIDEO?C=this.remoteVideoTrack:d===VA.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===VA.VIDEO&&a.fmtp.forEach(c=>{c.config+=";sps-pps-idr-in-keyframe=1"})}),Cy(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=Ic(e);return a.media.forEach(c=>{c.ext&&(c.ext=c.ext.filter(d=>!o.includes(d.uri)))}),Cy(a)}isSubscriptionStateNotChanged(e){return JSON.stringify(e)===JSON.stringify(this.subscribeState)}subscribe(e,o){return jA(this,null,function*(){var a,c;try{if((((a=this._peerConnection)==null?void 0:a.connectionState)===Eo.NEW||((c=this._peerConnection)==null?void 0:c.connectionState)===Eo.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 oi({code:lt.REMOTE_STREAM_NOT_EXIST,message:"remote user ".concat(this.userId," unpublished stream")})):d}})}unsubscribe(e){return jA(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=pi({},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 f="subscribe_change";Object.values(C).find(S=>S===!0)||(f="unsubscribe"),a._log.info("".concat(f==="unsubscribe"?f:"subscribe"," ").concat(d," [").concat(MK(C),"]")),yield a.sendSubscription(f,C),f==="unsubscribe"&&(a.closePeerConnection(),a.emitConnectionStateChangedEvent("DISCONNECTED"))}()})}unsubscribeDataChannel(){return jA(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=yK,d=cs.UNSUBSCRIBE_RESULT;return e==="subscribe_change"&&(a={audio:o.audio,bigVideo:o.video,auxVideo:o.auxiliary,smallVideo:o.smallVideo,srcTinyId:this.tinyId},c=DK,d=cs.SUBSCRIBE_CHANGE_RESULT),this._signalChannel.sendWaitForResponse({command:c,data:a,responseCommand:d,timeout:1e4}).then(C=>{let{data:f}=C;if(f.code!==0){let S=new oi({code:f.code,message:Zo({key:So.ERROR_MESSAGE,data:{type:e,message:f.message}})});throw this._log.error(S),S}})}connect(){return jA(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 jA(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:B5,commandDesc:"exchange sdp",data:c,responseCommand:cs.SUBSCRIBE_RESULT,timeout:ix});if(!this._peerConnection){let C=new oi({code:lt.INVALID_OPERATION,message:Zo({key:So.CONNECTION_CLOSED})});throw this._log.warn(C),C}yield this.onSubscribeResult(d),this._isSDPExchanging=!1}catch(o){throw this._isSDPExchanging=!1,o}})}createOffer(){return jA(this,null,function*(){let e={voiceActivityDetection:!1};Pd()&&this._sdpSemantics===TS?(this._peerConnection.addTransceiver(VA.AUDIO,{direction:zn.RECVONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:zn.RECVONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:zn.RECVONLY})):(e.offerToReceiveAudio=!0,e.offerToReceiveVideo=!0);let o=yield this._peerConnection.createOffer(e);if(o.sdp){let{isH264DecodeSupported:a}=yield ek();a||(this._log.warn("remove h264 desc from sdp"),o.sdp=function(c){let d=Ic(c);return d.media.forEach(C=>{var f,S;if(C.type===VA.VIDEO){let b=new Set;C.rtp.forEach(J=>{let{payload:cA,codec:CA}=J;return CA==="H264"&&b.add(cA)}),C.fmtp.forEach(J=>{let{payload:cA,config:CA}=J,vA=CA.match(/apt=(\d+)/);vA&&vA[1]&&b.has(Number(vA[1]))&&b.add(cA)});let V=J=>{let{payload:cA}=J;return!b.has(cA)};C.rtp=C.rtp.filter(V),C.rtcpFb=(f=C.rtcpFb)==null?void 0:f.filter(V),C.fmtp=C.fmtp.filter(V),C.payloads=(S=C.payloads)==null?void 0:S.split(" ").filter(J=>!b.has(Number(J))).join(" ")}}),Cy(d)}(o.sdp)),o.sdp=this.addRRTRLine(o.sdp),o.sdp=this.addSPSDescription(o.sdp),o.sdp=function(c){let d=Ic(c);return d.media.forEach(C=>{C.type===VA.AUDIO&&C.fmtp.forEach(f=>{f.config+=";sprop-stereo=1;stereo=1"})}),Cy(d)}(o.sdp),this._sdpSemantics===TS&&(o.sdp=this.removeSDESDescription(o.sdp))}yield this.setOffer(o)})}onSubscribeResult(e){return jA(this,null,function*(){let{code:o,message:a=""}=e&&e.data||{},{type:c,sdp:d}=e&&e.data&&e.data.data||{};if(o===J0)throw new oi({code:lt.NOT_SUPPORTED_H264,message:Zo({key:So.NOT_SUPPORTED_H264DECODE})});try{if(o!==0)throw new oi({code:o,message:Zo({key:So.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{Ic(e).media.forEach(o=>{if(o.ssrcs)if(o.type===VA.AUDIO){let a=o.ssrcs.find(c=>{var d;return(d=c.value)==null?void 0:d.includes(ou)});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(ou)}),c=o.ssrcs.find(d=>{var C;return(C=d.value)==null?void 0:C.includes(XP)});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 jA(this,null,function*(){if(!(MI(R6.prototype,this,"beforeReconnect").call(this)<0))try{this.closePeerConnection(),this.initialize(),yield this.connect(),this.stopReconnection(),this._log.warn("reconnect() success")}catch{let o=Bp(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}};di([Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=f=>{this._emitter.off("closed",C),d(new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.CONNECTION_ABORTED,data:f})}))};this._emitter.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this._emitter.off("closed",C)})})})],O2.prototype,"subscribe"),di([ly(521717,!1)],O2.prototype,"unsubscribe"),di([DM(qp.prototype.afterConnect),WW(qp.prototype.beforeConnect)],O2.prototype,"connect");var D5=O2,S5={voiceActivityDetection:!1},P2=class w6 extends qp{constructor(e){super(Bo(pi({},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,f=super.emitConnectionStateChangedEvent(e);return f&&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}))),f}publish(e){return jA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,isAuxiliary:C}=o;return function*(){let f;a._peerConnection||a.initialize(),c&&(a._publishingLocalAudioTrack=c),d&&(a._publishingLocalVideoTrack=d),a._isPublishingAux=C,d&&!C&&d.small&&(f=a._room.videoManager.smallTrack),a.sendMediaSettings(),Pd()?yield a.publishByTransceiver({localAudioTrack:c,localVideoTrack:d,smallTrack:f,isAuxiliary:C}):yield a.publishByAddTrack({localAudioTrack:c,localVideoTrack:d,smallTrack:f}),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 jA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,smallTrack:C,isAuxiliary:f}=o;return function*(){a._log.info("publish by transceiver");let S=new MediaStream,b=d?.outMediaTrack,V=c?.outMediaTrack;V&&S.addTrack(V),b&&S.addTrack(b);let J=a._peerConnection.getTransceivers();if(J.length===0)a._peerConnection.addTransceiver(V||VA.AUDIO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(f?VA.VIDEO:b||VA.VIDEO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(C||VA.VIDEO,{direction:zn.SENDONLY,streams:[S]}),a._peerConnection.addTransceiver(f&&b||VA.VIDEO,{direction:zn.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:c?.profile.bitrate||40,type:VA.AUDIO})),b){let CA=f?3:1;yield J[CA].sender.replaceTrack(b),yield a.setBandwidth({bandwidth:d.profile.bitrate,type:VA.VIDEO,videoType:f?VA.AUXILIARY:VA.BIG}),cA.push(CA),C&&(yield J[2].sender.replaceTrack(C),yield a.setBandwidth({bandwidth:d.small.bitrate,type:VA.VIDEO,videoType:VA.SMALL}),cA.push(2))}yield a.setTransceiverDirection(zn.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 jA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d,smallTrack:C}=o;return function*(){a._log.info("publish by addtrack");let f=d?.outMediaTrack,S=c?.outMediaTrack;if(a._peerConnection&&a._peerConnection.connectionState!=="new")return c&&S&&(yield a.addTrack(c)),void(f&&(yield a.addTrack(d)));let b=new MediaStream;if(S&&b.addTrack(S),f&&b.addTrack(f),S&&a._peerConnection.addTrack(S,b),f&&(a._peerConnection.addTrack(f,b),C)){let V=new MediaStream;V.addTrack(C),a._peerConnection.addTrack(C,V)}yield a.connect()}()})}enableSmall(e){return jA(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 jA(this,arguments,function(o){var a=this;let{localAudioTrack:c,localVideoTrack:d}=o;return function*(){if(!tQ())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,f=d?.outMediaTrack,S=a._peerConnection.getSenders(),b=[];c&&(C?a.localAuxAudioTrack=null:a.localMainAudioTrack=null,!a.localAuxAudioTrack&&!a.localMainAudioTrack&&(yield S[0].replaceTrack(null),b.push(0))),f&&(C?(yield S[3].replaceTrack(null),a.localAuxVideoTrack=null,a._mediaSettings=Bo(pi({},a._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),b.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),a.localMainVideoTrack=null,a._mediaSettings=Bo(pi({},a._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),b.push(1,2))),a.isMainStreamPublished||a.isAuxStreamPublished?(yield a.setTransceiverDirection(zn.INACTIVE,b),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 jA(this,null,function*(){let o={state:this._room.publishState,constraintConfig:this._mediaSettings},a=yield this._signalChannel.sendWaitForResponse({command:fK,data:o,responseCommand:cs.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:U2,commandDesc:"unpublish",responseCommand:cs.UNPUBLISH_RESULT,enableLog:e}).catch(o=>{if(o.getCode()===lt.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),ny){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:SK,data:this._mediaSettings,responseCommand:cs.UPDATE_CONSTRAINT_CONFIG_RES}).then(e=>{e.data.code!==0&&this._log.warn(e.data.message)}).catch(()=>{})}addTrack(e){return jA(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?VA.AUXILIARY:VA.MAIN," stream")),Pd()?yield this.addTrackByTransceiver(e,o):yield this.addTrackBySender(e)})}addTrackByTransceiver(e,o){return jA(this,null,function*(){var a;if(!e.mediaTrack)return;let c=this._peerConnection.getTransceivers();if(e.kind===VA.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 jA(this,null,function*(){if(!e.outMediaTrack)return;let o=e.outMediaTrack;tQ()&&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===VA.VIDEO&&e instanceof sQ&&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===V0||!this._peerConnection||!this._peerConnection.localDescription)return!1;let{sdp:e}=this._peerConnection.localDescription,o=Ic(e);for(let a=0;aa.sender&&a.sender.track===e.track)),this._peerConnection.removeTrack(e),o&&Ma(o.stop)&&(this._log.info("stop transceiver"),o.stop())}removeTrack(e){return jA(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?VA.AUXILIARY:VA.MAIN," stream")),Pd()?yield this.removeTrackByTransceiver(e,o):yield this.removeTrackBySender(e)})}removeTrackByTransceiver(e,o){return jA(this,null,function*(){if(!e.outMediaTrack)return;let a=this._peerConnection.getTransceivers();if(e.kind===VA.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 jA(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,f=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:f}))})}removeTrackBySender(e){return jA(this,null,function*(){if(!e.outMediaTrack)return;if(e.kind===VA.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===VA.VIDEO&&e.small&&this._peerConnection.getSenders().forEach(a=>{a.track&&a.track.kind===VA.VIDEO&&this.removeSender(a)})),yield this.updateOffer("remove",e.outMediaTrack)})}replaceTrack(e){return jA(this,null,function*(){var o;let a,c=(o=this._peerConnection)==null?void 0:o.getSenders();if(!c||c.length===0||!e.mediaTrack||(a=Pd()?e.kind===VA.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?VA.AUXILIARY:VA.MAIN," stream")),e.kind===VA.AUDIO?yield a.replaceTrack(e.outMediaTrack):e.kind===VA.VIDEO&&(d?c[3]&&(yield c[3].replaceTrack(e.outMediaTrack)):yield a.replaceTrack(e.outMediaTrack)),!0})}updateOffer(e,o){return jA(this,null,function*(){try{let a=yield this._peerConnection.createOffer(S5);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===VA.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:d5,data:d,responseCommand:cs.UPDATE_OFFER_RESULT,timeout:tx,commandDesc:"update offer"}),{code:f,message:S}=C.data;f!==0&&this.checkPublishResultCode(f,S),yield this.acceptAnswer(C.data.data),a.sdp&&this.updateSSRC(a.sdp)}catch(a){throw this._log.error(a),a}})}setBandwidth(e){return jA(this,arguments,function(o){var a=this;let{bandwidth:c,type:d,videoType:C,sdp:f}=o;return function*(){if(!gk())return f?d===VA.VIDEO?a.updateVideoBandwidthRestriction(f,c,C):a.updateAudioBandwidthRestriction(f,c):void 0;let S,b=a._peerConnection.getSenders();if(Pd()){let V=0;d===VA.VIDEO&&(V=C===VA.SMALL?2:C===VA.AUXILIARY?3:1),S=b[V]}else S=b.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")),f}catch(J){if(a._log.info("failed to set bandwidth by setting maxBitrate: ".concat(J)),f)return d===VA.VIDEO?a.updateVideoBandwidthRestriction(f,c,C):a.updateAudioBandwidthRestriction(f,c)}}return f}()})}updateVideoBandwidthRestriction(e,o,a){let c="AS";er&&(c="TIAS",o*=1e3);let d=0,C=-1;return a===VA.SMALL?d=1:a===VA.AUXILIARY&&(d=2),e=e.replace(/m=video (.*)\r\nc=IN (.*)\r\n/g,f=>(C+=1,C===d?"".concat(f,"b=").concat(c,":").concat(o,`\r +`):f)),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 +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 jA(this,null,function*(){try{yield this.exchangeSDP(),yield this.waitForPeerConnectionConnected()}catch(e){throw this.closePeerConnection(!0),this.uninstallEvents(),e}})}exchangeSDP(){return jA(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 jA(this,null,function*(){try{let e=yield this._peerConnection.createOffer(S5);yield this.setOffer(e),e.sdp&&this.updateSSRC(e.sdp)}catch(e){throw e}})}doExchangeSDP(){let e={command:h5,responseCommand:cs.PUBLISH_RESULT,data:{type:this._peerConnection.localDescription.type,sdp:this.removeVideoOrientation(this._peerConnection.localDescription.sdp),screen:this.localMainVideoTrack instanceof vM||this.localAuxVideoTrack instanceof vM,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=Ic(e);return c.media.forEach(d=>{(a==="all"||d.type===a)&&(d.direction=o)}),Cy(c)}acceptAnswer(e){return jA(this,null,function*(){var o,a,c,d,C;try{let f;if(this._publishingLocalAudioTrack||this._publishingLocalVideoTrack||this.isMainStreamPublished){let b=((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(b){let J=this._isPublishingAux?VA.AUXILIARY:VA.BIG;f=yield this.setBandwidth({bandwidth:b,type:VA.VIDEO,sdp:f,videoType:J})}V&&(f=yield this.setBandwidth({bandwidth:V,type:VA.AUDIO,sdp:f}))}if(f=this.removeVideoOrientation(e.sdp),(C=this._publishingLocalVideoTrack)!=null&&C.small){let{smallStreamConfig:b}=this._room;f=yield this.setBandwidth({bandwidth:this._publishingLocalVideoTrack.small.bitrate||b.bitrate,type:VA.VIDEO,videoType:VA.SMALL,sdp:f})}let S={type:e.type,sdp:f};yield this.setAnswer(S),this._log.debug("accepted answer: ".concat(f))}catch(f){throw this._log.error("failed to accept remote answer ".concat(f)),f}})}sendMutedFlag(e){e===this.localAuxAudioTrack||e===this.localAuxVideoTrack||(this._log.info("send muted state: ".concat(JSON.stringify(this._room.muteState))),this._signalChannel.send(C5,this._room.muteState))}getIsReconnecting(){return this._isReconnecting}reconnect(){return jA(this,null,function*(){if(!(MI(w6.prototype,this,"beforeReconnect").call(this)<0))try{yield this._signalChannel.sendWaitForResponse({command:U2,responseCommand:cs.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=Bp(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)&&U.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}updateSSRC(e){try{Ic(e).media.forEach((o,a)=>{if(o.type===VA.AUDIO){let c=o.ssrcs&&o.ssrcs[0];c&&(this.ssrc.audio=Number(c.id))}else{if(this._sdpSemantics===V0&&o.ssrcGroups)return void o.ssrcGroups.forEach((d,C)=>{let f=Number(d.ssrcs.split(" ")[0]);C===0?this.ssrc.video=f:C===1&&(this.ssrc.small=f)});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]:VA.VIDEO;if(this._peerConnection){let o=this._peerConnection.getSenders();if(e===VA.AUXILIARY&&o[3]&&o[3].track)return o[3].track.id;if(e===VA.VIDEO&&o[1]&&o[1].track)return o[1].track.id}if(this.localMainVideoTrack&&e===VA.VIDEO){let o=this.localMainVideoTrack.mediaTrack;if(o)return o.id}if(this.localAuxVideoTrack&&e===VA.AUXILIARY){let o=this.localAuxVideoTrack.mediaTrack;if(o)return o.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(e,o){if(e!==0)throw e===J0?(this._log.error(gc.NOT_SUPPORTED_H264ENCODE),new oi({code:lt.NOT_SUPPORTED_H264,message:Zo({key:So.NOT_SUPPORTED_H264ENCODE})})):new oi({code:lt.UNKNOWN,message:Zo({key:So.SIGNAL_RESPONSE_FAILED,data:{signalResponse:cs.PUBLISH_RESULT,code:e,message:o}})})}};di([Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=f=>{this._emitter.off("closed",C),d(new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.CONNECTION_ABORTED,data:f})}))};this._emitter.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this._emitter.off("closed",C)})})})],P2.prototype,"publish"),di([ly(521715,!1)],P2.prototype,"unpublish"),di([DM(qp.prototype.afterConnect),WW(qp.prototype.beforeConnect)],P2.prototype,"connect");var x2=P2,ztA=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 jA(this,null,function*(){var e,o,a,c,d,C,f;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},b=A.getPeerConnection(),V=A.getSSRC();if(b)try{if((this._spcStats||(yield b.getStats())).forEach(J=>{var cA,CA,vA,$A,he,Oe,Se,fi,Ne,dt,Ci,yi,Yo;let Vo,Qn;if(J.type==="outbound-rtp")if((J.mediaType||J.kind)===VA.VIDEO){if(J.ssrc===V.video?(Vo=VA.VIDEO,Qn=A.localMainVideoTrack):J.ssrc===V.small?Vo=VA.SMALL:J.ssrc===V.auxiliary&&(Qn=A.localAuxVideoTrack,Vo=VA.AUXILIARY),!Vo)return;S[Vo].bytesSent=J.bytesSent,S[Vo].packetsSent=J.packetsSent,S[Vo].framesEncoded=J.framesEncoded,xe(J.keyFramesEncoded)||(S[Vo].keyFramesEncoded=J.keyFramesEncoded),xe(J.nackCount)||(S[Vo].nackCount=J.nackCount),xe(J.pliCount)||(S[Vo].pliCount=J.pliCount),xe(J.retransmittedPacketsSent)||(S[Vo].retransmittedPacketsSent=J.retransmittedPacketsSent),xe(J.totalEncodeTime)||(S[Vo].totalEncodeTime=J.totalEncodeTime),xe(J.totalPacketSendDelay)||(S[Vo].totalPacketSendDelay=J.totalPacketSendDelay);let Jo=0;if(!xe(J.qpSum)&&!xe(J.framesEncoded)&&J.framesEncoded>0){let Ts=J.qpSum,Qg=J.framesEncoded,ma=Vo===VA.VIDEO?this._prevQpSum:this._prevAuxQpSum,gu=Vo===VA.VIDEO?((CA=(cA=A.localMainVideoTrack)==null?void 0:cA.stat)==null?void 0:CA.framesEncoded)||0:(($A=(vA=A.localAuxVideoTrack)==null?void 0:vA.stat)==null?void 0:$A.framesEncoded)||0;if(Qg>gu&&Ts>ma){let Yk=Ts-ma,$w=Qg-gu;Jo=Math.round(Yk/$w),Jo>35&&A.videoCodec==="h264"&&this._log.warn("".concat(Vo===VA.AUXILIARY?"aux ":"","video encoder QP is high: ").concat(Jo,", resolution: ").concat(J.frameWidth,"x").concat(J.frameHeight,", codec: ").concat(A.videoCodec,", "))}Vo===VA.VIDEO?this._prevQpSum=Ts:Vo===VA.AUXILIARY&&(this._prevAuxQpSum=Ts)}if(!xe(J.encoderImplementation)&&(Vo===VA.VIDEO&&this._prevEncoderImplementation!==J.encoderImplementation||Vo===VA.AUXILIARY&&this._prevAuxEncoderImpl!==J.encoderImplementation)){let Ts=2,Qg=this._prevEncoderImplementation;Vo===VA.AUXILIARY&&(Ts=7,Qg=this._prevAuxEncoderImpl),U.emit("262",{userId:A.userId,streamType:Ts,prevImplementation:Qg,implementation:J.encoderImplementation,codec:A.videoCodec,isHWCodec:J.powerEfficientEncoder}),this[Vo===VA.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?!xe(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevQualityLimitationReason!==J.qualityLimitationReason&&(Qn?.log.info("qualityLimitationReason change to ".concat(J.qualityLimitationReason)),U.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevQualityLimitationReason,streamType:2,isQosClearFirst:(he=A.localMainVideoTrack)==null?void 0:he.isQosClearFirst}),this._prevQualityLimitationReason=J.qualityLimitationReason):J.ssrc===V.auxiliary&&!xe(J.qualityLimitationReason)&&J.bytesSent!==0&&this._prevAuxQualityLimitationReason!==J.qualityLimitationReason&&(this._log.info("aux qualityLimitationReason change to ".concat(J.qualityLimitationReason)),U.emit("263",{userId:A.userId,reason:J.qualityLimitationReason,prevReason:this._prevAuxQualityLimitationReason,streamType:7,isQosClearFirst:(Oe=A.localAuxVideoTrack)==null?void 0:Oe.isQosClearFirst}),this._prevAuxQualityLimitationReason=J.qualityLimitationReason)}else S.audio.bytesSent=J.bytesSent,S.audio.packetsSent=J.packetsSent;else if(J.type==="candidate-pair")lM(J)&&(this.totalBytesSent=J.bytesSent,bn(J.currentRoundTripTime)&&(S.rtt=Math.floor(1e3*J.currentRoundTripTime)));else if(J.type==="media-source"){if(J.kind===VA.AUDIO)S.audio.audioLevel=J.audioLevel||0,S.audio.totalAudioEnergy=J.totalAudioEnergy||0,J.echoReturnLoss,xe((Ne=(fi=(Se=A.localMainAudioTrack)==null?void 0:Se.sourceTrack)==null?void 0:fi.stats)==null?void 0:Ne.deliveredFramesDuration)?J.totalSamplesDuration&&(S.audio.totalSamplesDuration=J.totalSamplesDuration):S.audio.totalSamplesDuration=A.localMainAudioTrack.sourceTrack.stats.deliveredFramesDuration/1e3;else if(J.kind===VA.VIDEO)if(J.trackIdentifier===A.getVideoTrackId(VA.VIDEO))if((yi=(Ci=(dt=A.localMainVideoTrack)==null?void 0:dt.sourceTrack)==null?void 0:Ci.stats)!=null&&yi.deliveredFrames){let{deliveredFrames:Jo}=A.localMainVideoTrack.sourceTrack.stats;S.video.framesCaptured=Jo,A.localMainVideoTrack.stat.framesCaptured&&A.localMainVideoTrack.stat.framesCaptured>0&&Jo>=A.localMainVideoTrack.stat.framesCaptured?S.video.fpsCapture=Math.floor((Jo-A.localMainVideoTrack.stat.framesCaptured)/this.statInterval):S.video.fpsCapture=J.framesPerSecond}else S.video.fpsCapture=J.framesPerSecond;else J.trackIdentifier===A.getVideoTrackId(VA.AUXILIARY)?S.auxiliary.fpsCapture=J.framesPerSecond:S.small.fpsCapture=J.framesPerSecond}if(!xe(J.audioLevel)&&(Yo=A.localMainAudioTrack)!=null&&Yo.mediaTrack&&J.trackIdentifier===A.localMainAudioTrack.mediaTrack.id&&(S.audio.audioLevel=J.audioLevel||0),!xe(J.frameWidth)){let Jo=VA.SMALL;J.trackIdentifier===A.getVideoTrackId(VA.VIDEO)||J.ssrc===V.video?Jo=VA.VIDEO:(J.trackIdentifier===A.getVideoTrackId(VA.AUXILIARY)||J.ssrc===V.auxiliary)&&(Jo=VA.AUXILIARY),S[Jo].frameWidth=J.frameWidth,S[Jo].frameHeight=J.frameHeight,S[Jo].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&&!xe((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: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((C=(d=J?.sourceTrack)==null?void 0:d.stats)!=null&&C.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===VA.AUDIO?(A.localMainAudioTrack&&(A.localMainAudioTrack.stat=S[J]),A.localAuxAudioTrack&&(A.localAuxAudioTrack.stat=S[J])):J===VA.VIDEO?A.localMainVideoTrack&&(A.localMainVideoTrack.stat=S[J]):J===VA.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=((f=this.room.networkQuality)==null?void 0:f.uplinkRTT)||0),S})}getReceiverStats(A){return jA(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:f,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 vA=(J.mediaType||J.kind)===VA.AUDIO;if(vA){if(J.ssrc!==C.audio||!f.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&&f.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=El[(cA=this._decodeMap.get(J.codecId))==null?void 0:cA.mimeType.split("/")[1]]||"h264",c.video.codec=A.videoCodec,$A=A.remoteVideoTrack,f.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)),U.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)),xe(J.keyFramesDecoded)||$A.updateKeyFramesDecoded(J.keyFramesDecoded)),J.ssrc===C.auxiliary&&f.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",xe(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&&(vA?(c.audio.totalJitter=J.jitterBufferDelay,c.audio.totalJitterCount=J.jitterBufferEmittedCount,c.audio.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===C.video&&f.hasVideo?(c.video.totalJitter=J.jitterBufferDelay,c.video.totalJitterCount=J.jitterBufferEmittedCount,c.video.estimatedPlayoutTimestamp=J.estimatedPlayoutTimestamp):J.ssrc===C.auxiliary&&f.hasAuxiliary&&(c.auxiliary.totalJitter=J.jitterBufferDelay,c.auxiliary.totalJitterCount=J.jitterBufferEmittedCount))}else J.type==="candidate-pair"&&lM(J)&&(this.totalBytesReceived=J.bytesReceived,bn(J.currentRoundTripTime)&&(c.rtt=Math.floor(1e3*J.currentRoundTripTime)));xe(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)),!xe(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),xe((e=A.remoteVideoTrack.player.stat)==null?void 0:e.fps)||(c.video.fpsRender=A.remoteVideoTrack.player.stat.fps),xe((o=A.remoteAuxiliaryTrack.player.stat)==null?void 0:o.fps)||(c.auxiliary.fpsRender=A.remoteAuxiliaryTrack.player.stat.fps);let b=c.audio.estimatedPlayoutTimestamp,V=c.video.estimatedPlayoutTimestamp;if(b&&V&&A.remoteAudioTrack.isAvailable&&A.remoteVideoTrack.isAvailable){let J=V-b;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 jA(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=bo(),f=yield d.getStats(),S=bo();S-C>2e3&&this._log.warn("getStats cost ".concat(S-C,"ms"));let b=[],V=new Set(["inbound-rtp","outbound-rtp","track","candidate-pair","media-source","codec","media-playout"]);f.forEach(J=>V.has(J.type)&&b.push(J)),this._spcStats=b}A&&(a=yield this.getSenderStats(A));for(let[d,C]of e){let f=yield this.getReceiverStats(C);f&&c.push(f)}return e.size&&(o=this.getMediaPlayoutStats(this._spcStats)),{senderStats:a,receiverStats:c,mediaPlayoutStats:o}})}getDifferenceValue(A,e){if(Jp(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,f,S,b,V,J,cA,CA;if(!Jp(e.senderStats)){let Ne={uint32_audio_level:e.senderStats.audio.audioLevel*qE,uint32_audio_energy:1e6*(e.senderStats.audio.totalAudioEnergy||0),uint32_audio_codec_bitrate:e.senderStats.audio.bytesSent};e.senderStats.audio.micAudioLevel&&(Ne.uint32_mic_audio_level=e.senderStats.audio.micAudioLevel*qE),xe(e.senderStats.audio.audioCaptureEnergyAfter3a)||(Ne.uint32_audio_capture_energy_after3a=e.senderStats.audio.audioCaptureEnergyAfter3a*qE),e.senderStats.audio.totalSamplesDuration&&(o.msg_device_info.uint32_audio_capture_cost=e.senderStats.audio.totalSamplesDuration);let dt=[];if(e.senderStats.video.bytesSent){let yi={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};dt.push(yi)}if(e.senderStats.small.bytesSent){let yi={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};dt.push(yi)}if(e.senderStats.auxiliary.bytesSent){let yi={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};dt.push(yi)}let Ci={uint32_bitrate:0,uint32_lost:0,uint32_rtt:e.senderStats.rtt};o.msg_up_stream_info={msg_audio_status:Ne,msg_video_status:dt,msg_network_status:Ci}}let{statInterval:vA}=this;o.msg_down_stream_info=[],e.receiverStats.forEach(Ne=>{let dt={msg_user_info:{str_identifier:Ne.userId,uint64_tinyid:Ne.tinyId},msg_network_status:{uint32_rtt:Ne.rtt,uint32_bitrate:0,uint32_lost:0},msg_audio_status:{},msg_video_status:[]};if(Ne.hasAudio){let Ci={uint32_audio_p2p_delay:Ne.audio.p2pDelay,uint32_audio_cache_ms:Ne.audio.totalJitter,uint32_audio_cache_ms_count:Ne.audio.totalJitterCount,uint32_audio_codec_bitrate:Ne.audio.bytesReceived,uint32_audio_total_bitrate:Ne.audio.bytesReceived,uint32_audio_level:1e8*Ne.audio.audioLevel,uint32_audio_energy:1e6*Ne.audio.totalAudioEnergy,uint32_audio_receive:Ne.audio.packetsReceived,uint32_audio_origin_lost:Ne.audio.packetsLost};dt.msg_audio_status=Ci}if(Ne.hasVideo){let Ci=a.get("".concat(Ne.userId,"_").concat(P0)),yi=Ci?Ci.duration:0,Yo={uint32_video_stream_type:Ne.isSmallSubscribed?3:2,uint32_video_receive_fps:Ne.video.framesReceived,uint32_video_width:Ne.video.frameWidth,uint32_video_height:Ne.video.frameHeight,uint32_video_codec_bitrate:Ne.video.bytesReceived,uint32_video_receive:Ne.video.packetsReceived,uint32_video_origin_lost:Ne.video.packetsLost,uint32_video_block_time:yi,uint32_video_dec_fps:Ne.video.framesDecoded,uint32_video_codec_fps:Ne.video.fpsRender,uint32_video_cache_ms:Ne.video.totalJitter,uint32_video_cache_ms_count:Ne.video.totalJitterCount,uint32_video_p2p_delay:Ne.video.p2pDelay,uint32_video_codec:Ne.video.codec,int32_video_audio_relative_delay:Ne.avSyncDelay+5e3};dt.msg_video_status.push(Yo)}if(Ne.hasAuxiliary){let Ci=a.get("".concat(Ne.userId,"_").concat(XG)),yi=Ci?Ci.duration:0,Yo={uint32_video_stream_type:7,uint32_video_receive_fps:Ne.auxiliary.framesReceived,uint32_video_width:Ne.auxiliary.frameWidth,uint32_video_height:Ne.auxiliary.frameHeight,uint32_video_codec_bitrate:Ne.auxiliary.bytesReceived,uint32_video_receive:Ne.auxiliary.packetsReceived+Ne.auxiliary.packetsLost,uint32_video_origin_lost:Ne.auxiliary.packetsLost,uint32_video_block_time:yi,uint32_video_dec_fps:Ne.auxiliary.framesDecoded,uint32_video_codec_fps:Ne.video.fpsRender,uint32_video_cache_ms:Ne.auxiliary.totalJitter,uint32_video_cache_ms_count:Ne.auxiliary.totalJitterCount,uint32_video_p2p_delay:Ne.auxiliary.p2pDelay,uint32_video_codec:Ne.video.codec};dt.msg_video_status.push(Yo)}o.msg_down_stream_info.push(dt)}),e.mediaPlayoutStats&&!Jp(e.mediaPlayoutStats)&&(e.mediaPlayoutStats.synthesizedSamplesDuration*=1e3,e.mediaPlayoutStats.totalSamplesDuration*=1e3);let $A=this._prevReport,he=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 Ne=$A.msg_up_stream_info.msg_audio_status,dt=o.msg_up_stream_info.msg_audio_status;if(Ne.uint32_audio_codec_bitrate===0)dt.uint32_audio_codec_bitrate=0;else{let Ci=this.getDifferenceValue(Ne.uint32_audio_codec_bitrate,dt.uint32_audio_codec_bitrate);dt.uint32_audio_codec_bitrate=Math.round(8*Ci/vA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=dt.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)/vA),o.msg_device_info.uint32_audio_capture_cost>0&&((f=c?.localMainAudioTrack)==null||f.updateAfter3aSilenceStartTime((C=e.senderStats.audio.audioCaptureEnergyAfter3a)!=null?C:e.senderStats.audio.micAudioLevel))):delete o.msg_device_info.uint32_audio_capture_cost}let Oe=$A.msg_up_stream_info.msg_video_status;o.msg_up_stream_info.msg_video_status.forEach(Ne=>{let dt=Oe.find(Qn=>Qn.uint32_video_stream_type===Ne.uint32_video_stream_type);if(!dt||dt.uint32_video_codec_bitrate===0)return Ne.uint32_video_codec_bitrate=0,Ne.uint32_video_enc_fps=0,void(Ne.uint32_video_codec_fps=0);let Ci=0,yi=0,Yo=0;dt&&Ne.uint32_video_codec_bitrate>=dt.uint32_video_codec_bitrate&&(Ci=dt.uint32_video_codec_bitrate,yi=dt.uint32_video_enc_fps,Yo=dt.uint32_video_codec_fps);let Vo=this.getDifferenceValue(Ci,Ne.uint32_video_codec_bitrate);Ne.uint32_video_codec_bitrate=Math.round(8*Vo/vA),o.msg_up_stream_info.msg_network_status.uint32_bitrate+=Ne.uint32_video_codec_bitrate,Ne.uint32_video_enc_fps=Math.round(this.getDifferenceValue(yi,Ne.uint32_video_enc_fps)/vA),Ne.uint32_video_codec_fps=Math.round(this.getDifferenceValue(Yo,Ne.uint32_video_codec_fps)/vA),dt.uint32_video_width===0&&dt.uint32_video_height===0&&dt.uint32_video_codec_fps===0&&(Ne.uint32_video_codec_fps=Ne.uint32_video_enc_fps),xe(dt.uint32_key_frame_count)||(Ne.uint32_key_frame_count=Math.round(this.getDifferenceValue(dt.uint32_key_frame_count,Ne.uint32_key_frame_count))),xe(dt.uint32_nack_count)||(Ne.uint32_nack_count=Math.round(this.getDifferenceValue(dt.uint32_nack_count,Ne.uint32_nack_count))),xe(dt.uint32_pli_count)||(Ne.uint32_pli_count=Math.round(this.getDifferenceValue(dt.uint32_pli_count,Ne.uint32_pli_count))),xe(dt.uint32_video_arq_packets)||(Ne.uint32_video_arq_packets=Math.round(this.getDifferenceValue(dt.uint32_video_arq_packets,Ne.uint32_video_arq_packets))),xe(dt.uint32_encode_cost)||(Ne.uint32_encode_cost=Math.round(this.getDifferenceValue(dt.uint32_encode_cost,Ne.uint32_encode_cost)/vA)),xe(dt.uint32_send_packet_cost)||(Ne.uint32_send_packet_cost=Math.round(this.getDifferenceValue(dt.uint32_send_packet_cost,Ne.uint32_send_packet_cost)/vA))});let Se=$A.msg_down_stream_info;o.msg_down_stream_info=o.msg_down_stream_info.filter(Ne=>Se.find(dt=>dt.msg_user_info.uint64_tinyid===Ne.msg_user_info.uint64_tinyid));let fi=o.msg_down_stream_info;if(fi.forEach(Ne=>{let dt=Se.find(Ci=>Ci.msg_user_info.uint64_tinyid===Ne.msg_user_info.uint64_tinyid);if(Jp(Ne.msg_audio_status)||Jp(dt.msg_audio_status))Ne.msg_audio_status={};else{let Ci=Ne.msg_audio_status,yi=dt.msg_audio_status,Yo=this.getDifferenceValue(yi.uint32_audio_cache_ms_count,Ci.uint32_audio_cache_ms_count);delete Ci.uint32_audio_cache_ms_count,Ci.uint32_audio_cache_ms=Math.floor(1e3*this.getDifferenceValue(yi.uint32_audio_cache_ms,Ci.uint32_audio_cache_ms)/Yo)||0;let Vo=this.room.remotePublishedUserMap.get(Ne.msg_user_info.str_identifier);Vo&&(Vo.remoteAudioTrack.stat.jitterBufferDelay=Ci.uint32_audio_cache_ms),Ci.uint32_audio_origin_lost=this.getDifferenceValue(yi.uint32_audio_origin_lost,Ci.uint32_audio_origin_lost),Ci.uint32_audio_receive=this.getDifferenceValue(yi.uint32_audio_receive,Ci.uint32_audio_receive),Ci.uint32_audio_receive+=Ci.uint32_audio_origin_lost;let Qn=this.getDifferenceValue(yi.uint32_audio_codec_bitrate,Ci.uint32_audio_codec_bitrate);Ci.uint32_audio_codec_bitrate=Math.round(8*Qn/vA),Ci.uint32_audio_total_bitrate=Math.round(8*Qn/vA)}if(Ne.msg_video_status&&dt.msg_video_status){let Ci=dt.msg_video_status;Ne.msg_video_status=Ne.msg_video_status.filter(yi=>Ci.find(Yo=>Yo.uint32_video_stream_type===yi.uint32_video_stream_type)),Ne.msg_video_status.forEach(yi=>{let Yo=Ci.find($w=>$w.uint32_video_stream_type===yi.uint32_video_stream_type),Vo=Yo.uint32_video_receive,Qn=Yo.uint32_video_origin_lost,Jo=Yo.uint32_video_codec_bitrate,Ts=Yo.uint32_video_receive_fps,Qg=Yo.uint32_video_dec_fps;yi.uint32_video_origin_lost=this.getDifferenceValue(Qn,yi.uint32_video_origin_lost),yi.uint32_video_receive=this.getDifferenceValue(Vo,yi.uint32_video_receive)+yi.uint32_video_origin_lost;let ma=this.getDifferenceValue(Jo,yi.uint32_video_codec_bitrate);yi.uint32_video_codec_bitrate=Math.round(8*ma/vA);let gu=this.getDifferenceValue(Ts,yi.uint32_video_receive_fps);yi.uint32_video_receive_fps=Math.round(gu/vA),yi.uint32_video_dec_fps=Math.round(this.getDifferenceValue(Qg,yi.uint32_video_dec_fps)/vA);let Yk=this.getDifferenceValue(Yo.uint32_video_cache_ms_count,yi.uint32_video_cache_ms_count);delete yi.uint32_video_cache_ms_count,yi.uint32_video_cache_ms=Math.floor(1e3*this.getDifferenceValue(Yo.uint32_video_cache_ms,yi.uint32_video_cache_ms)/Yk)||0})}}),!xe((S=he?.mediaPlayoutStats)==null?void 0:S.totalSamplesDuration)&&!xe((b=e.mediaPlayoutStats)==null?void 0:b.totalSamplesDuration)){let Ne=2*Math.floor(this.getDifferenceValue((V=he?.mediaPlayoutStats)==null?void 0:V.synthesizedSamplesDuration,(J=e.mediaPlayoutStats)==null?void 0:J.synthesizedSamplesDuration)/vA),dt=2*Math.floor(this.getDifferenceValue((cA=he?.mediaPlayoutStats)==null?void 0:cA.totalSamplesDuration,(CA=e.mediaPlayoutStats)==null?void 0:CA.totalSamplesDuration)/vA);o.msg_device_info.uint32_audio_play_cost=dt-Ne}return he&&e.receiverStats.forEach(Ne=>{if(Ne.audio.concealedSamples&&Ne.audio.totalSamplesReceived){let dt=he.receiverStats.find(Ci=>Ci.userId===Ne.userId);if(dt&&dt.audio.concealedSamples&&dt.audio.totalSamplesReceived){let Ci=(Ne.audio.silentConcealedSamples||0)-(dt.audio.silentConcealedSamples||0),yi=Ne.audio.concealedSamples-dt.audio.concealedSamples,Yo=Ne.audio.totalSamplesReceived-dt.audio.totalSamplesReceived,Vo=Math.floor((yi-Ci)/Yo*1e3*vA);if(Vo>1e3*vA/5){let Qn=fi.find(Jo=>Jo.msg_user_info.str_identifier===Ne.userId);Qn&&(Qn.msg_audio_status.uint32_audio_block_time=Vo)}}}}),o.msg_down_stream_info.forEach(Ne=>{Ne.msg_video_status.forEach(dt=>{dt.uint32_video_codec_bitrate===0&&dt.uint32_video_receive_fps===0&&(dt.uint32_video_width=0,dt.uint32_video_height=0)})}),o}getStatsReport(A){return jA(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}}]},f=yield o.getStats(a,c);return JSON.stringify(o._prevReport)==="{}"&&(o._prevReport=JSON.parse(JSON.stringify(C))),o.prepareReport({stats:f,report:C,freezeMap:d,uplinkConnection:a}),o._prevReportTime=Date.now(),C}()})}getMediaPlayoutStats(A){let e;if(va(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)})}},ZtA=ac(Jl());function XtA(A){return new Promise(e=>jA(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 f={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 b of S)if(b.name===C){let V=Math.round(b.duration),J=Math.max(Math.round(b.domainLookupStart-b.startTime),0),cA=b.redirectStart>0?Math.max(Math.round(b.redirectEnd-b.redirectStart),0):0,CA=b.fetchStart>0?Math.max(Math.round(b.domainLookupStart-b.fetchStart),0):0,vA=Math.round(b.domainLookupEnd-b.domainLookupStart),$A=Math.round(b.requestStart-b.secureConnectionStart),he=Math.round(b.secureConnectionStart-b.connectStart),Oe=Math.round(b.responseStart-b.requestStart),Se=Math.round(b.responseEnd-(b.responseStart||b.startTime));f=Bo(pi({},f),{totalCost:V,local:J,redirect:cA,httpCache:CA,dns:vA,tcp:he,tls:$A,request:Oe,response:Se});break}}catch{}return f}(c);d.totalCost===0&&(d.totalCost=Date.now()-a),e(d)}))}var Y2=class g_ extends ZtA.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>g_.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>g_.HISTORY_SIZE&&this._downlinkQualityHistory.shift()}initialize(){this._signalChannel.on(cs.UPLINK_NETWORK_STATS,e=>{this.handleUplinkNetworkQuality(e)}),this._signalChannel.on(mK,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,f=c.recvAudPkg+c.recvVidPkg,S=C-f;C===0&&f===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 jA(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(f=>{let S=f.getPeerConnection();return!(!S||o.has(S))&&(o.add(S),!0)}),c=a.filter(f=>{var S;return((S=f.getPeerConnection())==null?void 0:S.connectionState)===Eo.CONNECTED});if(a.filter(f=>this.isPeerConnectionDisconnected(f.getPeerConnection())).length===e.length)return void(this.downlinkNetworkQuality=6);for(let f=0;f{this.isPeerConnectionDisconnected(f)&&(this._downlinkPrevStatMap.delete(f),this._downlinkLossAndRTTMap.delete(f))}),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 jA(this,null,function*(){let o={rtt:0,totalPacketsLost:0,totalPacketsReceived:0};if(!e||!sy())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===VA.AUDIO||d.mediaType===VA.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!==Eo.DISCONNECTED&&e.connectionState!==Eo.FAILED&&e.connectionState!==Eo.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=_r.run("ric",()=>{var e;this.handleDownlinkNetworkQuality();let o=[...this._downlinkLossAndRTTMap.values()];U.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=Bo(pi({},c),{pingResults:this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold?this.pingResults:{}})),this.emit(g_.EVENT_NETWORK_QUALITY,c);let d=Date.now();if(a&&(this.uplinkRTT>a.rttThreshold||this.downlinkRTT>a.rttThreshold)&&d-g_.lastPingTime>1e3*a.interval){g_.lastPingTime=Date.now();let C=a.domain.map(f=>XtA(f).then(S=>({domain:f,cost:S.totalCost})));Promise.all(C).then(f=>{this.pingResults.isPoorNetwork=f.some(S=>S.cost>700),this.pingResults.timestamp=d,this.pingResults.data=f,f.forEach(S=>{Ai.addSuccessEvent({key:521718,cost:S.cost})}),this._log.warn("All ping results: ".concat(JSON.stringify(f)))}).catch(f=>{this._log.warn("Error during pinging domains: ".concat(f))})}},{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&&(_r.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,f=o.get(c);if(f){let S=this._room.remotePublishedUserMap.get(f);S?.setDelay({videoDelay:d,audioDelay:C})}})}};Y(Y2,"HISTORY_SIZE",10),Y(Y2,"EVENT_NETWORK_QUALITY","0"),Y(Y2,"lastPingTime",0);var M5=Y2,v5=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")&&Ma(this[e])&&(this[e]=function(o){let{fn:a,context:c}=o;return function(){try{for(var d=arguments.length,C=new Array(d),f=0;fQA.error("".concat(a.name,"() error observed ").concat(b))):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:kd,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,iM().then(()=>{this._basicInfo.string_os_version=Np(),this._basicInfo.string_device_name=ZB()||this._basicInfo.string_os_version})}addEvent(A,e){return this._eventMap.set(A,e),U.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===VA.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,f=a.hasAuxiliary;!c&&C&&this.handleRemoteStreamAdded(a.userId,"main"),!d&&f&&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)=>U.off(e,A)),this._eventMap.clear()}destroy(){this.uninstallEvents(),_r.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&&(xe(A.params.frameWorkType)||(this._frameWorkType=A.params.frameWorkType,this._basicInfo.uint32_framework=this._frameWorkType),xe(A.params.component)||(this._component=A.params.component,this._basicInfo.uint32_component=this._component),xe(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:f,request:S,response:b}=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=f,this._pathJoinRoom.int32_schedule_request=S,this._pathJoinRoom.int32_schedule_response=b}}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 oi?Number(o.getExtraCode()||o.getCode()):lt.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=bo()-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 oi?Number(o.getExtraCode()||o.getCode()):lt.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:Bo(pi({},$tA),{msg_user_info:new vK({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:f}=o,S=new vK({userId:d,tinyId:C,role:f==="anchor"?20:21}),b=Date.now(),V="".concat(d,"_").concat(a),J=this._remoteStreamStatMap.get(V);J&&J.subscribeStartTime===0&&(J.subscribeStartTime=b),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:b}),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:b})):o.muteState.hasAuxiliary&&c.auxiliary&&!this._pathAuxiliaryMap.has(V)&&this._pathAuxiliaryMap.set(V,{sendSubscribeCMDTime:b})}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,Ai.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,f=this._networkQuality.totalDownlinkRTTAndLossMap.get(c);if(f)f.totalRTT+=o,f.totalLoss+=a,d&&(f.totalVideoDelay=(f.totalVideoDelay||0)+d,f.videoDelayCount=(f.videoDelayCount||0)+1),C&&(f.totalAudioDelay=(f.totalAudioDelay||0)+C,f.audioDelayCount=(f.audioDelayCount||0)+1),f.count++;else{let S,b,V,J;d&&(b=d,V=1),C&&(S=C,J=1),this._networkQuality.totalDownlinkRTTAndLossMap.set(c,{totalRTT:o,totalLoss:a,count:1,totalAudioDelay:S,totalVideoDelay:b,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:f,uint32_video_height:S}=a.msg_video_status[0];this._localStreamStat.totalVideoBitrate+=d,this._localStreamStat.totalVideoFPS+=C,this._localStreamStat.totalVideoWidth+=f,this._localStreamStat.totalVideoHeight+=S,this._localStreamStat.videoCount++}if(a.msg_audio_status){let{uint32_audio_level:d}=a.msg_audio_status;Math.floor(d/qE*100)>0&&(this._localStreamStat.totalAudioLevel+=d/qE,this._localStreamStat.audioLevelCount++)}c.forEach(d=>{let{msg_user_info:C,msg_audio_status:f,msg_video_status:S}=d,b=C.str_identifier,V=this._room.remotePublishedUserMap.get(b);if(S.forEach(J=>{let cA=J.uint32_video_stream_type===2,CA=J.uint32_video_stream_type===7,vA="".concat(b,"_").concat(cA?"main":"auxiliary"),$A=this._remoteStreamStatMap.get(vA);if($A&&(cA&&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 he=cA?V.remoteVideoTrack:V.remoteAuxiliaryTrack;he.stat.jitterBufferDelay&&($A.videoJitterBufferDelay=he.stat.jitterBufferDelay),he.stat.framesReceived&&($A.statsToReport.uint32_video_consume_render_rate=Math.floor(he.stat.framesDecoded/he.stat.framesReceived*fS(10,6)))}}),!iw(f)){let J="".concat(b,"_main"),cA=this._remoteStreamStatMap.get(J);this._remoteStreamStatMap.has(J)&&cA&&V!=null&&V.remoteAudioTrack.isSubscribed&&(cA.totalAudioBitrate+=f.uint32_audio_codec_bitrate,cA.audioCount++,V.remoteAudioTrack.stat.jitterBufferDelay&&(cA.audioJitterBufferDelay=V.remoteAudioTrack.stat.jitterBufferDelay),Math.floor(f.uint32_audio_level/qE*100)>0&&(cA.totalAudioLevel+=f.uint32_audio_level/qE,cA.audioLevelCount++),f.uint32_audio_block_time&&(cA.statsToReport.uint32_audio_block_time+=f.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 oi?o.getExtraCode()||o.getCode():lt.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&vS)>=0}hasAudioFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&wS)>=0}hasAuxFlag(A){return this._firstPublishedUserList.findIndex(e=>e.userId===A&&e.flag&RS)>=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:b,count:V,audioDelayCount:J,videoDelayCount:cA,totalAudioDelay:CA,totalVideoDelay:vA}=a;A.statsToReport.uint32_avg_down_loss=Math.floor(b/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&&vA&&(A.statsToReport.uint32_video_network_p2p_delay=Math.floor(vA/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:c}=this._room;c&&(A.statsToReport.uint32_audio_play_time=c.getDuration(e,VA.AUDIO),A.statsToReport.uint32_video_play_time=c.getDuration(e,VA.VIDEO)),A.statsToReport.uint32_video_render_first&&(A.statsToReport.uint32_video_render_first=Math.min(A.statsToReport.uint32_video_render_first,GM));let{badCaseDetector:d}=this._room,{dataFreeze:C,count:f}=d.getDataFreezeDuration(e),{renderFreeze:S}=d.getRenderFreezeDuration(e);A.statsToReport.uint32_video_block_count=f,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>GM&&(A.statsToReport.uint64_play_first_frame_time=A.statsToReport.uint64_start_enter_time+GM):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>GM&&(A.statsToReport.uint64_render_first_frame_time=A.statsToReport.uint64_start_enter_time+GM):this._pathMainVideoMap.delete(e)}),this._pathJoinRoom.uint64_end_time-this._pathJoinRoom.uint64_start_time>GM&&(this._pathJoinRoom.uint64_end_time=this._pathJoinRoom.uint64_start_time+GM)}getReportData(){this._basicInfo.uint32_networkType=Lf();let A={uint32_sdk_app_id:Number(this._room.sdkAppId),msg_user_info:new vK({userId:this._room.userId,tinyId:this._room.tinyId,role:this._room.role==="anchor"?20:21}),msg_basic_info:this._basicInfo,uint32_acc_ip:PS(this._signalInfo.relayIp),uint32_client_ip:PS(this._signalInfo.clientIp,!1),uint32_acc_port:this._signalInfo.relayPort||0,uint64_timestamp:Date.now(),uint32_seq:Math.floor(Math.random()*fS(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:PS(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 nw(A),A}report(){return jA(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 jA(this,null,function*(){if(A.msg_path_enter_room.uint64_start_time===0)return;let e=Number(this._room.sdkAppId),o=TA.enable?JB(A,2001,e):yield pb(A),a=o instanceof ArrayBuffer,c="".concat(kf(e,RI.KEY_POINT),"&gzip=").concat(+a),d=!1;navigator.sendBeacon&&(d=navigator.sendBeacon(c,o));let C=[this.uploadKVStat(Ai),this.uploadKVStat(Ph)];d||C.push(HB({url:c,body:o,priority:"low"})),yield Promise.all(C)})}setConnectionType(A){this.connectionType=A,this._basicInfo.uint32_connection_type=A}uploadKVStat(A){return jA(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=Bo(pi({},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 f=TA.enable?JB(C,2003,a):yield pb(C),S=f instanceof ArrayBuffer,b="".concat(kf(+a,RI.KV_STAT),"&gzip=").concat(+S),V=!1;navigator.sendBeacon&&(V=navigator.sendBeacon(b,f)),V||HB({url:b,body:f})}()})}};di([Yh({settings:{timeout:500,retries:3}})],v5.prototype,"upload");var GM=5e3,$tA={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},vK=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}},AiA=v5,R5=class{constructor(){Y(this,"_startTime"),Y(this,"_endTime"),this._startTime=0,this._endTime=0,this.start()}start(){this._startTime===0&&(this._startTime=bo())}stop(){this._endTime===0&&(this._endTime=bo())}getDuration(){return this._endTime===0?bo()-this._startTime:this._endTime-this._startTime}get startTime(){return this._startTime}get endTime(){return this._endTime}},eiA=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"),VA.AUDIO),o.hasVideo&&!a.hasVideo&&this.stopDurationItem("".concat(d,"_main"),VA.VIDEO),o.hasAuxiliary&&!a.hasAuxiliary&&this.stopDurationItem("".concat(d,"_auxiliary"),VA.VIDEO);let C=(c=this._room)==null?void 0:c.remotePublishedUserMap.get(d);C&&(!o.hasAudio&&a.hasAudio&&C.remoteAudioTrack.isSubscribed&&this.addDuractionItem(d,VA.AUDIO,"main"),!o.hasVideo&&a.hasVideo&&C.remoteVideoTrack.isSubscribed&&this.addDuractionItem(d,VA.VIDEO,"main"),!o.hasAuxiliary&&a.hasAuxiliary&&C.remoteAuxiliaryTrack.isSubscribed&&this.addDuractionItem(d,VA.VIDEO,"auxiliary"))}),this._eventMap.forEach((A,e)=>U.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>U.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 R5,d=this._durationMap.get(a);d?this.isRecording(d[e])||d[e].push(c):this._durationMap.set(a,{userId:A,type:o,audio:e===VA.AUDIO?[c]:[],video:e===VA.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()}},tiA=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:(hg||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()}},iiA=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 tiA),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===VA.VIDEO){if(o==="PLAYING"){let d="".concat(e.userId,"_").concat(e.streamType);this._isVideoPlayingEventFiredMap.set(d,!0)}a===VA.MUTE?this.onVideoTrackMuted(e):a===VA.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)=>U.on(e,A,this))}uninstallEvents(){this._eventMap.forEach((A,e)=>U.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 R5;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=bo();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 f=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-decode"));f&&C-f>this.ABNORMAL_TIME_LOWER_LIMIT&&C-f=this.ABNORMAL_TIME_UPPER_LIMIT&&(on.uploadEvent({userId:this._room.userId,log:"stat-".concat(Va.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 f=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));if(f&&C-f>this.ABNORMAL_TIME_LOWER_LIMIT/2&&C-f<2*this.ABNORMAL_TIME_UPPER_LIMIT){on.uploadEvent({userId:this._room.userId,log:"stat-".concat(Va.VIDEO_HARDWARE_DECODE_FAILED)});let S=this._room.remotePublishedUserMap.get(a);if(S){let b=d.uint32_video_stream_type===2?S.remoteVideoTrack:S.remoteAuxiliaryTrack;b&&(b.log.warn("decode failed during call"),b.emit("decode-failed-during-call"))}}}else this._remoteVideoAbnormalTimestampMap.set("".concat(a,"-hardware"),C);else{let f=this._remoteVideoAbnormalTimestampMap.get("".concat(a,"-hardware"));f&&C-f>=2*this.ABNORMAL_TIME_UPPER_LIMIT&&(on.uploadEvent({userId:this._room.userId,log:"stat-".concat(Va.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=bo();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&&on.uploadEvent({userId:this._room.userId,log:"stat-".concat(Va.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=bo();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&&on.uploadEvent({userId:this._room.userId,log:"stat-".concat(Va.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>eb){let f=this._monitorFreezeData.get(e,"data");this._monitorFreezeData.set(e,{userId:o,type:a,duration:f?f.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!==VA.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=(f,S)=>{var b;if(c){let V=e.decodeFPS,J=V>0&&V<=5?600+1e3/V:600,cA=S.presentationTime-c;if(cA>J){cA=Math.min(cA,5e3);let CA="".concat(e.userId,"_").concat(e.streamType),vA=this._monitorFreezeData.get(CA,"render");vA?vA.duration+=cA:this._monitorFreezeData.set(CA,{userId:e.userId,type:e.streamType,duration:cA},"render");let $A=this._renderFreezeMap.get(CA);$A?($A.totalDuration+=cA,$A.count+=1):this._renderFreezeMap.set(CA,{userId:e.userId,type:e.streamType,totalDuration:cA,count:1})}}c=S.presentationTime,(b=o.element)==null||b.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()}},oiA=ac(Jl(),1),siA=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?Ai.addSuccessEvent({key:a.key}):Ai.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,f,S=arguments.length>6&&arguments[6]!==void 0?arguments[6]:.4,b=A+o/2,V=e+a/2,{min:J,offset:cA}=this.calculateBoundary(b,c,A,o),{min:CA,offset:vA}=this.calculateBoundary(V,d,e,a);return C=2*J+o,f=2*CA+a,C/f>this.originalAspect?(C=f*this.originalAspect,cA=b-C/2):(f=C/this.originalAspect,vA=V-f/2),o/c>S&&(cA=0,vA=0,C=c,f=d),cA=Math.max(0,Math.min(cA,c-C)),vA=Math.max(0,Math.min(vA,d-f)),{sx:cA,sy:vA,cropWidth:C,cropHeight:f,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=pi({},A),void(this.animationState.target=pi({},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(fS(A.sx-e.sx,2)+fS(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 f=this.calculateTargetPosition(o,a,c,d,A,e);this.processFacePositionCrop(f,A,e),c*d/f.cropWidth/f.cropHeight>C&&this.recoverOriginal(A,e)}movingPortrait(A,e,o,a,c,d){var C,f,S,b,V,J,cA,CA,vA,$A,he,Oe;let Se={sx:o+c/2+this.totalOffsetX,sy:a+d/2+this.totalOffsetY,cropWidth:A,cropHeight:e,scaleRatio:(f=(C=this.animationState.current)==null?void 0:C.scaleRatio)!=null?f:1,scaleOffsetX:(b=(S=this.animationState.current)==null?void 0:S.scaleOffsetX)!=null?b: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:($A=(vA=this.animationState.target)==null?void 0:vA.scaleOffsetX)!=null?$A:0,scaleOffsetY:(Oe=(he=this.animationState.target)==null?void 0:he.scaleOffsetY)!=null?Oe: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 oi({code:lt.VIDEO_MANAGER_ERROR,extraCode:6,message:"init vb node error ".concat(o.message||o)})),this.resolvePreditReady()})}init(A){return jA(this,null,function*(){var e,o,a;this.predictReady=new Promise(f=>{this.resolvePreditReady=f});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:f,y:S,width:b,height:V}=A.waterMark;this.wasm.setWaterMark(f,S,b,V)}if(A.beautyParams){let{beauty:f,brightness:S,ruddy:b}=A.beautyParams;this.wasm.setBeauty(f,S,b,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 f=this.context.createShader(d.FRAGMENT_SHADER,`#version 300 es +precision highp float; +uniform sampler2D u_texture; +uniform sampler2D mask; + +in vec2 v_texCoord; +out vec4 outColor; +void main() { + outColor = vec4(texture(u_texture, v_texCoord).rgb, texture(mask, v_texCoord).a); +}`),S=this.context.createShader(d.VERTEX_SHADER,`#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; +}`);this._prePrograme=this.context.createProgram(S,f),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:Dw()?(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 jA(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 siA(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(),VB(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(VB(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,f=this._mat4.create();this._mat4.fromTranslation(f,[A/d,1-(e+a)/C,0]),this._mat4.scale(f,f,[o/d,a/C,1]),c.uniformMatrix4fv(this._textureMatrixLocation,!1,f)}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()}},riA=class extends Yd{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; + uniform sampler2D vSampler; + varying highp vec2 textureCoord; + const mat4 YUV2RGB = mat4( + 1.1643828125, 0, 1.59602734375, -.87078515625, + 1.1643828125, -.39176171875, -.81296875, .52959375, + 1.1643828125, 2.017234375, 0, -1.081390625, + 0, 0, 0, 1); + void main() { + vec3 yuv; + yuv.r = texture2D(ySampler, textureCoord).r; + yuv.g = texture2D(uSampler, textureCoord).r; + yuv.b = texture2D(vSampler, textureCoord).r; + gl_FragColor = vec4(yuv,1) * YUV2RGB; + } + `,vertexShaderSource:` + attribute vec4 vertexPos; + attribute vec2 texturePos; + varying vec2 textureCoord; + 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)}},w5=(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")},aiA=0,giA=class{constructor(A){Y(this,"id",aiA++),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=oQ(),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=ga(e.availableState,zs.OFF),this.stopOB=oQ(),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),Qa(this.stateChangeOB,E4((a,c)=>(a!==c&&e.onDecodeDowngradeStateChanged({type:this.type,renderer:this.renderer,reason:this.failedReason,prevState:a,state:c}),c),"INITIALIZED"),oE(this.stopOB),Cl()),this.start()}start(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;this.waitFirstKeyFrame=!0,this.stateChangeOB.next("STARTING");let e=Qa(this.pipe(this.track),oE(this.stopOB),Dk());Qa(e,Cl(()=>{this.track.stat.framesDecoded++},o=>{if(this.track.log.error("".concat(this.id," play failed: ").concat(o," retryCount: ").concat(A)),Ai.addFailedEvent({key:w5(this.type,this.renderer),error:o}),A>4)this.failedReason=o,this.stateChangeOB.next("FAILED"),Ai.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")),Ai.addSuccessEvent({key:w5(this.type,this.renderer)}),Ai.addSuccessEvent({key:514704})})),Qa(e,Vw(1),Cl(()=>{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"&&!gM()&&(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:f}=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=f,this.startTime=Date.now(),this.startPerformanceTime=bo()}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(f," ").concat((a=A.getMetadata)==null?void 0:a.call(A).rtpTimestamp)),this.decodeFrameCount++,this.lastDecodeFrameTimestamp=f,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=>jA(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",f=>{this.decodedFrameCount++,C++,(C<=10||C%500==0)&&A.log.debug("frame ".concat(C," ").concat(this.decodedFrameCount,"/").concat(this.decodeFrameCount," decoded ").concat(f.timestamp)),Date.now()-this.lastDowngradeTime>5e3&&(this.type==="webCodecs"?this.checkDowngradeByFrameDiff():this.type==="wasm"&&this.checkDowngradeByTimestampDiff(f.timestamp)),e.next(f)}),o.on("error",f=>{A.log.error(f),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 NC({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create(),this.videoContext.on(NC.UNAVAILABLE,S=>{A.log.error(S),e.error(7)});let f=new riA(this.videoContext);o.on("videoCodecInfo",S=>f.resize(S.width,S.height)),o.on("videoFrame",S=>{({y:f.Y,u:f.U,v:f.V}=S),this.downgradeLevel===1?this.decodedFrameCount%2==0&&f.render(this.decodedFrameCount):f.render(this.decodedFrameCount)}),A.source=f,A.player.setCanvas(this.videoContext._canvas,2)}else if(c==="videoFrame"){A.player.setCanvas();let f=new MediaStreamTrackGenerator({kind:"video"}),S=f.writable.getWriter();A.setInputMediaStreamTrack(f),o.on("videoFrame",b=>S.write(b))}else{this.videoContext=new nQ({frameRate:15,logger:A.log,name:A.userId}),this.videoContext.create({alpha:!1});let f=this.videoContext.createVideoImageSource();o.on("videoFrame",b=>{try{f.image=b,f.update()}catch(V){delete this.goodType,A.log.error(V),e.error(11)}});let S=new Xq(this.videoContext,{name:"remotePlayer",logger:A.log});f.connect(S),A.source=f,A.player.setCanvas(this.videoContext._canvas,2)}this.decoder=o}catch(C){A.log.error(C),e.error(d==="webCodecs"?2:6)}})}},_5=Promise.resolve(),T5=class extends oiA.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",_5),Y(this,"_updateFlag",!1),this.log=QA.createLogger({parent:A?.getLogger(),id:"vm",userId:A?.userId,sdkAppId:A?.sdkAppId}),this.smallVideoContext=new nQ({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 VB(this._rotation)?{width:o,height:e}:{width:e,height:o}}get2dVideoContext(){return this._2dVideoContext?this._2dVideoContext.destroy():this._2dVideoContext=new nQ({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 NC({frameRate:15,logger:this.log,name:"m"});return this.initializeGlVideoContext(),this._glVideoContext}initializeGlVideoContext(){try{this._glVideoContext.create(Lx<=22),this._glVideoContext.on(NC.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=_r.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(),_r.clearTask(this._checkId)}get needAlpha(){return this._hasWaterMark||this._hasVirtualBg}get active(){return(Rp||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?Ai.addFailedEvent({key:e,error:A}):Ai.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 NC({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 keA(this.smallVideoContext,A,this.log),this.smallVideoContext.on(NC.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;Rp&&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),U.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 jA(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(Yd.RENDER,c=>{var d;(d=this.cameraTrack)==null||d.emit("render",c)})),Od===16?this.initialTrack instanceof CanvasCaptureMediaStreamTrack?(this.cameraNode&&(this.cameraNode instanceof Jw?(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 Jw?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 beA(this.videoContext,{name:"mainDestination",logger:this.log}),this.destination.on(Yd.RENDER,f=>{var S;(S=this.cameraTrack)==null||S.emit("render",f)}));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 niA(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 Ey(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 v4(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 vM)return this.log.info("change screen input",(e=A.mediaTrack)==null?void 0:e.label),this.setScreenTrack(A);if(A instanceof sQ)return this.log.info("change video input",(o=A.mediaTrack)==null?void 0:o.label),this.setCameraTrack(A);if(A instanceof bk){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 AK)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 vM?((e=this.screenNode)==null||e.close(),delete this.screenNode,delete this.screenTrack,this.update()):A instanceof sQ?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 bk?A.source&&A.source.context.destroy():A instanceof AK&&(delete this.mixTrack,this.update())}setMixTrack(A){this.mixTrack=A}setCameraTrack(A){return this.cameraTrack=A,this.update(!0)}setScreenTrack(A){return jA(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 jA(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 oi({code:lt.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:f,width:S,height:b,fillVideo:V}=c,J=V&&A||S,cA=V&&e||b,CA=V?0:C,vA=V?0:f;a.drawImage(d,CA,vA,J,cA)}),YS(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 jA(this,null,function*(){this._beautyParams=A,this.update()})}stopBeauty(){return jA(this,null,function*(){this._beautyParams=void 0,this.update()})}setWatermark(A){return jA(this,null,function*(){let e;try{e=yield YS(A?.imageElement||A.imageUrl)}catch{throw new oi({code:lt.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:f=2,fillVideo:S=!1}=A;this.watermarkImageList.some(b=>b.type===C)?(this.watermarkImageList=this.watermarkImageList.filter(b=>b.type!==C),this.pushWaterMarkImageList({x:o,y:a,width:c,height:d,image:e,zIndex:f,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:f,type:C,imageUrl:A.imageUrl,fillVideo:S}),yield this.freshWatermark()),this.log.info("set watermark",JSON.stringify(this.watermarkImageList,(b,V)=>b==="imageUrl"?void 0:V))})}deleteWatermark(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"watermark";return jA(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 jA(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 jA(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 YS(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 oi({code:lt.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 jA(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 giA(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}};di([zW(function(A){this.log.error("update failed",A)}),Hr(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 oi({code:lt.API_CALL_TIMEOUT,message:"update timeout"}))}),this._updateFlag=!1,yield this.updated)})})],T5.prototype,"update");var ciA=0,liA=class extends zs{constructor(A){super("room"),Y(this,"seq",++ciA),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,wr(A.autoReceiveAudio)&&(this.autoReceiveAudio=A.autoReceiveAudio),wr(A.autoReceiveVideo)&&(this.autoReceiveVideo=A.autoReceiveVideo),wr(A.enableAutoPlayDialog)&&(this.enableAutoPlayDialog=A.enableAutoPlayDialog),this._sdkType=A.sdkType,this.keyPointManager=new AiA({room:this,frameWorkType:A.frameWorkType,component:A.component,language:A.language}),this.callDurationCalculator=new eiA({room:this}),this.badCaseDetector=new iiA({room:this}),this.audioManager=new xeA(this),this.videoManager=new T5(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 jA(this,null,function*(){return this.publish(A)})}removeTrack(A){return jA(this,null,function*(){return this.unpublish(A)})}replaceTrack(A){return jA(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(eE(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?(sK([d,d]),DS("https://".concat(d))):(a&&DS(a),c&&sK(c))}U.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({sched_domain:Hp.main,sched_back_domain:Hp.backup,signal_domain:this.proxy_ws||this.proxy_wt||""}))}getRemoteAudioStats(){return jA(this,null,function*(){let A={};return this.remotePublishedUserMap.forEach(e=>{A[e.userId]=e.remoteAudioTrack.stat}),A})}getTransportStats(){return jA(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 jA(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 oi({code:lt.INVALID_OPERATION,message:Zo({key:So.CLIENT_DESTROYED,data:{funName:"join"}})})}destroy(){if(this.isJoined)throw this._log.warn(gc.INVALID_DESTROY),new oi({code:lt.INVALID_OPERATION,message:Zo({key:So.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,U.emit(nA.ROOM_DESTROY,{room:this})}schedule(A,e){return jA(this,null,function*(){var o,a,c,d;let C=bo();try{let{isCached:f,result:S,detailCost:b}=yield H4({userId:this.userId,sdkAppId:this.sdkAppId,roomId:this.useStringRoomId?A.strRoomId:A.roomId,useStringRoomId:this.useStringRoomId,version:kd,userSig:this.userSig,role:this.scene==="live"?A.role:void 0,frameWorkType:e,latencyLevel:A.latencyLevel});this._isUsingCachedSchedule=f,this._log.info("schedule cache:".concat(+f," ").concat(Fd(S,{keysToExclude:["username","credential"]}))),f&&U.once(nA.JOIN_RECEIVED_CMD_RES,()=>this.sendAbilityStatus({scheduleCache:1})),this.scheduleResult=pi(pi({},this.scheduleResult),S),bn((o=S.config)==null?void 0:o.retryCount)&&Y0(S.config.retryCount),Yn((a=S.config)==null?void 0:a.loggerDomain)&&DS(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,U.emit(nA.JOIN_SCHEDULE_SUCCESS,{room:this,schedule:this.scheduleResult,detailCost:b}),Ai.addSuccessEvent({key:521700,cost:bo()-C})}catch(f){throw Ai.addFailedEvent({key:521700,error:f}),f}})}sendAbilityStatus(A){}enableInsertableStreams(){return Promise.resolve()}switchRoom(A){return Promise.reject()}isSwitchRoomSupported(){return!1}prelink(A,e,o,a,c,d){return jA(this,null,function*(){return Promise.resolve()})}closePrelink(){return jA(this,null,function*(){return Promise.resolve()})}},IiA=ac(Jl()),N5=ac(VG());function G5(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:f}=d;return{id:C,params:f?[f]:[]}})})}return o}var uiA=(A,e,o)=>jA(null,null,function*(){var a;let c=Ic(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],f=c.media[1];C.ext&&(d.audio.extensions=C.ext.map(b=>({id:b.value,uri:b.uri}))),f.ext&&(d.video.extensions=f.ext.map(b=>({id:b.value,uri:b.uri})));for(let b of C.rtp){if(b.codec!=="opus")continue;let V=C.fmtp.find(cA=>cA.payload===b.payload);if(!V)continue;let J={codec:b.codec,fmtp:V.config,payload:V.payload,rate:b.rate,channels:b.encoding,rtcpfb:[],rtx:0};(a=C.rtcpFb)==null||a.forEach(cA=>{let{payload:CA,type:vA,subtype:$A}=cA;if(CA===J.payload){let he={id:vA,params:[]};$A&&he.params.push($A),J.rtcpfb.push(he)}}),d.audio.codecs.push(J);break}let S=["h264","vp8","h265"];return e&&S.shift(),d.video.codecs=[...G5(f)].filter(b=>S.includes(b.codec.toLocaleLowerCase())),d.video.decoders=(yield function(){return jA(this,null,function*(){let b=new RTCPeerConnection;b.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_RECVONLY});let V=yield b.createOffer();if(!V.sdp)return[];let J=G5(Ic(V.sdp).media[0]);return b.close(),J})}()).filter(b=>["h264","vp8","h265"].includes(b.codec.toLocaleLowerCase())),d}),b5=(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 f=new RegExp(d,"g");return o.replace(f,"".concat(c,"=").concat(a))}if(!o)return"".concat(c,"=").concat(a);let C=o.endsWith(";")?"":";";return"".concat(o).concat(C).concat(c,"=").concat(a)},EiA=A=>{let{serverAbility:e,clientAbility:o,offerSDP:a,enableCustomMessage:c,profileLevelIdConfig:d}=A,C=Ic(a),f={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:VA.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:VA.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}]};f.media.push(S);let b=[d?.big,d?.small,d?.aux];return[1,2,3].forEach((V,J)=>{f.media.push(k5({mid:V,serverAbility:e,clientAbility:o,parsedOffer:C,profileLevelId:b[J]}))}),c&&f.media.push(C.media.find(V=>V.mid==="dc")),Cy(f)},k5=A=>{let{mid:e,serverAbility:o,clientAbility:a,parsedOffer:c,isDownlink:d=!1,profileLevelId:C}=A,f={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:VA.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:VA.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(b=>{Zw(f,b)})}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 b=o.video.codecs[S]||a.video.codecs[0];Zw(f,b)}if(!d&&C){let S=f.fmtp,b=f.rtp.find(V=>{var J;return((J=V.codec)==null?void 0:J.toLowerCase())==="h264"});if(b){let V=S.find(J=>String(J.payload)===String(b.payload));V&&(V.config=b5(V.config,C))}}return f},Zw=(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}))},diA=(A,e,o)=>{let a=N5.default.parse(A);return a.media.forEach((c,d)=>{var C;if((c.type===VA.AUDIO||c.type===VA.VIDEO)&&(function(f){if(!f.rtcpFb)return;let S=[];f.rtcpFb.forEach((b,V)=>{var J;S.push(b),f.rtcpFb&&((J=f.rtcpFb[V+1])==null?void 0:J.payload)!==b.payload&&b.type!=="rrtr"&&S.push({payload:b.payload,type:"rrtr"})}),f.rtcpFb=S}(c),function(f){f.type===VA.VIDEO&&f.fmtp&&f.fmtp.forEach(S=>{S.config.includes("apt")||(S.config+=";sps-pps-idr-in-keyframe=1")})}(c),function(f){f.type===VA.AUDIO&&f.fmtp&&f.fmtp.forEach(S=>{S.config+=";sprop-stereo=1;stereo=1"})}(c),function(f){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"]);f.ext&&(f.ext=f.ext.filter(b=>!S.has(b.uri)))}(c),c.type===VA.VIDEO)){if(d<4)c.payloads="",c.fmtp=[],c.rtp=[],c.rtcpFb=[],e.video.codecs.forEach(f=>Zw(c,f));else if(o){c.payloads="",c.fmtp=[],c.rtp=[],c.rtcpFb=[];let f=o.video.decoders;(!f||f.length===0)&&(f=o.video.codecs),(!f||f.length===0)&&(f=e.video.decoders),f.forEach(S=>Zw(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")}),N5.default.write(a)};function RK(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 wK(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 L5(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=RK(a.fmtp);if(c&&wK(c)===o)return c}return""}var CiA=ac(Jl()),U5=class extends CiA.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"),!Ja&&tE&&U.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(){U.off("262",this.onVideoCodecChanged,this),this.room.off("heartbeat-report",this.onHeartbeatReport,this)}};Y(U5,"EVENT_BAD_HEALTH","bad_health");var hiA=U5,Xw=(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))(Xw||{}),BiA=1,hy=class extends IiA.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(BiA++),userId:this._room.userId,sdkAppId:this._room.sdkAppId}),this._room.enableCodecPipeline&&(Up?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=Ic(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&&!xe(a.ssrcs[0].id)){let C=Number(a.ssrcs[0].id),f=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=f;break;case 2:o.smallVideoSsrc=C,o.smallVideoRtxSsrc=f;break;case 3:o.auxVideoSsrc=C,o.auxVideoRtxSsrc=f}}}),o})(this._peerConnection.localDescription.sdp):{audioSsrc:0,audioRtxSsrc:0,bigVideoSsrc:0,bigVideoRtxSsrc:0,smallVideoSsrc:0,smallVideoRtxSsrc:0,auxVideoSsrc:0,auxVideoRtxSsrc:0}}onBadHealth(A){}initScriptTransformWorker(){Gw&&(this.scriptTransformWorker=t5({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 Mx(a)&&(o.encodedInsertableStreams=a),this._log.debug("getPeerConnectionConfig",JSON.stringify(o)),o}initialize(A){return jA(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(),Ai.addSuccessEvent({key:521711,cost:this.stat.iceEndTime-this.stat.iceStartTime})):a==="failed"&&Ai.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 piA(a.data);this.emit("data_channel_msg",{data:c})},this._datachannel.onerror=a=>{this._log.warn("datachannel error",a)}),this._peerConnection.addTransceiver(VA.AUDIO,{direction:VA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_SENDONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_SENDONLY}),o=yield this._peerConnection.createOffer(),this.clientAbility=yield uiA(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()))}),Ai.addSuccessEvent({key:521707}),this.clientAbility}catch(a){throw Ai.addFailedEvent({key:521707,error:a}),this._log.error("initialize failed ".concat(a,` +offer: `).concat(o?.sdp)),a}})}setIceServers(A){return jA(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 jA(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=bo(),C=this.getProfileLevelIdConfig(),f={type:"answer",sdp:EiA({serverAbility:A,clientAbility:this.clientAbility,offerSDP:this._peerConnection.localDescription.sdp,enableCustomMessage:this._enableDataChannel,profileLevelIdConfig:C})};this._serverAbility=A,yield this.setAnswer(f),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||Ai.addSuccessEvent({key:521703,cost:bo()-d})}catch(d){let C=d instanceof oi&&d.code===lt.API_CALL_ABORTED;throw C||this._log.error("connect failed: ".concat(d),A),this.reset(),!C&&!this.isReconnecting&&!this.isDestroyed&&(Ai.addFailedEvent({key:521703,error:d}),this.emitConnectionStateChangedEvent("DISCONNECTED"),this.startReconnection()),d}})}reconnect(){return jA(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(xk,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=pi({ability:e},A),a=yield this._signalChannel.sendWaitForResponse({command:OtA,responseCommand:cs.REBUILD_PEER_CONNECTION_RES,data:o,enableLog:!1});if(a.data.code!==0)throw new oi({code:a.data.code,message:a.data.message});yield this.connect(a.data.data.ability,!0),Ai.addSuccessEvent({key:521704}),this._log.warn("reconnect() success"),this.stopReconnection(),U.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=Bp(this.reconnectionCount);this._log.warn("reconnect() timeout, try again after ".concat(e/1e3,"s")),yield SC(e,o=>{this._reconnectionTimer=o}),this.clearReconnectionTimer(),yield this.reconnect()}else this._log.error("reconnect() failed ".concat(A?.code," ").concat(A)),Ai.addFailedEvent({key:521704,error:A}),this.reconnectionCount>=Tf()&&this._log.warn("SDK has tried reconnect for ".concat(Tf()," 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 jA(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(xk,this.reconnect,this),this.currentState==="RECONNECTING"&&this.emitConnectionStateChangedEvent("DISCONNECTED"))}checkPeerConnectionToReconnect(){var A;!this.isReconnecting&&((A=this._peerConnection)==null?void 0:A.connectionState)===Eo.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===Eo.CONNECTING&&(this.stat.peerConnectionStartTime===0&&(this.stat.peerConnectionStartTime=Date.now()),this.emitConnectionStateChangedEvent("CONNECTING")),(A.target.connectionState===Eo.FAILED||A.target.connectionState===Eo.CLOSED)&&(this.emitConnectionStateChangedEvent("DISCONNECTED"),this._room.forceRelay?this.switchRelay(!1):this.startReconnection()),(A.target.connectionState===Eo.CONNECTED||A.target.connectionState===Eo.COMPLETED)&&(this.stat.peerConnectionEndTime===0&&(this.stat.peerConnectionEndTime=Date.now()),U.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 Lh;let A=null;return _I()&&this._peerConnection.getSenders().length!==0?(A=this._peerConnection.getSenders()[0].transport,sy()&&this._peerConnection.getReceivers().length!==0&&A?A.state:Lh):Lh}emitConnectionStateChangedEvent(A){A!==this.currentState&&(this.currentState==="RECONNECTING"&&A==="CONNECTING"||(this.emit(Xw.CONNECTION_STATE_CHANGED,{prevState:this.currentState,state:A}),this.currentState=A))}logSelectedCandidate(){return jA(this,null,function*(){if(!this._peerConnection)return;let A=yield this._peerConnection.getStats();for(let[e,o]of A)if(lM(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&&Aw(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:f}=C;f===this._room&&(clearTimeout(d),c(),e(new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.CONNECTION_ABORTED,data:"leave room"})})))},c=()=>{U.off(nA.LEAVE_SUCCESS,a,this),this.off(Xw.CONNECTION_STATE_CHANGED,o,this)},d=setTimeout(()=>{c();let C=new oi({code:lt.API_CALL_TIMEOUT,message:"connection timeout"});this._room.firewallDetector.increaseTimeoutCount(),e(C)},tb);this.clearConnectTimeout=()=>{c(),clearTimeout(d),delete this.clearConnectTimeout},this.clearWaitForConnectedPromise=()=>{this._waitForPCConnectedPromise=null,e(new oi({code:lt.API_CALL_TIMEOUT,message:"connection timeout"}))},U.on(nA.LEAVE_SUCCESS,a,this),this.on(Xw.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 jA(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=Ic(this._peerConnection.remoteDescription.sdp));let d,C,f,S=this._parsedAnswer.media.filter(J=>{var cA;return(cA=J.ssrcs)==null?void 0:cA.find(CA=>{var vA;return(vA=CA.value)==null?void 0:vA.includes(a)})});if(S.length===3)d=S[0],C=S[1],f=S[2];else{let J,cA=this._peerConnection.getTransceivers().slice(4);if(c?.length===3&&c.every(vA=>{var $A;return(($A=cA.find(he=>Number(he.mid)===vA))==null?void 0:$A.direction)==="inactive"})?(J=c,this._log.info("reusing previous mids for ".concat(o,": ").concat(J.join(","))),cA.forEach(vA=>{J.includes(Number(vA.mid))&&(vA.direction=VA.TRANSCEIVER_DIRECTION_RECVONLY)})):J=cA.filter(vA=>vA.direction==="inactive").slice(0,3).map(vA=>(vA.direction=VA.TRANSCEIVER_DIRECTION_RECVONLY,Number(vA.mid))),J.length===3)d=this._parsedAnswer.media.find(vA=>Number(vA.mid)===Number(J[0])),C=this._parsedAnswer.media.find(vA=>Number(vA.mid)===Number(J[1])),f=this._parsedAnswer.media.find(vA=>Number(vA.mid)===Number(J[2]));else if(J.length===0){this._peerConnection.addTransceiver(VA.AUDIO,{direction:VA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_RECVONLY}),this._peerConnection.addTransceiver(VA.VIDEO,{direction:VA.TRANSCEIVER_DIRECTION_RECVONLY}),d=JSON.parse(JSON.stringify(this._parsedAnswer.media[0]));let vA=k5({mid:1,serverAbility:this._serverAbility,clientAbility:this.clientAbility,parsedOffer:Ic(this._peerConnection.localDescription.sdp),isDownlink:!0});C=JSON.parse(JSON.stringify(vA)),f=JSON.parse(JSON.stringify(vA)),d.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(d),C.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(C),f.mid=this._parsedAnswer.media.length,this._parsedAnswer.media.push(f)}}d.direction=VA.TRANSCEIVER_DIRECTION_SENDONLY;let b="".concat(a,"-").concat(e.audio);d.ssrcs=[{id:e.audio,attribute:"cname",value:"".concat(b)},{id:e.audio,attribute:"msid",value:"".concat(b,"-").concat(VA.MAIN," ").concat(b,"-audio")}],C.direction=VA.TRANSCEIVER_DIRECTION_SENDONLY,C.ssrcs=[{id:e.video,attribute:"cname",value:"".concat(b)},{id:e.video,attribute:"msid",value:"".concat(b,"-").concat(VA.MAIN," ").concat(b,"-bigvideo")},{id:e.videoRtx,attribute:"cname",value:"".concat(b)},{id:e.videoRtx,attribute:"msid",value:"".concat(b,"-").concat(VA.MAIN," ").concat(b,"-bigvideo")}],C.ssrcGroups=[{semantics:"FID",ssrcs:"".concat(e.video," ").concat(e.videoRtx)}],f.direction=VA.TRANSCEIVER_DIRECTION_SENDONLY;let V="".concat(b,"-aux");f.ssrcs=[{id:e.auxiliary,attribute:"cname",value:V},{id:e.auxiliary,attribute:"msid",value:"".concat(V," ").concat(b,"-aux").concat(VA.VIDEO)},{id:e.auxiliaryRtx,attribute:"cname",value:"".concat(V," ").concat(b,"-aux").concat(VA.VIDEO)},{id:e.auxiliaryRtx,attribute:"msid",value:"".concat(V," ").concat(b,"-aux").concat(VA.VIDEO)}],f.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,f.mid]),this._downlinkMIDUserIDMap.set(d.mid,o),this._downlinkMIDUserIDMap.set(C.mid,o),this._downlinkMIDUserIDMap.set(f.mid,o)}removeDownlink(A){return jA(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=Ic(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 jA(this,null,function*(){if(!this._peerConnection)return;let{audio:e,bigVideo:o,smallVideo:a,auxVideo:c}=A;try{if(gk()){let d=this._peerConnection.getSenders().slice(0,4);for(let f=0;f5e3?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=Ic(this._peerConnection.localDescription.sdp);this._parsedAnswer||(this._parsedAnswer=Ic(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 f={type:"offer",sdp:Cy(d)};return this.updateSDP({localDescription:f})}setScaleResolutionDownBy(A,e,o){let a=A.getParameters();(!a.encodings||a.encodings.length===0)&&(a.encodings=[{}]);let c=a.encodings[0].scaleResolutionDownBy;if(xe(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(tE&&HE<83||Ag&&xb(wI,"12.1")||er&&Ew<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=Cy(this._parsedAnswer);return this._updateSDPPromise=new Promise((o,a)=>jA(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),` +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(f=>{let{mid:S,currentDirection:b,direction:V,stopped:J}=f;return{mid:S,currentDirection:b,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 jA(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 Ic(arguments.length>0&&arguments[0]!==void 0?arguments[0]:"").media.map(A=>A.direction)}setOffer(A){this._log.info("setting offer");let e=diA(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 jA(this,null,function*(){if(this._parsedAnswer||(this._parsedAnswer=Ic(this._peerConnection.remoteDescription.sdp)),!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let e=!1;this._parsedAnswer.media.forEach(o=>{var a;if(o.type===VA.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=[],Zw(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=mb(o?.big)?o.big:"":A===3?a=mb(o?.small)?o.small:"":A===7&&(a=mb(o?.aux)?o.aux:""),!a)return"";let c=L5(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=L5(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 jA(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=Ic(this._peerConnection.remoteDescription.sdp));let o=A==="main"?1:3,a=this._parsedAnswer.media[o];if(!a||a.type!==VA.VIDEO)return;let c=a.rtp||[],d=a.fmtp||[],C=c.find(cA=>{var CA;return((CA=cA.codec)==null?void 0:CA.toLowerCase())==="h264"});if(!C)return;let f=d.find(cA=>String(cA.payload)===String(C.payload));if(!f)return;let S=RK(f.config);if(!S)return;let b=wK(S)==="high";if(e&&b||!e&&!b)return;let V=this._serverAbility.video.codecs.map(cA=>RK(cA.fmtp)).filter(Boolean).find(cA=>{let CA=wK(cA);return e?CA==="high":CA!=="high"});if(!V)return;let J=f.config;f.config=b5(f.config,V),f.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 jA(this,null,function*(){if(!this._peerConnection||!this._parsedAnswer||!this._serverAbility)return;let o=!1,a=[];xe(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===VA.VIDEO){let C;A&&this.is42001fSupported?C=this.clientAbility.video.codecs.find(f=>f.fmtp.includes("42001f")):A||(C=this._serverAbility.video.codecs.find(f=>f.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=[],Zw(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=>fp(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:f}=((a=this._room.scheduleResult.config)==null?void 0:a.useTurnTcpInfo)||{};if(!(C&&f&&c&&d))return;let S=Math.floor(d/c),b=(this._isRelayTried||S>C)&&d>f;b?++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(b," 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 jA(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")),Ai.addSuccessEvent({key:a,cost:Date.now()-c})}catch(c){this._log.warn("switchRelay ".concat(o," failed"),c),Ai.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:SK,data:{videoDecCodec:"h264"},responseCommand:cs.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)})}};di([XW("reconnect")],hy.prototype,"startReconnection"),di([cy(A=>A.userId)],hy.prototype,"addDownlink"),di([cy(A=>A)],hy.prototype,"removeDownlink"),di([yk(!0)],hy.prototype,"updateSDP"),di([ly(521712,!1),Q2(10,0)],hy.prototype,"setOffer"),di([ly(521713,!1),Q2(10,0)],hy.prototype,"setAnswer"),di([Hr((A,e)=>function(){for(var o=arguments.length,a=new Array(o),c=0;cclearTimeout(d)),this._checkPendingPromiseSet.clear()),A.apply(this,a)})],hy.prototype,"close");var QiA=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}},piA=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,b)=>S+b.byteLength,0),C=new Uint8Array(d),f=0;c.forEach(S=>{C.set(new Uint8Array(S),f),f+=S.byteLength}),this.data=C.buffer}},F5=new Set;function Hh(){let A=Math.floor(4294967296*Math.random());return F5.has(A)?Hh():(F5.add(A),A)}var miA=ac(Jl()),O5=class extends miA.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&&(U.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 P5(A){let{when:e,onSkip:o}=A;return Hr((a,c)=>function(){for(var d=arguments.length,C=new Array(d),f=0;fpostMessage({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:f}=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(f))}}}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),!gM()||!d||!e||typeof Worker>"u")return void this._log.warn("black video detector not supported");let C=f=>{var S,b,V,J;let cA;if(o)cA=(b=(S=f.msg_up_stream_info)==null?void 0:S.msg_video_status)==null?void 0:b.filter(CA=>CA.uint32_video_stream_type===3)[0];else{let CA=(V=f.msg_down_stream_info)==null?void 0:V.filter(vA=>{var $A;return(($A=vA.msg_user_info)==null?void 0:$A.str_identifier)===c})[0];cA=(J=CA?.msg_video_status)==null?void 0:J.filter(vA=>vA.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",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)}},V2=class extends O5{constructor(A){super(Bo(pi({},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=_r.run("timeout",()=>this.checkPublishState(!0),{delay:1e4,count:1}));Ai.addCount({key:521e3}),a.forEach(c=>{this._log.warn("".concat(c," publish failed during call ").concat(Np()," ").concat(ZB())),Ai.addEnum({key:521719,value:x5[c]})}),_r.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&wS),bigVideo:!!(this.flag&vS),smallVideo:!!(this.flag&zG),auxVideo:!!(this.flag&RS)}}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 jA(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 jA(this,arguments,function(e){var o=this;let{localAudioTrack:a,localVideoTrack:c,isAuxiliary:d}=e;return function*(){var C,f,S,b,V,J,cA;if(!o.singlePC)return;if(o.installEvents(),o.installTrackMuteEvents(a,c),c&&(c.retryEncodeFailed=o.onVideoEncodeFailed.bind(o),Ag&&(zf(wI,"26.2",!0)||zf(jB,"26.2",!0)||qB&&zf(wI,"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 oi({code:lt.NOT_SUPPORTED_H264,message:Zo({key:So.NOT_SUPPORTED_H264ENCODE})});o.singlePC.isUsingH264&&!o.singlePC.isH264EncodeSupported&&o.singlePC.isVP8EncodeSupported&&(o._log.warn("h264 encoder not supported"),yield o.singlePC.switchVideoEncoder("vp8")),Ja&&eM()===115&&c.profile.width*c.profile.height<=230400&&(o._log.warn("fallback video to defaultBigVideoProfile: ".concat(JSON.stringify(MS))),c.setProfile(MS),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:Q5,responseCommand:cs.SPC_PUBLISH_RESULT,data:Bo(pi({},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)||((f=o.localAuxAudioTrack)==null?void 0:f.profile.bitrate),bigVideo:(S=o.localMainVideoTrack)==null?void 0:S.profile.bitrate,smallVideo:(V=(b=o.localMainVideoTrack)==null?void 0:b.small)==null?void 0:V.bitrate,auxVideo:(J=o.localAuxVideoTrack)==null?void 0:J.profile.bitrate}),o.sendMediaSettings();let vA=d?7:2;(o._room.preferHW||(cA=o._room.scheduleResult.config)!=null&&cA.preferHW)&&c&&c.profile.width*c.profile.height>=921600&&o.singlePC.useHWEncoder(!0,vA)}()})}publishByTransceiver(A){let{localAudioTrack:e,localVideoTrack:o,smallTrack:a,isAuxiliary:c}=A;if(!Pd())return;this._log.info("publish by transceiver");let d=o?.outMediaTrack,C=e?.outMediaTrack,f=this._peerConnection.getTransceivers(),S=[],b=[],V=(cA,CA,vA)=>{var $A;let he=f[CA].sender.replaceTrack(vA);b.push(CA),($A=this.singlePC)!=null&&$A.enableInsertableStreams&&he.then(()=>this.createEncodedStreams(f[CA].sender,cA)),this.initSenderTransform(f[CA].sender,cA),S.push(he)};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,b);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,f)=>{var S,b;let V=this.getTrackByMediaType(e);if(!V||!V.encodeFrame)return f.enqueue(C);V.isAudio?f.enqueue(V.enableEncodeFrame?V.encodeFrame(C):C):f.enqueue((S=this.singlePC)!=null&&S.isUsingH264||(b=this.singlePC)!=null&&b.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&&Gw))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 jA(this,null,function*(){A?yield this.publishSmall(this._room.videoManager.smallMode):yield this.unpublishSmall()})}publishSmall(A){return jA(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"&&!Nw())return void o._log.warn("canvas mode small stream is not supported");let d=o._peerConnection.getTransceivers(),{sender:C}=d[2],f=yield o.doPublishSmall(e,a),S=e==="canvas"?524700:524701;Ai.addSuccessEvent({key:S}),f?((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=bM.start({track:C.track,room:o._room,isUplink:!0,userId:o.userId,onBlack:()=>{o._log.warn("small video is black");let b=e==="canvas"?524700:524701;Ai.addFailedEvent({key:b,error:10002}),bM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0}}))):Ai.addFailedEvent({key:S,error:10001})}()})}doPublishSmall(A){return jA(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(),f=rw(a?.profile,a?.small);return o._log.info("small scaleResolutionDownBy",f),C.encodings[0].scaleResolutionDownBy=f,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 jA(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(),bM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0)})}checkHighProfile(A){return jA(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&&!Zf();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 jA(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,f=c?.outMediaTrack,S=o._peerConnection.getSenders(),b=[];a&&(C?o.localAuxAudioTrack=null:o.localMainAudioTrack=null,!o.localMainAudioTrack&&!o.localAuxAudioTrack&&(yield S[0].replaceTrack(null),b.push(0))),f&&(C?(yield S[3].replaceTrack(null),o.localAuxVideoTrack=null,o._mediaSettings=Bo(pi({},o._mediaSettings),{auxVideoBps:0,auxVideoFps:0,auxVideoWidth:0,auxVideoHeight:0}),b.push(3)):(yield S[1].replaceTrack(null),yield S[2].replaceTrack(null),o.localMainVideoTrack=null,o._mediaSettings=Bo(pi({},o._mediaSettings),{videoWidth:0,videoHeight:0,videoBps:0,videoFps:0,audioFs:0,audioChannel:0,audioBps:0,smallVideoWidth:0,smallVideoHeight:0,smallVideoFps:0,smallVideoBps:0}),b.push(1,2))),o.isMainStreamPublished||o.isAuxStreamPublished?(yield o.singlePC.setTransceiverDirection(zn.INACTIVE,b),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 jA(this,null,function*(){let e={state:this._room.publishState,constraintConfig:this._mediaSettings},o=yield this._signalChannel.sendWaitForResponseWithRetry({command:fK,data:e,responseCommand:cs.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:U2,commandDesc:"unpublish",responseCommand:cs.UNPUBLISH_RESULT,enableLog:A}).catch(e=>{if(e.getCode()===lt.API_CALL_TIMEOUT||e.getCode()===lt.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),ny){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:SK,data:this._mediaSettings,responseCommand:cs.UPDATE_CONSTRAINT_CONFIG_RES}).then(A=>{A.data.code!==0&&this._log.warn(A.data.message)}).catch(()=>{})}addTrack(A){return jA(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?VA.AUXILIARY:VA.MAIN," stream")),tQ()&&(yield this.addTrackByTransceiver(A,e))})}addTrackByTransceiver(A,e){return jA(this,null,function*(){var o;if(!A.mediaTrack)return;let a=this._peerConnection.getTransceivers();if(A.kind===VA.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 jA(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?VA.AUXILIARY:VA.MAIN," stream")),tQ()&&(yield this.removeTrackByTransceiver(A,e))})}removeTrackByTransceiver(A,e){return jA(this,null,function*(){if(!A.mediaTrack)return;let o=this._peerConnection.getTransceivers();if(A.kind===VA.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 jA(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?VA.AUXILIARY:VA.MAIN," stream")),a.kind===VA.AUDIO&&o[0]&&(yield o[0].replaceTrack(a)),a.kind===VA.VIDEO&&(!c&&o[1]&&(yield o[1].replaceTrack(a)),c&&o[3]&&(yield o[3].replaceTrack(a))),!0})}setBandwidth(A){return jA(this,arguments,function(e){var o=this;let{bandwidth:a,type:c,videoType:d}=e;return function*(){if(o.singlePC){let C={};c===VA.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:C5,responseCommand:cs.MUTE_RESULT,data:this._room.muteState,retries:3}).catch(()=>{}))}handleConnectionStateChange(A){A.state==="CONNECTED"&&(this.localMainVideoTrack||this._publishingLocalVideoTrack&&!this._isPublishingAux)&&U.emit(nA.SEND_FIRST_VIDEO_FRAME,{room:this._room})}getVideoTrackId(){let A=arguments.length>0&&arguments[0]!==void 0?arguments[0]:VA.VIDEO;if(this._peerConnection){let e=this._peerConnection.getSenders();if(A===VA.AUXILIARY&&e[3]&&e[3].track)return e[3].track.id;if(A===VA.VIDEO&&e[1]&&e[1].track)return e[1].track.id}if(this.localMainVideoTrack&&A===VA.VIDEO){let e=this.localMainVideoTrack.mediaTrack;if(e)return e.id}if(this.localAuxVideoTrack&&A===VA.AUXILIARY){let e=this.localAuxVideoTrack.mediaTrack;if(e)return e.id}return""}getSSRC(){return this.ssrc}checkPublishResultCode(A,e){if(A!==0)throw A===J0?(this._log.error(gc.NOT_SUPPORTED_H264ENCODE),new oi({code:lt.NOT_SUPPORTED_H264,message:Zo({key:So.NOT_SUPPORTED_H264ENCODE})})):new oi({code:lt.UNKNOWN,message:Zo({key:So.SIGNAL_RESPONSE_FAILED,data:{signalResponse:cs.PUBLISH_RESULT,code:A,message:e}})})}onSinglePCReconnected(){return jA(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}))})}};di([DM(A=>{let{localVideoTrack:e}=A;e==null||delete e.retryEncodeFailed})],V2.prototype,"unpublish"),di([P5({when(){return this.isDestroyed}})],V2.prototype,"doPublishChange"),di([P5({when(){return this.isDestroyed}})],V2.prototype,"doUnpublish");var x5=(A=>(A[A.audio=1]="audio",A[A.bigVideo=2]="bigVideo",A[A.smallVideo=3]="smallVideo",A[A.auxVideo=4]="auxVideo",A))(x5||{}),Y5=V2;function V5(A){return Object.keys(A).filter(e=>A[e])}var J2=class extends O5{constructor(A){super(Bo(pi({},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 p2(this._room,this),this.remoteVideoTrack=new bk(this._room,this),this.remoteAuxiliaryTrack=new w4(this._room,this),this.avPlayerStateSyncManager=new gK({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 Qp(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===VA.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 f=VA.AUDIO;c.kind===VA.VIDEO&&(f=C===VA.MAIN?VA.VIDEO:VA.AUXILIARY);let S=this.remoteAudioTrack;f===VA.VIDEO?S=this.remoteVideoTrack:f===VA.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===VA.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,f;let S=(d=this.singlePC)==null?void 0:d.receiverRemoteTrackMap.get(A);return S&&(S.kind!=="video"||(C=this.singlePC)!=null&&C.isUsingH264||(f=this.singlePC)!=null&&f.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 jA(this,null,function*(){var o,a;try{let c=!0;if(this._log.info("subscribe ".concat(e," ").concat(V5(A))),this.hasSSRC){let f="subscribe_change";Object.values(A).find(S=>S===!0)||(f="unsubscribe"),yield this.sendSubscription(f,A)}else{if(yield this._room.switchRoomSubedReq,(o=this.singlePC)!=null&&o.autoSubscribedUserMap.size){let f=this.singlePC.autoSubscribedUserMap.get(this.userId);if(f){this.singlePC.autoSubscribedUserMap.delete(this.userId);let S=(a=this.singlePC.autoSubscribedSsrcGroups.get(this._room.roomId))==null?void 0:a[f.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?(Ai.addSuccessEvent({key:524702}),this._blackSmallVideoDetectionId=bM.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),Ai.addFailedEvent({key:524702}),bM.stop(this._blackSmallVideoDetectionId),this._blackSmallVideoDetectionId=void 0}})):(bM.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 oi({code:lt.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"),tE&&HE<92)return;this.singlePC.startReconnection()}}unsubscribe(A){return jA(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=pi({},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 f="subscribe_change";Object.values(C).find(S=>S===!0)||(f="unsubscribe"),o._log.info("".concat(f==="unsubscribe"?f:"subscribe"," ").concat(c," [").concat(V5(C),"]")),f==="unsubscribe"&&((d=o.singlePC)==null||d.removeDownlinkQueue.add(o.tinyId)),yield o.sendSubscription(f,C),c==="main"&&(bM.stop(o._blackSmallVideoDetectionId),o._blackSmallVideoDetectionId=void 0),f==="unsubscribe"&&(yield o.removeDownlink())}()})}subscribeDataChannel(){return jA(this,null,function*(){if(!this.singlePC)return;yield this.singlePC.waitForPeerConnectionConnected();let A=Bo(pi({},this.subscribeState),{datachannel:!0});yield this.doSubscribe(A)})}unsubscribeDataChannel(){return jA(this,null,function*(){let A=Bo(pi({},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=yK,c=cs.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=DK,c=cs.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 f=new oi({code:C.code,message:Zo({key:So.ERROR_MESSAGE,data:{type:A,message:C.message}})});throw this._log.error(f),f}})}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 jA(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 jA(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:Hh(),bigVideoSsrc:Hh(),bigVideoRtxSsrc:Hh(),auxVideoSsrc:Hh(),auxVideoRtxSsrc:Hh()},{audioSsrc:C,bigVideoSsrc:f,bigVideoRtxSsrc:S,auxVideoSsrc:b,auxVideoRtxSsrc:V}=d;A.ssrc={audio:C,video:f,videoRtx:S,auxiliary:b,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:p5,responseCommand:cs.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 oi({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)&&iQ){let{main:d,aux:C}=A._room.jitterBufferDelay||{},{jitterDelay:f=d,jitterDelayAux:S=C}=A._room.scheduleResult.config||{};(bn(f)||bn(S))&&A.setJitterBufferDelay({mainDelay:f,auxDelay:S})}}}}()})}removeDownlink(){return jA(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(!iQ||!this.singlePC||!this._peerConnection||YE(e)&&YE(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,YE(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 f=d.track===this.remoteAuxiliaryTrack.outMediaTrack||YE(e)&&d.track===this.remoteAudioTrack.outMediaTrack;if(f&&YE(o)||!f&&YE(e))return;let S=f?o||0:e,b=(d.jitterBufferTarget||0)+100;b>S||(d.jitterBufferTarget=b,this._log.debug("set ".concat(f?"aux ":"").concat((C=d?.track)==null?void 0:C.kind," jitterBuffer delay ").concat(b," -> ").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()}};di([yk(),Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;a{let C=f=>{this.off("closed",C),d(new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.CONNECTION_ABORTED,data:f})}))};this.on("closed",C),A.apply(this,o).then(c,d).finally(()=>{this.off("closed",C)})})})],J2.prototype,"subscribe"),di([yk()],J2.prototype,"unsubscribe"),di([cy(()=>"jitter")],J2.prototype,"setJitterBufferDelay");var fiA=J2,yiA=ac(Jl()),J5=class _6 extends yiA.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(cs.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(VtA,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)>_6.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 f=setTimeout(()=>this.emitMessage(c,!0),5e3);C.cachedMessageMap.set(c.seq,{message:c,timeoutId:f})}}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),SC(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 f=[...c.cachedMessageMap.values()].sort((S,b)=>S.message.seq-b.message.seq);f[0]&&(d=f[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(J5,"SEQ_INTERVAL",300);var DiA=J5,{isString:H5,isUndefined:kM,getNetworkType:SiA,isEmpty:MiA}=bd,By=class extends liA{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",EM),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 KeA,this.firewallDetector.on("firewall-restriction",()=>{this._log.warn("firewall restriction"),this.emit("firewall-restriction")}),this._stats=new ztA(this,this._log),this.userManager=new HeA(this.userId,this._log),this._version=kd,this.sdpSemantics=V0,kM(A.sdpSemantics)?te.isUnifiedPlanDefault()&&(this.sdpSemantics=TS):this.sdpSemantics=A.sdpSemantics,this._log.info("sdpSemantics: ".concat(this.sdpSemantics,", netType: ").concat(SiA())),A.iceTransportPolicy&&(this._iceTransportPolicy=A.iceTransportPolicy),this._enableMultiAuxStream=!kM(A.enableMultiAuxStream)&&A.enableMultiAuxStream,this.enableSEI=A.enableSEI&&EM,!kM(A.enableSPC)&&EM&&(this.enableSPC=A.enableSPC),this.preferHW=!!A.preferHW,this.enableVolumeControlInIOS=A.enableVolumeControlInIOS,this._initBusinessInfo(A),this.healthDetector=new hiA(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 jA(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=FP(a,[]);U.emit(nA.REMOTE_PUBLISH_STATE_CHANGED,pi({room:this},c)),this.emit("remote-publish-state-changed",pi({},c))}),this.joinParams=A,wr(A.enableDataChannel)&&(this._enableDataChannel=A.enableDataChannel),new Promise((a,c)=>jA(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 oi&&S.code===lt.SPC_INITIALIZED_FAILED))return c(S);(d=this.signalChannel)==null||d.destroy(),yield this.initialize()}let f=bo();yield this.doJoin(A,(C=this.singlePC)==null?void 0:C.clientAbility),Ai.addSuccessEvent({key:521708,cost:bo()-f}),a(),this._firstPublishedList&&this.onPublishedUserList({data:{userList:this._firstPublishedList}})}catch(f){Ai.addFailedEvent({key:521708,error:f}),c(f)}this._joinReject=null}))})}initSinglePC(){return jA(this,null,function*(){if(this.enableSPC&&!this.singlePC){this.singlePC=new hy({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 oi({code:lt.SPC_INITIALIZED_FAILED,message:A?.message})}}})}doJoin(A,e){return new Promise((o,a)=>jA(this,null,function*(){var c,d,C,f,S,b,V,J;A.privateMapKey&&(this.privateMapKey=A.privateMapKey),A.latencyLevel&&(this.latencyLevel=A.latencyLevel),this.signalChannel.once(k2,vA=>{this.clearJoinTimeout(),U.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this,error:vA}),a(vA)}),wr((d=(c=this.scheduleResult)==null?void 0:c.config)==null?void 0:d.singlePC)&&EM&&(this.enableSPC=this.scheduleResult.config.singlePC),this.keyPointManager.setConnectionType(this.singlePC?1:2),(!((f=(C=this.scheduleResult)==null?void 0:C.config)!=null&&f.jitterDelay)&&!((b=(S=this.scheduleResult)==null?void 0:S.config)!=null&&b.jitterDelayAux)||!iQ)&&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:Lf(),bussinessInfo:this._businessInfo,ability:e,sdkType:this._sdkType,userSig:this.userSig,receiveMix:!0,isChorus:!!this.enableChorus,enableNtpAudioFrame:!!this.enableChorus&&Tw(),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 oi({code:lt.JOIN_ROOM_FAILED,message:Zo({key:So.JOIN_ROOM_TIMEOUT})}))},CA),U.emit(nA.JOIN_SEND_CMD,{room:this}),this.signalChannel.send(this.singlePC?PtA:StA,cA),this.signalChannel.once(cs.JOIN_ROOM_RESULT,vA=>jA(this,null,function*(){this.clearJoinTimeout();let{code:$A,message:he,data:Oe,tinyId:Se}=vA.data;U.emit(nA.JOIN_RECEIVED_CMD_RES,{room:this,code:$A}),$A===0?(this._log.info("Join room success, start heartbeat"),Se&&(this.tinyId=Se),this.startHeartbeat(),this.syncUserList(),this.startSyncUserListInterval(),this._firstPublishedList=Oe.publishers,this._iceServersFromJoin=Oe.iceServer?[Oe.iceServer]:[],this.singlePC&&this.singlePC.setIceServers(this.getIceServers()).then(()=>{var fi;(fi=this.singlePC)==null||fi.connect(Bo(pi({},Oe.ability),{useVp8:Oe.ability.useVp8||!!A.useVp8,useH265:Oe.ability.useH265&&!!A.useH265})).catch(()=>{})}),o()):(this._log.error("Join room failed result: ".concat($A," error: ").concat(he)),a(new oi({code:lt.JOIN_ROOM_FAILED,extraCode:$A,message:Zo({key:So.JOIN_ROOM_FAILED,data:{error:he,code:$A}})})))}))}))}reJoin(){return jA(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(Bo(pi({},this.joinParams),{role:this.role==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel}),A),this._log.warn("reJoin success"),on.logSuccessEvent({userId:this.userId,eventType:Va.REJOIN}),this.singlePC){let o=a=>{var c;a.state==="CONNECTED"&&((c=this.singlePC)==null||c.off(Xw.CONNECTION_STATE_CHANGED,o),this.uplinkConnection instanceof Y5&&(this.uplinkConnection.installEvents(),this.uplinkConnection.onSinglePCReconnected()),this.remotePublishedUserMap.forEach(d=>{d.installEvents(),d.onSinglePCReconnected()}))};this.singlePC.on(Xw.CONNECTION_STATE_CHANGED,o),this.checkConnectionsToReconnect(),this.uplinkConnection instanceof x2&&!this.uplinkConnection.getIsReconnecting()&&this.uplinkConnection.startReconnection()}}catch(A){this._log.warn("reJoin fail ".concat(A)),this.reset(),on.logFailedEvent({userId:this.userId,eventType:Va.REJOIN,error:A}),this.emit("error",new oi({code:lt.JOIN_ROOM_FAILED,message:Zo({key:So.REJOIN_ROOM_FAILED,data:{roomId:this.joinParams.roomId}})}))}else this._log.warn("reJoin abort")})}initialize(A){return jA(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[...F2.values()].find(V=>V.room.userId===S&&!V.room.isJoined)||null}(this.userId),f=!!(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(f?"reuse":"setup"," signal channel")),f?(C.url=c,C.backupUrl=d,C.room.setSignalChannel(null),C.room=this,this.signalChannel=C):(C&&C.close(),this.signalChannel=new m5({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 DiA(this,this.signalChannel),this._customMessageManager.on("message",S=>{this.emit("custom-message",S)})),this.networkQuality||(this.networkQuality=new M5({signalChannel:this.signalChannel,room:this}),this.networkQuality.on(M5.EVENT_NETWORK_QUALITY,S=>{var b;this.emit("network-quality",S),(b=this.singlePC)==null||b.detectTCPAndUDP(S)})),WE(this,this.signalChannel).add(mK,S=>{U.emit(nA.SIGNAL_CONNECTION_STATE_CHANGED,pi({room:this},S)),this.emit("signal-connection-state-changed",S)}).add(ftA,S=>{this.reset(),this.emit("error",S)}).add(cs.PEER_JOIN,S=>{let{srcTinyId:b,userId:V,role:J,fromType:cA}=S.data.data;this.userManager.addUser({userId:V,tinyId:b,role:J,fromType:cA})}).add(cs.PEER_LEAVE,S=>{let{userId:b,reason:V=0}=S.data.data;this.userManager.deleteUser(b,V)}).add(cs.UPDATE_REMOTE_MUTE_STAT,S=>{this._lastHeartBeatTime>0&&Date.now()-this._lastHeartBeatTime>=1e4&&this.doHeartbeat(),this.onPublishedUserList(S.data)}).add(cs.CLIENT_BANNED,S=>{let b=S.data.data,{reason:V}=b;if(on.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(cs.SEND_SWITCH_ROOM_SUBED_REQ,S=>{if(!this.singlePC)return;let{subList:b}=S.data.data;this._log.info("auto subscribe ".concat(Fd(b,{keysToInclude:["userId"]}))),b.forEach(V=>{this.singlePC.autoSubscribedUserMap.set(V.userId,V)}),this.resolveSwitchRoomSubedReq()}).add(cs.FALLBACK_CODEC,S=>jA(this,null,function*(){var b,V,J,cA,CA;let vA=S.data.data;((b=vA.videoControlInfo)==null?void 0:b.enableH265Enc)===0&&((V=this.singlePC)==null?void 0:V.videoCodec)==="h265"&&(this._log.warn("fallback codec enableH265Enc: ".concat((J=vA.videoControlInfo)==null?void 0:J.enableH265Enc)),Ai.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(u5,S=>{this.tinyId=S.signalInfo.tinyId,U.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this})}),U.emit(nA.JOIN_SIGNAL_CONNECTION_START,{room:this}),yield this.signalChannel.connect(),f&&U.emit(nA.JOIN_SIGNAL_CONNECTION_END,{room:this}),f})}setSignalChannel(A){this.signalChannel=A,A||kn(this)}leave(){return jA(this,null,function*(){var A;try{yield this.doHeartbeat()}catch{}this._log.info("leave() => leaving room"),U.emit(nA.LEAVE_SEND_CMD,{room:this}),(A=this.signalChannel)==null||A.send(MtA),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=_r.run("ric",this.doHeartbeat.bind(this),{delay:2e3}),this.enableChorus&&this.startUpdateNTPTime())}stopHeartbeat(){this._heartbeat!==-1&&(this._log.info("stopHeartbeat"),_r.clearTask(this._heartbeat),this._heartbeat=-1,this._lastHeartBeatTime=-1)}doHeartbeat(){return jA(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(Hw.has(d)){let C=Hw.get(d).map(f=>({uint32_event_id:f.eventId,uint64_date:f.timestamp,str_userid:f.remoteUserId,uint32_param1:f.param1,uint32_param2:f.param2,uint32_video_stream_type:f.streamType}));return Hw.delete(d),C}return[]}(this.userId):[],c=Bo(pi({str_sdk_version:b0,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:pi({uint32_terminal_type:15,str_device_name:ZB(),str_os_version:"",uint32_net_type:Lf()},o.msg_device_info)});if(this.heartbeatReport=c,this.heartbeatCount++,U.emit(nA.HEARTBEAT_REPORT,{room:this,report:c}),this.signalChannel){if(this.signalChannel.isConnected){this.signalChannel.send(vtA,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",Bo(pi({},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===ZG)continue;let{userId:f,srcTinyId:S,flag:b,fromType:V}=C;f===this.userId&&(e=!0,this.uplinkConnection&&(this.uplinkConnection.flag=b),this.localPublishFlag!==b&&(this.localPublishFlag=b,this.emit("local-publish-flag-changed",b))),c.push({userId:f,tinyId:S,flag:b,fromType:V})}let d=[...a.map(C=>{let{userId:f,srcTinyId:S,flag:b,mixUserList:V,fromType:J}=C;return{userId:f,tinyId:S,flag:b,isRobot:!0,mixUserList:V,fromType:J}}),...c];d.forEach(C=>{let{userId:f}=C,S=this.remotePublishedUserMap.get(f);S&&this.checkSubscribeBigSmallVideo(S)}),A.data.fakeMixUser&&(A.data.fakeMixUser.tinyId=A.data.fakeMixUser.srcTinyId,d.push(A.data.fakeMixUser)),U.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 x2&&(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?fiA:D5)({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!==lt.ICE_TRANSPORT_ERROR&&(a===lt.DOWNLINK_RECONNECTION_FAILED&&this.closeDownLinkConnection(e),this.emit("error",o))}),A.on("connection-state-changed",o=>{this.emit("media-connection-state-changed",Bo(pi({},o),{userId:A.userId}))})}startSyncUserListInterval(){this._syncUserListInterval===-1&&(this._syncUserListInterval=_r.run("ric",this.syncUserList.bind(this)))}stopSyncUserListInterval(){_r.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:UtA,responseCommand:cs.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:f,role:S,fromType:b}=d;return{userId:C,tinyId:f,role:S,fromType:b}});throw Zo({key:So.SIGNAL_RESPONSE_FAILED,data:{signalResponse:cs.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||!f5)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 qp&&!e.getIsReconnecting()){let o=e.getPeerConnection();o&&o.connectionState===Eo.CLOSED&&(this._log.warn("[".concat(e.getUserId(),"] pc is closed but not reconnect")),e.startReconnection())}})}fallbackToMPC(){return jA(this,null,function*(){var A;if(this._log.warn("fallback to multi pc"),on.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 x2({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 D5({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 oi({code:lt.INVALID_OPERATION,message:Zo({key:So.CLIENT_DESTROYED,data:{funName:"join"}})})),this.clearJoinTimeout(),this.reset()),this.firewallDetector.destroy(),this.removeAllListeners(),this.healthDetector.destroy(),_r.clearTask(this._audioVolumeIntervalId))}switchRole(A){return jA(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:FtA,data:{role:A==="anchor"?20:21,privateMapKey:this.privateMapKey,latencyLevel:this.latencyLevel},responseCommand:cs.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 oi({code:lt.SWITCH_ROLE_FAILED,message:Zo({key:So.SWITCH_ROLE_FAILED,data:{message:c,code:a}})});this.role=A}).catch(o=>{throw o instanceof oi&&o.getCode()===lt.API_CALL_TIMEOUT&&(o=new oi({code:lt.SWITCH_ROLE_FAILED,message:Zo({key:So.SWITCH_ROLE_TIMEOUT})})),this._log.error(o),o})}subscribeDataChannel(){return jA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===K0);this._log.info("subscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>jA(this,null,function*(){try{yield e.subscribe(Bo(pi({},e.subscribeState),{datachannel:!0}),"main")}catch(o){this._log.error("subscribeDataChannel failed:",e.userId,o)}})))})}unsubscribeDataChannel(){return jA(this,null,function*(){if(this.remotePublishedUserMap.size===0)return;let A=[...this.remotePublishedUserMap.values()].filter(e=>e.fromType===K0);this._log.info("unsubscribeDataChannel",A.map(e=>e.userId)),yield Promise.all(A.map(e=>e.unsubscribeDataChannel()))})}_initUplinkConnection(){this.uplinkConnection=this.singlePC?new Y5({userId:this.userId,tinyId:this.tinyId,room:this}):new x2({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",Bo(pi({},A),{userId:this.userId}))}),this.uplinkConnection.on("error",A=>{let e=A.getCode();e!==lt.ICE_TRANSPORT_ERROR&&(e===lt.UPLINK_RECONNECTION_FAILED&&this.closeUplink(),this.emit("error",A))})}publish(A){return jA(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 MM?A:null,localVideoTrack:A instanceof sQ?A:null,isAuxiliary:A.streamType==="auxiliary"})})}unpublish(A){return jA(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 MM?A:null,localVideoTrack:A instanceof sQ?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&&Wx()?this.uplinkConnection.replaceTrack(A).then(e=>{e&&U.emit(nA.LOCAL_TRACK_REPLACED,{track:A})}):Promise.resolve()}setBandWidth(A){return jA(this,null,function*(){this.uplinkConnection&&(yield this.uplinkConnection.setBandwidth(A),yield this.uplinkConnection.sendMediaSettings())})}enableSmall(A){return jA(this,null,function*(){if(!this.uplinkConnection||!this.uplinkConnection.localMainVideoTrack)return Promise.resolve();A&&this.uplinkConnection.localMainVideoTrack.small&&(yield this.setBandWidth({type:VA.VIDEO,videoType:VA.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=pi({},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 f=this._changeBigSmallRecords.get(a);f&&f.options.smallVideo&&c.muteState.hasSmall&&C.video&&(C.video=!1,C.smallVideo=!0),U.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(MK(C),"] prev: [").concat(MK(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());U.emit(nA.SUBSCRIBE_SUCCESS,{room:this,streamType:d,remotePublishedUser:c})}catch(C){let f=C instanceof oi?C.getCode():lt.UNKNOWN,S=C;throw C instanceof oi?f===lt.REMOTE_STREAM_NOT_EXIST&&(S=new oi({code:lt.API_CALL_ABORTED,message:Zo({key:So.API_CALL_ABORTED,data:{message:C.message,userId:a,streamType:d}})}),this._log.warn(S)):(S=new oi({code:f,message:Zo({key:So.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)}),U.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 _r.clearTask(this._audioVolumeIntervalId);A=Math.floor(Math.max(A,100)),U.emit(nA.AUDIO_LEVEL_INTERVAL,{interval:A}),this._audioVolumeIntervalId&&_r.clearTask(this._audioVolumeIntervalId),this._enableAudioVolumeEvaluation=!0,this._audioVolumeIntervalId=_r.run("intervalInWorker",()=>{var o;n2.isRunning?this.stopUpdateAudioLevelFromSenderStat():this.updateAudioLevelFromSenderStat(A,e);let a=[];(o=this.remotePublishedUserMap)==null||o.forEach(c=>{if(c.muteState.hasAudio){!n2.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 jA(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=_r.run("intervalInWorker",()=>jA(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(f=>{f.type==="media-source"&&f.audioLevel&&(C.volume=f.audioLevel)})}),{delay:c,backgroundTask:e})})}stopUpdateAudioLevelFromSenderStat(){var A;this._updateAudioLevelTaskId!==-1&&(this._log.warn("stopUpdateAudioLevelFromSenderStat"),_r.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(!ck||!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 jA(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 jA(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 jA(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 jA(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 jA(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(bd.getTurnServer(a))):bd.isPlainObject(A)&&o.push(bd.getTurnServer(A)),this._turnServers=o,e&&(this._iceTransportPolicy=e)}sendStartMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:NtA,data:A,timeout:5e3,responseCommand:cs.START_MIX_TRANSCODE_RES,commandDesc:"startMixTranscode"}).catch(e=>{if(e.code!==lt.API_CALL_ABORTED)throw e})}sendStopMixTranscode(A){return this.signalChannel.sendWaitForResponse({command:GtA,data:A,timeout:5e3,responseCommand:cs.STOP_MIX_TRANSCODE_RES,commandDesc:"stopMixTranscode"}).catch(e=>{if(e.code!==lt.API_CALL_ABORTED)throw e})}sendStartPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?RtA:_tA,data:A,timeout:5e3,responseCommand:e?cs.START_PUBLISH_TENCENT_CDN_RES:cs.START_PUBLISH_GIVEN_CDN_RES,commandDesc:"startPublishCDN"}).catch(o=>{if(o.code!==lt.API_CALL_ABORTED)throw o})}sendStopPublishCDN(A){let e=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return this.signalChannel.sendWaitForResponse({command:e?wtA:TtA,data:A,timeout:5e3,responseCommand:e?cs.STOP_PUBLISH_TENCENT_CDN_RES:cs.STOP_PUBLISH_GIVEN_CDN_RES,commandDesc:"stopPublishCDN"}).catch(o=>{if(o.code!==lt.API_CALL_ABORTED)throw o})}sendStartPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:btA,data:A,timeout:5e3,responseCommand:cs.START_PUBLISH_CDN_STREAM_RES,commandDesc:"startPublishCDNStream"}).catch(e=>{if(e.code!==lt.API_CALL_ABORTED)throw e})}sendUpdatePushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:ktA,data:A,timeout:5e3,responseCommand:cs.UPDATE_PUBLISH_CDN_STREAM_RES,commandDesc:"updatePublishCDNStream"}).catch(e=>{if(e.code!==lt.API_CALL_ABORTED)throw e})}sendStopPushStreamToRoom(A){return this.signalChannel.sendWaitForResponse({command:LtA,data:A,timeout:5e3,responseCommand:cs.STOP_PUBLISH_CDN_STREAM_RES,commandDesc:"stopPublishCDNStream"}).catch(e=>{if(e.code!==lt.API_CALL_ABORTED)throw e})}sendAbilityStatus(A){var e;(e=this.signalChannel)==null||e.sendWaitForResponse({command:xtA,data:A,timeout:5e3,responseCommand:cs.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=bd.getEnv();return e?(A.mainUrl="wss://".concat(bd.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 jA(this,null,function*(){var C;if(this.isJoined)throw new oi({code:lt.INVALID_OPERATION,message:"already joined room"});if(!c&&!d)throw new oi({code:lt.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((f,S)=>{this.prelinkTimeoutId=setTimeout(()=>{S(new oi({code:lt.INVALID_OPERATION,message:"prelink timeout after ".concat(this.PRELINK_TIMEOUT,"ms")}))},this.PRELINK_TIMEOUT)})]).then(()=>{this.clearPrelinkTimeout()}).catch(f=>{throw this.clearPrelinkTimeout(),this.closePrelink().catch(()=>{}),f}),this.prelinkPromise})}doPrelink(A,e,o,a,c,d){return jA(this,null,function*(){var C,f,S;try{if(!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!bd.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 oi({code:lt.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}),(f=this.signalChannel)==null||f.markPrelinkConnected({sdkAppId:A,userId:e,userSig:o}),(S=this.signalChannel)==null||S.stopPrelinkIn(this.PRELINK_EXPIRED_TIME/1e3),this._log.info("prelink success")}catch(b){throw this._log.error("prelink failed",b),b}})}clearPrelinkTimeout(){this.prelinkTimeoutId&&(clearTimeout(this.prelinkTimeoutId),this.prelinkTimeoutId=null)}closePrelink(){return jA(this,null,function*(){var A;if(this.isJoined)throw new oi({code:lt.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 jA(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:f}=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=f-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(GS-d.reSubscribeCount,".")),d.isSubscribing=!1,d.reSubscribeCount=GS}catch(b){this._log.info("change [".concat(o,"] to ").concat(S.smallVideo?"small":"big"," video failed. count ").concat(GS-d.reSubscribeCount,". reason: ").concat(b)),d.isSubscribing=!1,d.reSubscribeCount===0&&this._changeBigSmallRecords.delete(o)}})}changeType(A,e){let o={options:{video:!A,smallVideo:A},isSubscribing:!1,reSubscribeCount:GS};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(H5(A.businessInfo)&&(e=JSON.parse(A.businessInfo)),!kM(A.pureAudioPushMode)){if(!Number.isInteger(Number(A.pureAudioPushMode)))throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.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(!kM(A.userDefineRecordId)){let o=/^[A-Za-z0-9_-]{1,64}$/gi;if(A.userDefineRecordId.match(o)===null)throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.INVALID_USER_DEFINE_RECORDID})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_record_id=A.userDefineRecordId}if(!kM(A.userDefinePushArgs)){if(!(H5(A.userDefinePushArgs)&&String(A.userDefinePushArgs)&&String(A.userDefinePushArgs).length<=256))throw new oi({code:lt.INVALID_PARAMETER,message:Zo({key:So.INVALID_USER_DEFINE_PUSH_ARGS})});e.Str_uc_params||(e.Str_uc_params={}),e.Str_uc_params.userdefine_push_args=A.userDefinePushArgs}MiA(e)||(this._businessInfo=JSON.stringify(e))}sendCustomMessage(A){var e;(e=this._customMessageManager)==null||e.send(A)}enableInsertableStreams(){return jA(this,null,function*(){if(this.singlePC&&!this.singlePC.enableInsertableStreams&&Up)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 oi({code:lt.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 jA(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,f=String(this.useStringRoomId?a:o),S=[];for(let cA=0;cA{this.resolveSwitchRoomSubedReq=cA,SC(5e3).then(cA)}),U.emit(nA.SWITCH_ROOM_START,{room:this}),yield this.singlePC.waitForPeerConnectionConnected();try{this.userManager.clear(),V=yield this.signalChannel.sendWaitForResponse({command:JtA,responseCommand:cs.SEND_SWITCH_ROOM_RES,data:b});let{code:cA,message:CA}=V.data;if(cA!==0){this._log.error("switch room failed. result: ".concat(cA," error: ").concat(CA));let vA=new oi({code:lt.SWITCH_ROOM_FAILED,extraCode:cA,message:CA});throw U.emit(nA.SWITCH_ROOM_FAILED,{room:this,error:vA}),vA}this.userSig=c,kM(d)||(this.privateMapKey=d),U.emit(nA.SWITCH_ROOM_SUCCESS,{room:this,currentRoomId:J,targetRoomId:f})}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,c=e[0].offset;e.forEach(f=>{a=Math.min(f.offset,a),c=Math.max(f.offset,c)});let d=Math.floor(e.reduce((f,S)=>f+S.rtt,0)/e.length),C=Math.floor(e.reduce((f,S)=>f+S.offset,0)/e.length);(c-a>30||d>50)&&setTimeout(()=>this.startUpdateNTPTime(),5e3),UB(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:HtA,responseCommand:cs.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 di([cc(["left",zs.INIT],"joined"),Yh({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"),rQ(!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())}}),Hr(A=>{let e=new QtA;return function(o,a,c){return jA(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 oi({code:lt.INVALID_OPERATION,message:Zo({key:So.INVALID_JOIN})});if(this.checkDestroy(),e.isJoined({userId:this.userId,roomId:d,sdkAppId:this.sdkAppId,room:this}))throw new oi({code:lt.INVALID_OPERATION,message:Zo({key:So.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)),U.emit(nA.JOIN_START,{room:this,roomId:d,params:o});let C=bd.getEnv();C||(C=FB.QCLOUD,this.proxy_ws&&(this.proxy_ws.startsWith(vf.OLD_CLOUD_LADDER)?C=FB.OLD_CLOUD_LADDER:this.proxy_ws.startsWith(vf.WEBRTC)&&(C=FB.WEBRTC))),on.setConfig({env:C,sdkAppId:String(this.sdkAppId),userId:this.userId,roomId:d}),te.checkSystemRequirementsInternal(c).then(f=>{this.checkSystemResult=f,ptA.call(this)});try{!this.prelinkPromise&&!this.proxy_ws&&!this.proxy_wt&&!this.scheduleResult.domains&&!bd.getEnv()&&(yield this.schedule(o,c));let f=yield A.call(this,o,a,c);return this.roomId=d,this._joinedTimestamp=bd.performanceNow(),U.emit(nA.JOIN_SUCCESS,{room:this}),c===30&&!o.component&&on.uploadEvent({log:"stat-conv-".concat(Number(wp),"-").concat(location.hostname),userId:this.userId}),f}catch(f){throw e.delete({room:this,roomId:d}),U.emit(nA.JOIN_FAILED,{room:this,error:f}),f}})}})],By.prototype,"join"),di([cc("joined","left",{ignoreError:!0,success(){this.reset(!0)}}),Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;aA.mediaType),Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.outMediaTrack&&d.state==="ready"),!o.length))return;U.emit("61",{room:this});let c=A.apply(this,o);return Promise.all(o.map(d=>d.publish(this,c)))})}),Yh({settings:{retries:Tf,timeout:A=>Bp(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),U.emit(nA.PUBLISH_FAILED,{room:this}))}})],By.prototype,"publish"),di([Fw({fnName:"publish"}),cy(A=>A.mediaType),Hr(A=>function(){for(var e=arguments.length,o=new Array(e),a=0;ad.unpublish()),c}),DM(function(){var A,e;this.localTracks.size===0&&_I()&&((e=(A=this.singlePC)==null?void 0:A.getPeerConnection())==null||e.getSenders().forEach(o=>o.track&&o.replaceTrack(null)))})],By.prototype,"unpublish"),di([zW(A=>{if(A.code!==lt.API_CALL_ABORTED)throw A}),cy(A=>A.userId)],By.prototype,"replaceTrack"),di([cy(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}),Yh({settings:{retries:Tf,timeout:A=>Bp(A)},onError(A,e,o,a){if(A.message.includes("timeout"))this._log.warn("subscribe timeout"),e();else{let c=A?.code===lt.API_CALL_ABORTED;this._log[c?"warn":"error"]("subscribe failed ".concat(a.map(d=>d.strMediaType).join(","),": ").concat(A)),o(A),U.emit(nA.SUBSCRIBE_FAILED,{room:this,remoteTracks:a})}}})],By.prototype,"subscribe"),di([Fw({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")})}}),cy(function(){for(var A=arguments.length,e=new Array(A),o=0;oi in t?pY(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,fnA=(t,i)=>{for(var r in i||(i={}))G6.call(i,r)&&Vj(t,r,i[r]);if(Oz)for(var r of Oz(i))mnA.call(i,r)&&Vj(t,r,i[r]);return t},ynA=(t,i)=>function(){return i||(0,t[N6(t)[0]])((i={exports:{}}).exports,i),i.exports},DnA=(t,i,r,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let u of N6(i))G6.call(t,u)||u===r||pY(t,u,{get:()=>i[u],enumerable:!(l=T6(i,u))||l.enumerable});return t},SnA=(t,i,r)=>(r=t!=null?QnA(pnA(t)):{},DnA(pY(r,"default",{value:t,enumerable:!0}),t)),h_=(t,i,r,l)=>{for(var u,p=T6(i,r),y=t.length-1;y>=0;y--)(u=t[y])&&(p=u(i,r,p)||p);return p&&pY(i,r,p),p},pn=(t,i,r)=>Vj(t,typeof i!="symbol"?i+"":i,r),MnA=ynA({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,l="~";function u(){}function p(k,F,j){this.fn=k,this.context=F,this.once=j||!1}function y(k,F,j,lA,aA){if(typeof j!="function")throw new TypeError("The listener must be a function");var mA=new p(j,lA||k,aA),IA=l?l+F:F;return k._events[IA]?k._events[IA].fn?k._events[IA]=[k._events[IA],mA]:k._events[IA].push(mA):(k._events[IA]=mA,k._eventsCount++),k}function w(k,F){--k._eventsCount===0?k._events=new u:delete k._events[F]}function _(){this._events=new u,this._eventsCount=0}Object.create&&(u.prototype=Object.create(null),new u().__proto__||(l=!1)),_.prototype.eventNames=function(){var k,F,j=[];if(this._eventsCount===0)return j;for(F in k=this._events)r.call(k,F)&&j.push(l?F.slice(1):F);return Object.getOwnPropertySymbols?j.concat(Object.getOwnPropertySymbols(k)):j},_.prototype.listeners=function(k){var F=l?l+k:k,j=this._events[F];if(!j)return[];if(j.fn)return[j.fn];for(var lA=0,aA=j.length,mA=new Array(aA);lA{if(!navigator.userAgent.includes("Firefox"))return t;const i=t.split(`\r +`),r=[],l=[];i.forEach(y=>{const w=y.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&r.push(y)}),r.length>1&&l.push(...r.slice(1));const u=l.map(y=>{const w=/a=rtpmap:(\d+)\s/.exec(y);return w&&w.length>1?w[1]:null}).filter(y=>y!==null),p=[];return i.forEach(y=>{let w=y;if(y.includes("a=setup")&&(w="a=setup:passive"),(y.includes("m=audio")||y.includes("m=video"))&&(w=y.split(" ").filter((_,k)=>k<3||!u.includes(_)).join(" ")),y.includes("a=fmtp")||y.includes("a=rtcp-fb")||y.includes("a=rtpmap")){const _=/a=(?:fmtp|rtcp-fb|rtpmap):(\d+)\s/.exec(y);if(_&&_.length>1&&u.includes(_[1]))return}p.push(w)}),p.join(`\r +`)},Pz=t=>{const i=t.split(`\r +`),r=[];i.forEach(y=>{const w=y.toLowerCase();w.includes("a=rtpmap")&&w.includes("h264")&&r.push(y)});const l=r.map(y=>{const w=/a=rtpmap:(\d+)\s/.exec(y);return w&&w.length>1?w[1]:null}).filter(y=>y!==null),u=[];i.forEach(y=>{let w=y;if(y.includes("a=fmtp:111")&&(w=`${y};stereo=1`),y.includes("a=fmtp")){const _=/a=fmtp:(\d+)\s/.exec(y);_&&_.length>1&&l.includes(_[1])&&(w=`${y};sps-pps-idr-in-keyframe=1`)}u.push(w)});const p=u.join(`\r +`);return RnA(p)},wnA="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",JK=(t=21)=>{let i="",r=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)i+=wnA[63&r[t]];return i},c_=t=>typeof t=="function",_nA=0,TnA=1,xz=2;function NnA({retryFunction:t,settings:i,onError:r,onRetrying:l,onRetryFailed:u,onRetrySuccess:p,context:y}){return function(...w){const{retries:_=5,timeout:k=1e3}=i;let F=0,j=-1,lA=_nA;const aA=async(mA,IA)=>{const tA=y||this;try{const MA=await t.apply(tA,w);F>0&&p&&p.call(this,F),F=0,mA(MA)}catch(MA){const PA=()=>{clearTimeout(j),F=0,lA=xz,IA(MA)},ge=()=>{lA!==xz&&F<(c_(_)?_():_)?(F++,lA=TnA,c_(l)&&l.call(this,F,PA),j=window.setTimeout(()=>{j=-1,aA(mA,IA)},c_(k)?k(F):k)):(PA(),c_(u)&&u.call(this,MA))};c_(r)?r.call(this,{error:MA,retry:ge,reject:IA,retryFuncArgs:w,retriedCount:F}):ge()}};return new Promise(aA)}}var GnA=NnA,cQ=new WeakMap;function bnA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:l}){return function(u,p,y){const w=GnA({retryFunction:y.value,settings:t,onError({error:_,retry:k,reject:F,retryFuncArgs:j}){var lA;i?i.call(this,_,()=>{var aA;(aA=cQ.get(u))!=null&&aA.has(p)?k():F(_)},F,j):(lA=cQ.get(u))!=null&&lA.has(p)?k():F(_)},onRetrying(_,k){var F;c_(r)&&r.call(this,_,k),(F=cQ.get(u))!=null&&F.has(p)&&(cQ.get(u).get(p).stopRetry=k)},onRetryFailed:l});return y.value=function(..._){const k=cQ.get(u);return k?k.set(p,{args:_}):cQ.set(u,new Map([[p,{args:_}]])),w.apply(this,_).finally(()=>{var F;return(F=cQ.get(u))==null?void 0:F.delete(p)})},y}}function knA({fnName:t,callback:i,validateArgs:r=!0}){return function(l,u,p){const y=p.value;return p.value=function(...w){var _,k;if((_=cQ.get(l))!=null&&_.has(t)){const{stopRetry:F,args:j}=cQ.get(l).get(t);let lA=!0;if(r){for(const aA of j)if(!w.find(mA=>mA===aA)){lA=!1;break}}lA&&(i&&i.apply(this,w),F&&F(),(k=cQ.get(l))==null||k.delete(t))}return y.apply(this,w)},p}}var LnA=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(),u=this.parseAudioStats(r),p=this.parseVideoStats(r),y=this.parseNetworkStats(r);this._prevReportTime=l,this.callback({audio:u,video:p,network:y})}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,u;const p={bitrate:0,volume:0,packetLossRate:0,jitterBufferDelay:0,bytesReceived:0,packetsReceived:0,packetsLost:0};for(const y of t){if(y.type==="inbound-rtp"&&(y.mediaType==="audio"||y.kind==="audio")){if(p.bytesReceived=y.bytesReceived||0,p.packetsReceived=y.packetsReceived||0,p.packetsLost=y.packetsLost||0,this.previousRawStats&&this.previousRawStats.audio){const k=this.getDifferenceValue(this.previousRawStats.audio.bytesReceived,p.bytesReceived);p.bitrate=Math.round(8*k/this.statInterval/1e3)}const w=this.getDifferenceValue((i=this.previousRawStats)==null?void 0:i.audio.packetsLost,p.packetsLost),_=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.audio.packetsReceived,p.packetsReceived)+w;if(_>0&&(p.packetLossRate=Math.round(w/_*100)),this.core.utils.isUndefined(y.audioLevel)||(p.volume=y.audioLevel||0),y.jitterBufferDelay&&y.jitterBufferEmittedCount){let{jitterBufferEmittedCount:k}=y,{jitterBufferDelay:F}=y;(l=this.previousRawStats)!=null&&l.audio&&(k=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferEmittedCount,y.jitterBufferEmittedCount),F=this.getDifferenceValue(this.previousRawStats.audio.jitterBufferDelay,y.jitterBufferDelay)),k>0&&(p.jitterBufferDelay=Math.floor(F/k*1e3)),this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.jitterBufferDelay=y.jitterBufferDelay,this.previousRawStats.audio.jitterBufferEmittedCount=y.jitterBufferEmittedCount}this.previousRawStats||this.initPreviousRawStats(),this.previousRawStats.audio.bytesReceived=p.bytesReceived,this.previousRawStats.audio.packetsReceived=p.packetsReceived,this.previousRawStats.audio.packetsLost=p.packetsLost}!this.core.utils.isUndefined(y.audioLevel)&&((u=this.audioTransceiver)!=null&&u.receiver.track)&&y.trackIdentifier===this.audioTransceiver.receiver.track.id&&(p.volume=y.audioLevel||0)}return p}parseVideoStats(t){var i,r,l,u,p;const y={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(y.bytesReceived=w.bytesReceived||0,y.packetsReceived=w.packetsReceived||0,y.packetsLost=w.packetsLost||0,y.framesDecoded=w.framesDecoded||0,this.core.utils.isUndefined(w.framesPerSecond)||(y.frameRate=Math.round(w.framesPerSecond)),w.decoderImplementation&&this._prevDecoderImplementation!==w.decoderImplementation){const F=this._decodeMap.get(w.codecId),j=((i=F?.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 F=this.getDifferenceValue(this.previousRawStats.video.bytesReceived,y.bytesReceived);y.bitrate=Math.round(8*F/this.statInterval/1e3)}const _=this.getDifferenceValue((r=this.previousRawStats)==null?void 0:r.video.packetsLost,y.packetsLost),k=this.getDifferenceValue((l=this.previousRawStats)==null?void 0:l.video.packetsReceived,y.packetsReceived)+_;if(k>0&&(y.packetLossRate=Math.round(_/k*100)),w.jitterBufferDelay&&w.jitterBufferEmittedCount){let{jitterBufferEmittedCount:F}=w,{jitterBufferDelay:j}=w;(u=this.previousRawStats)!=null&&u.video&&(F=this.getDifferenceValue(this.previousRawStats.video.jitterBufferEmittedCount,w.jitterBufferEmittedCount),j=this.getDifferenceValue(this.previousRawStats.video.jitterBufferDelay,w.jitterBufferDelay)),F>0&&(y.jitterBufferDelay=Math.floor(j/F*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=y.bytesReceived,this.previousRawStats.video.packetsReceived=y.packetsReceived,this.previousRawStats.video.packetsLost=y.packetsLost}!this.core.utils.isUndefined(w.frameWidth)&&((p=this.videoTransceiver)!=null&&p.receiver.track)&&w.trackIdentifier===this.videoTransceiver.receiver.track.id&&(y.width=w.frameWidth,y.height=w.frameHeight)}return y}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}}}},UnA=SnA(MnA()),Yz=Symbol("instance"),z2=Symbol("cacheResult"),HK=class{constructor(i,r,l){this.oldState=i,this.newState=r,this.action=l,this.aborted=!1}abort(i){this.aborted=!0,fL.call(i,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},qK=class extends Error{constructor(i,r,l){super(r),this.state=i,this.message=r,this.cause=l}};function FnA(t){return typeof t=="object"&&t&&"then"in t}var mL=new Map;function Z2(t,i,r={}){return(l,u,p)=>{const y=r.action||u;if(!r.context){const _=mL.get(l)||[];mL.has(l)||mL.set(l,_),_.push({from:t,to:i,action:y})}const w=p.value;p.value=function(..._){let k=this;if(r.context&&(k=xC.get(typeof r.context=="function"?r.context.call(this,..._):r.context)),k.state===i)return r.sync?k[z2]:Promise.resolve(k[z2]);k.state instanceof HK&&k.state.action==r.abortAction&&k.state.abort(k);let F=null;Array.isArray(t)?t.length==0?k.state instanceof HK&&k.state.abort(k):typeof k.state=="string"&&t.includes(k.state)||(F=new qK(k._state,`${k.name} ${y} to ${i} failed: current state ${k._state} not from ${t.join("|")}`)):t!==k.state&&(F=new qK(k._state,`${k.name} ${y} to ${i} failed: current state ${k._state} not from ${t}`));const j=tA=>{if(r.fail&&r.fail.call(this,tA),r.sync){if(r.ignoreError)return tA;throw tA}return r.ignoreError?Promise.resolve(tA):Promise.reject(tA)};if(F)return j(F);const lA=k.state,aA=new HK(lA,i,y);fL.call(k,aA);const mA=tA=>{var MA;return k[z2]=tA,aA.aborted||(fL.call(k,i),(MA=r.success)===null||MA===void 0||MA.call(this,k[z2])),tA},IA=tA=>(fL.call(k,lA,tA),j(tA));try{const tA=w.apply(this,_);return FnA(tA)?tA.then(mA).catch(IA):r.sync?mA(tA):Promise.resolve(mA(tA))}catch(tA){return IA(new qK(k._state,`${k.name} ${y} from ${t} to ${i} failed: ${tA}`,tA instanceof Error?tA:new Error(String(tA))))}}}}var OnA=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 fL(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 UC extends UnA.default{constructor(i,r,l){super(),this.name=i,this.groupName=r,this._state=UC.INIT,i||(i=Date.now().toString(36)),l?Object.setPrototypeOf(this,l):l=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const u=l[Yz];u?this.name=u.name+"-"+u.count++:l[Yz]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=mL.get(i)||[];let l=new Set,u=[],p=[];const y=new Set,w=Object.getPrototypeOf(i);mL.has(w)&&(w.stateDiagram.forEach(k=>l.add(k)),w.allStates.forEach(k=>y.add(k))),r.forEach(({from:k,to:F,action:j})=>{typeof k=="string"?u.push({from:k,to:F,action:j}):k.length?k.forEach(lA=>{u.push({from:lA,to:F,action:j})}):p.push({to:F,action:j})}),u.forEach(({from:k,to:F,action:j})=>{y.add(k),y.add(F),y.add(j+"ing"),l.add(`${k} --> ${j}ing : ${j}`),l.add(`${j}ing --> ${F} : ${j} 🟢`),l.add(`${j}ing --> ${k} : ${j} 🔴`)}),p.forEach(({to:k,action:F})=>{l.add(`${F}ing --> ${k} : ${F} 🟢`),y.forEach(j=>{j!==k&&l.add(`${j} --> ${F}ing : ${F}`)})});const _=[...l];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:y}}),_}static get(i){let r;return typeof i=="string"?(r=UC.instances.get(i),r||UC.instances.set(i,r=new UC(i,void 0,Object.create(UC.prototype)))):(r=UC.instances2.get(i),r||UC.instances2.set(i,r=new UC(i.constructor.name,void 0,Object.create(UC.prototype)))),r}static getState(i){var r;return(r=UC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){OnA(UC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){fL.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 oL=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 u,p;this._log.warn("handleAutoPlayFailed",r);const y=()=>{this.audioPlayer.resume().then(()=>{document.removeEventListener("click",y,!0)})};document.addEventListener("click",y,!0),(p=(u=this.callback)==null?void 0:u.onAutoPlayFailed)==null||p.call(u,{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))}};h_([Z2([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)}})],oL.prototype,"onLoadStart"),h_([Z2(["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)}})],oL.prototype,"onPlaying"),h_([Z2("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)}})],oL.prototype,"onPaused"),h_([Z2([],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)}})],oL.prototype,"onStopped");var Vz=oL,PnA=["overseas-webrtc.tlivewebrtc.com","oswebrtc-lint.tliveplay.com"],p1=class b6{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 Vz(i,this._log),i.innerEmitter.on(i.INNER_EVENT.SEI_MESSAGE,this.onSEIMessage,this)}getName(){return b6.Name}getAlias(){return"LEB"}getGroup(){return""}getValidateRule(i){switch(i){case"start":return vnA;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 u of Object.keys(i)){const p=i[u];typeof p=="function"&&(l.includes(u)?r[u]=p:r[u]=(...y)=>(this._log.debug(`callback ${u} called`,y.length>0?y[0]:""),p(...y)))}return r}async start(i){var r;this.isStopped=!1;const{view:l,url:u,volume:p,muted:y,fillMode:w,loggerConfig:_,callback:k}=i;this.callback=this.wrapCallback(k),this.player.setCallback(this.callback);const{errorModule:{RtcError:F,ErrorCode:j,ErrorCodeDictionary:lA},loggerManager:aA,rtcDectection:mA}=this.core;if(this._sdkAppId=_.sdkAppId,this._userId=_.userId,this._log.setSdkAppId(_.sdkAppId),this._log.setUserId(_.userId),this.player.updateLogConfig(_),aA.addJoinedUser(_),!mA.isWebRTCSupported()||!mA.isAddTransceiverSupported())throw new F({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 F({code:j.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_H264_DECODE,message:"h264 not supported"});!mA.IS_SEI_SUPPORTED&&k?.onSEIMessage&&((r=k.onError)==null||r.call(k,new F({code:j.ENV_NOT_SUPPORTED,extraCode:lA.NOT_SUPPORTED_SEI,message:"sei not supported"}))),this.player.setVideoContainer(l),this.player.setMuted(y),this.player.setFillMode(w);try{await this.connect(u),this.stat=new LnA(this.peerConnection,this.core),this.stat.start(MA=>{var PA,ge;return(ge=(PA=this.callback)==null?void 0:PA.onStats)==null?void 0:ge.call(PA,MA)});const IA=this.player.play();this.player.setVolume(p);const tA=this.createStreamHealthCheckPromise();await Promise.race([IA,tA]),this.clearStreamHealthCheck(),this.isStarted=!0}catch(IA){throw this.stop(),IA}}async update(i){const{view:r,url:l,volume:u,muted:p,fillMode:y,action:w,fullScreen:_,pictureInPicture:k}=i;l&&l!==this.streamURL&&await this.switchStream(l),this.player.setMuted(p),this.player.setVolume(u),this.player.setFillMode(y),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(k)&&(k?await this.player.enterPictureInPicture():await this.player.exitPictureInPicture())}async switchStream(i){this._log.info("switchStream",i);const r=this.peerConnection,l=this.streamURL,u=this.signalURL,p=this.svrSig,y=new Map(this.insertableStreamsAbortMap),w=this.player;delete this.peerConnection,delete this.streamURL,delete this.signalURL,delete this.svrSig,this.insertableStreamsAbortMap.clear();const _=new Vz(this.core,this._log);_.setVideoContainer(w.videoPlayer.container),_.setFillMode(w.videoPlayer.objectFit),_.setMuted(w.muted),_.setCallback(this.callback);const k=F=>{const{track:j}=F;this.createEncodedStreams(F.receiver),this.initReceiverTransform(F.receiver,j.kind==="audio"),j.kind==="audio"?_.setAudioTrack(j):_.setVideoTrack(j)};try{await this.connectForSwitch(i,k),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(F=>y.delete(F)),l&&p&&u&&this.fetchStopStreamWithParams(l,u,p).catch(F=>{this._log.warn("switchStream: stop old stream failed",F)})),this._log.info("switchStream: switch completed successfully")}catch(F){this._log.error("switchStream failed",F),_.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=u,this.svrSig=p,this.insertableStreamsAbortMap=y,this.player=w,w.audioPlayer.setMuted(w.muted),F}}waitForNewPlayerFirstFrame(i){return new Promise((r,l)=>{let u=0,p=!1;const y=i.videoPlayer.getElement();if(!y)return void l(new Error("VideoPlayer has no video element"));const w=()=>{p=!0,clearInterval(F),y.removeEventListener("loadeddata",_),y.removeEventListener("playing",k)},_=()=>{p||(this._log.info("waitForNewPlayerFirstFrame: loadeddata event fired"),w(),r())},k=()=>{p||(this._log.info("waitForNewPlayerFirstFrame: playing event fired"),w(),r())};y.addEventListener("loadeddata",_,{once:!0}),y.addEventListener("playing",k,{once:!0}),i.play().catch(j=>{this._log.warn("waitForNewPlayerFirstFrame: play failed",j)});const F=setInterval(()=>{if(!p){if(u+=100,y.videoWidth>0&&y.videoHeight>0)return this._log.info(`waitForNewPlayerFirstFrame: video has valid dimensions ${y.videoWidth}x${y.videoHeight}`),w(),void r();u>=1e4&&(w(),l(new Error("waitForNewPlayerFirstFrame timeout")))}},100)})}connectForSwitch(i,r){return new Promise((l,u)=>{try{this.initScriptTransformWorker();const p={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},y=new RTCPeerConnection(p);this.peerConnection=y,y.onconnectionstatechange=()=>{this.connectionState=y.connectionState,this._log.info("connectForSwitch connectionState",y.connectionState),y.connectionState!=="failed"&&y.connectionState!=="closed"||u(new Error(`connection is ${y.connectionState}`)),y.connectionState==="connected"&&(this.logSelectedCandidate(),l())},y.ontrack=r,y.addTransceiver("audio",{direction:"recvonly"}),y.addTransceiver("video",{direction:"recvonly"}),this._log.info("connectForSwitch createOffer"),y.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(w=>(w.sdp=Pz(w.sdp),this._log.info("connectForSwitch setOffer"),y.setLocalDescription(w))).then(()=>{const w={sessionId:JK(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:y.localDescription};return this.exchangeSDP(i,w)}).then(w=>(this._log.info("connectForSwitch setAnswer"),y.setRemoteDescription(w))).catch(u)}catch(p){u(p)}this.connectionTimeoutId=setTimeout(()=>u(new Error("connection timeout")),1e4)})}async fetchStopStreamWithParams(i,r,l){try{const u=`${r}/webrtc/v1/stopstream`,p=await X2(u,{streamurl:i,svrsig:l},{timeout:3}),{errcode:y,errmsg:w}=p;if(y!==0)throw new Error(`errCode:${y}, errmsg:${w}`);return p}catch(u){this._log.error("fetchStopStreamWithParams error",u)}}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 u=0,p=0;l.forEach(j=>{j.type==="inbound-rtp"&&(j.mediaType==="video"||j.kind==="video")&&(u=j.bytesReceived||0,p=j.framesDecoded||0)});const{isPlaying:y}=this.player,w=y||p>0;this._log.info(`checkStreamHealth: bytesReceived=${u}, framesDecoded=${p}, isPlaying=${y}`);const{RtcError:_,ErrorCode:k,ErrorCodeDictionary:F}=this.core.errorModule;u===0?(this._log.warn("checkStreamHealth: no stream data received after 5s"),i(new _({code:k.OPERATION_FAILED,message:"no stream data received"}))):w||(this._log.warn("checkStreamHealth: decode failed"),this.isH264DecodeSupported=!1,i(new _({code:k.ENV_NOT_SUPPORTED,extraCode:F.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 u={encodedInsertableStreams:this.enableSEI,iceServers:[],sdpSemantics:"unified-plan",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",tcpCandidatePolicy:"disable",IceTransportsType:"nohost"},p=new RTCPeerConnection(u);this.peerConnection=p,p.onconnectionstatechange=()=>{this.connectionState=p.connectionState,this._log.info("connectionState",p.connectionState),p.connectionState!=="failed"&&p.connectionState!=="closed"||(this.isStarted?this.reconnect(i):l(new Error(`connection is ${p.connectionState}`))),p.connectionState==="connected"&&(this.logSelectedCandidate(),r())},p.ontrack=y=>this.onTrack(y),p.addTransceiver("audio",{direction:"recvonly"}),p.addTransceiver("video",{direction:"recvonly"}),this._log.info("createOffer"),p.createOffer({offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1}).then(y=>(y.sdp=Pz(y.sdp),this._log.info("setOffer"),p.setLocalDescription(y))).then(()=>{const y={sessionId:JK(),streamurl:i,clientinfo:this.core.environment.getOSString(),localsdp:p.localDescription};return this.exchangeSDP(i,y)}).then(y=>(this._log.info("setAnswer"),p.setRemoteDescription(y))).catch(l)}catch(u){l(u)}this.connectionTimeoutId=setTimeout(()=>l(new Error("connection timeout")),1e4)})}async exchangeSDP(i,r){let l,u,p;try{this._log.info("exchangeSDP");const y=xnA(i);if(!y)throw new Error("streamDomain is empty");const{signalDomain:w,cached:_}=await this.fetchSignalDomain(y);if(!w)throw new Error("signalDomain is empty");{this._log.info("try exchangeSDP signalDomain:",w,_);const k=await this.doExchangeSDP(`https://${w}`,r,3);l=k.url,u=k.remoteSdp,p=k.svrSig}}catch(y){this._log.warn("exchangeSDP failed, fallback",y);try{const w=await this.core.utils.promiseAny(PnA.map(_=>this.doExchangeSDP(`https://${_}`,r,3)));l=w.url,u=w.remoteSdp,p=w.svrSig}catch(w){throw this._log.error("exchangeSDP failed",w),w[0]||w}}return this.streamURL=i,this.signalURL=l,this.svrSig=p,u}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(u){this._log.error("reconnect error",u);const{RtcError:p,ErrorCode:y}=this.core.errorModule;(l=(r=this.callback)==null?void 0:r.onError)==null||l.call(r,new p({code:y.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 u=i.get(l.localCandidateId),p=i.get(l.remoteCandidateId);u&&this._log.info(`local candidate: ${u.candidateType} ${u.protocol}:${u.ip||u.address}:${u.port} ${u.networkType||""} ${u.relayProtocol?`relayProtocol:${u.relayProtocol} url: ${u.url}`:""}`),p&&this._log.info(`remote candidate: ${p.candidateType} ${p.protocol}:${p.ip||p.address}:${p.port}`);break}}async doExchangeSDP(i,r,l){const u=`${i}/webrtc/v1/pullstream`,p=await X2(u,r,{timeout:l}),{errcode:y,errmsg:w,remotesdp:_,svrsig:k}=p;if(y!==0){const F=new Error(`errCode:${y}, errMsg:${w}`);throw F.name="RequestSignalError",F}return{url:i,remoteSdp:_,svrSig:k}}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(),u=new AbortController,p={abortController:u,enqueue:y=>i.track.kind==="audio"?y:this.decodeVideoFrame(y)};l.readable.pipeThrough(new TransformStream({transform:(y,w)=>{const _=p.enqueue(y);_&&w.enqueue(_)}})).pipeTo(l.writable,u).catch(y=>{y!=="destroy"&&this._log.warn(y)}),(r=this.insertableStreamsAbortMap.get(i))==null||r.abort("destroy"),this.insertableStreamsAbortMap.set(i,u)}}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:u,TRTC:p}=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=y=>{var w,_;y.data.type==="sei"&&((_=(w=this.callback)==null?void 0:w.onSEIMessage)==null||_.call(w,{data:y.data.data,seiPayloadType:y.data.seiPayloadType}))},this.scriptTransformWorker.onerror=y=>{this._log.error("scriptTransformWorker error: ",y.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 X2(i,{streamurl:this.streamURL,svrsig:this.svrSig},{timeout:3}),{errcode:l,errmsg:u}=r;if(l!==0)throw new Error(`errCode:${l}, errmsg:${u}`);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,u;i===this.core.room&&((u=(l=this.callback)==null?void 0:l.onSEIMessage)==null||u.call(l,{data:r.seiPayload.buffer,seiPayloadType:r.seiPayloadType}))}async fetchSignalDomain(i,r=$2[0]){var l;const u=`https://${r}/signal_query`;try{const p=window.localStorage.getItem(KK);if(p){const F=JSON.parse(p);if(((l=F[i])==null?void 0:l.expire)-new Date().getTime()>0)return{signalDomain:F[i].signal,cached:!0}}const y=await X2(u,{domain:i,requestid:JK(16),client_type:"Web",client_info:window.navigator.userAgent}),{errcode:w,errmsg:_,data:k}=y;if(w===0){const{signal_domain:F,cache_time:j}=k;let lA={};const aA=window.localStorage.getItem(KK);aA&&(lA=JSON.parse(aA)),lA[i]={signal:F,expire:new Date().getTime()+1e3*j};try{window.localStorage.setItem(KK,JSON.stringify(lA))}catch{}return{signalDomain:F,cached:!1}}throw new Error(`errCode:${w} errmsg:${_}`)}catch(p){return this._log.error("fetchSignalDomain error",p),$2[1]&&r!==$2[1]?this.fetchSignalDomain(i,$2[1]):{signalDomain:"",cached:!1}}}};pn(p1,"Name","LEBPlayer"),h_([knA({fnName:"connect"})],p1.prototype,"stop"),h_([bnA({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:u}=this.core.errorModule;this.isFireWallErrorEmitted=!0,this.callback.onError(new r({code:l.OPERATION_FAILED,extraCode:u.FIREWALL_RESTRICTION,message:"firewall restriction"}))}},onError(t,i,r,l){var u;if(this._log.warn("connect failed",t),this.peerConnection&&(this.peerConnection.close(),delete this.peerConnection),!this.isStopped&&((u=t.message||t)==null?void 0:u.includes("connection")))i();else{const{RtcError:p,ErrorCode:y}=this.core.errorModule;r(new p({code:y.UNKNOWN_ERROR,message:t.message}))}}})],p1.prototype,"connect");var k6=p1,X2=async(t,i,r={})=>{const{timeout:l=10}=r;let u,p=0,y={};window.AbortController&&(u=new window.AbortController,y={signal:u.signal},p=window.setTimeout(()=>u.abort(),1e3*l));const w=await fetch(t,fnA({body:JSON.stringify(i),cache:"no-cache",credentials:"same-origin",headers:{"content-type":"text/plain;charset=utf-8"},method:"POST",mode:"cors"},y));if(p&&window.clearTimeout(p),w.status!==200)throw new Error(`Network Error, status code:${w.status}`);return w.json()},$2=["webrtc-signal-scheduler.tlivesource.com","bak-webrtc-signal-scheduler.tlivesource.com"],KK="LEB_PLAYER_STORAGE_KEY",xnA=t=>{const i=/^(?:webrtc:\/\/)([0-9.\-A-Za-z_]+)(?:\/)(?:[0-9.\-A-Za-z_=]+)(?:\/)(?:[^?#]*)(?:\?*)(?:[^?#]*)/.exec(t);return i?i[1]:""},YnA=k6;const VnA=Object.freeze(Object.defineProperty({__proto__:null,LEBPlayer:k6,default:YnA},Symbol.toStringTag,{value:"Module"})),JnA=ZL(VnA);var L6=Object.defineProperty,HnA=Object.defineProperties,qnA=Object.getOwnPropertyDescriptors,Jz=Object.getOwnPropertySymbols,KnA=Object.prototype.hasOwnProperty,jnA=Object.prototype.propertyIsEnumerable,Jj=(t,i,r)=>i in t?L6(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,WnA=(t,i)=>{for(var r in i||(i={}))KnA.call(i,r)&&Jj(t,r,i[r]);if(Jz)for(var r of Jz(i))jnA.call(i,r)&&Jj(t,r,i[r]);return t},znA=(t,i)=>HnA(t,qnA(i)),ZnA=(t,i)=>{for(var r in i)L6(t,r,{get:i[r],enumerable:!0})},Jg=(t,i,r)=>Jj(t,typeof i!="symbol"?i+"":i,r);async function XnA({sdkAppId:t,userId:i,userSig:r,core:l}){var u;const p=Math.round(new Date().getTime()/1e3);try{const y=await l.schedule.getAbilityConfig(t,l.schedule.ScheduleRequestType.TRTC_AUTO_CONF,{sdkAppId:t,userId:i,userSig:r,timestamp:p});l.log.info(`virtual background ability response: ${JSON.stringify(y)}`);const{data:w}=y;return(u=w?.trtcAutoConf)!=null&&u.web_ar?{auth:!0,timestamp:p}:{auth:!1}}catch(y){return l.log.error("virtual background fetch error",y),{auth:!1}}}var $nA={sdkAppId:{required:!0,type:"number"},userId:{required:!0,type:"string"},userSig:{required:!0,type:"string"}};function ArA(t){return{name:"VirtualBackgroundOptions",type:"object",required:!0,allowEmpty:!1,properties:znA(WnA({},$nA),{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,u){var p;const{RtcError:y,ErrorCode:w,ErrorCodeDictionary:_}=t.errorModule;if(!i)return;const{type:k,src:F,onAbort:j}=i;if(k==="image"&&!F)throw new y({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_REQUIRED,fnName:l,messageParams:{key:"src"}});if(j&&!t.utils.isFunction(j))throw new y({code:w.INVALID_PARAMETER,extraCode:_.INVALID_PARAMETER_TYPE,fnName:l,messageParams:{key:"onAbort",value:typeof j,rule:{type:"Function"}}});if(!((p=t.room.videoManager.cameraTrack)!=null&&p.mediaTrack))throw new y({code:w.INVALID_OPERATION,extraCode:_.INVALID_OPERATION_NEED_VIDEO,fnName:l})}}}function erA(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,u){if(!i)return;const{RtcError:p,ErrorCode:y,ErrorCodeDictionary:w}=t.errorModule,{type:_,src:k}=i;if(_==="image"&&!k)throw new p({code:y.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_REQUIRED,fnName:l,messageParams:{key:"src"}})}}}function trA(t){return{name:"StopVirtualBackgroundOptions",required:!1}}var irA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,l,u=i;u.ready=new Promise(($,K)=>{r=$,l=K});var p=Object.assign({},u),y="";typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),t&&(y=t),y=y.indexOf("blob:")!==0?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,k=u.print||console.log.bind(console),F=u.printErr||console.error.bind(console);function j($){if(si($))return function(K){for(var RA=atob(K),KA=new Uint8Array(RA.length),Ae=0;Ae$.startsWith(ft);function Vt($){return Promise.resolve().then(()=>function(K){if(K==re&&w)return new Uint8Array(w);var RA=j(K);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function gi($,K,RA,KA){return function(Ae,pe,Fe){return Vt(Ae).then(Ue=>WebAssembly.instantiate(Ue,pe)).then(Ue=>Ue).then(Fe,Ue=>{F(`failed to asynchronously prepare wasm: ${Ue}`),It(Ue)})}(K,RA,KA)}si(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/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/Mi4wKmEyKmEyOjEuMC0yLjAqKDEuMC1hMikqKDEuMC1hMik7CiAgICAgIC8vIGZsb2F0IGRlbHRhID0gYSAtIGEyOwogICAgICAvLyBpZiAoZGVsdGEgPCAwLjI1ICYmIGRlbHRhID4gLTAuMjUpCiAgICAgIC8vIHsKICAgICAgLy8gICAgIGEgPSBhICsgMC41KmRlbHRhOwogICAgICAvLyB9CiAgICAgIAogICAgICB2ZWMyIG8gPSAxLjAgLyB2ZWMyKHRleHR1cmVTaXplKGZyYW1lLCAwKSk7CiAgICAACiAgICAgIG91dENvbG9yID0gZzsKICAAI3ZlcnNpb24gMzAwIGVzCmluIHZlYzIgYV9wb3NpdGlvbjsKaW4gdmVjMiBhX3RleENvb3JkOwoKdW5pZm9ybSBtYXQ0IHVfdGV4dHVyZU1hdHJpeDsKCm91dCB2ZWMyIHZfdGV4Q29vcmQ7CnZvaWQgbWFpbigpIHsKICBnbF9Qb3NpdGlvbiA9IHZlYzQoYV9wb3NpdGlvbi54LCBhX3Bvc2l0aW9uLnksIDAsIDEpOwogIHZfdGV4Q29vcmQgPSh1X3RleHR1cmVNYXRyaXggKiB2ZWM0KGFfdGV4Q29vcmQsIDAsIDEpKS54eTsKfQoAc2V0QmVhdXR5ICVmICVmICVmICVmICVmCgBvdXRDb2xvciA9IHNyY19jb2xvcjsKAG91dENvbG9yID0gbWl4KHZlYzQodV9jb2xvciwxLjApLHNyY19jb2xvcixhKTsKADZBbGxJbjEAAIAoAABfFgAAUDZBbGxJbjEAAAAABCkAAHAWAAAAAAAAaBYAAFBLNkFsbEluMQAAAAQpAACMFgAAAQAAAGgWAABpaQB2AHZpAHwWAADMFgAATjEwZW1zY3JpcHRlbjN2YWxFAACAKAAAuBYAAGlpaQB2aWlpAAAAALwnAAB8FgAAcCgAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkZABBkC4LyAi8JwAAfBYAAHAoAABwKAAAcCgAAHAoAAB2aWlkZGRkALwnAAB8FgAAdmlpALwnAADMFgAAzBYAAHwWAADMFgAAHCgAALwnAADMFgAAoBcAAE5TdDNfXzIxMmJhc2ljX3N0cmluZ0ljTlNfMTFjaGFyX3RyYWl0c0ljRUVOU185YWxsb2NhdG9ySWNFRUVFAACAKAAAYBcAAMwWAAC8JwAAzBYAAMwWAABOU3QzX18yMTJiYXNpY19zdHJpbmdJaE5TXzExY2hhcl90cmFpdHNJaEVFTlNfOWFsbG9jYXRvckloRUVFRQAAgCgAALgXAABOU3QzX18yMTJiYXNpY19zdHJpbmdJd05TXzExY2hhcl90cmFpdHNJd0VFTlNfOWFsbG9jYXRvckl3RUVFRQAAgCgAAAAYAABOU3QzX18yMTJiYXNpY19zdHJpbmdJRHNOU18xMWNoYXJfdHJhaXRzSURzRUVOU185YWxsb2NhdG9ySURzRUVFRQAAAIAoAABIGAAATlN0M19fMjEyYmFzaWNfc3RyaW5nSURpTlNfMTFj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")||(qe=re,re=u.locateFile?u.locateFile(qe,y):y+qe);var Fi=$=>{for(;$.length>0;)$.shift()(u)};u.noExitRuntime;function _o($){this.excPtr=$,this.ptr=$-24,this.set_type=function(K){MA[this.ptr+4>>2]=K},this.get_type=function(){return MA[this.ptr+4>>2]},this.set_destructor=function(K){MA[this.ptr+8>>2]=K},this.get_destructor=function(){return MA[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,RA){this.set_adjusted_ptr(0),this.set_type(K),this.set_destructor(RA)},this.set_adjusted_ptr=function(K){MA[this.ptr+16>>2]=K},this.get_adjusted_ptr=function(){return MA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Ga(this.get_type()))return MA[this.excPtr>>2];var K=this.get_adjusted_ptr();return K!==0?K:this.excPtr}}var to,uo,Ys,ki=$=>{for(var K="",RA=$;aA[RA];)K+=to[aA[RA++]];return K},os={},Ko={},$i={},jt=$=>{throw new uo($)},io=$=>{throw new Ys($)},bi=($,K,RA)=>{function KA(Ue){var ot=RA(Ue);ot.length!==$.length&&io("Mismatched type converter count");for(var ut=0;ut<$.length;++ut)Ms($[ut],ot[ut])}$.forEach(function(Ue){$i[Ue]=K});var Ae=new Array(K.length),pe=[],Fe=0;K.forEach((Ue,ot)=>{Ko.hasOwnProperty(Ue)?Ae[ot]=Ko[Ue]:(pe.push(Ue),os.hasOwnProperty(Ue)||(os[Ue]=[]),os[Ue].push(()=>{Ae[ot]=Ko[Ue],++Fe===pe.length&&KA(Ae)}))}),pe.length===0&&KA(Ae)};function Ms($,K,RA={}){if(!("argPackAdvance"in K))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(KA,Ae,pe={}){var Fe=Ae.name;if(KA||jt(`type "${Fe}" must have a positive integer typeid pointer`),Ko.hasOwnProperty(KA)){if(pe.ignoreDuplicateRegistrations)return;jt(`Cannot register type '${Fe}' twice`)}if(Ko[KA]=Ae,delete $i[KA],os.hasOwnProperty(KA)){var Ue=os[KA];delete os[KA],Ue.forEach(ot=>ot())}}($,K,RA)}var qA,ce=$=>{jt($.$$.ptrType.registeredClass.name+" instance already deleted")},Pe=!1,kt=$=>{},it=$=>{$.count.value-=1,$.count.value===0&&(K=>{K.smartPtr?K.smartPtrType.rawDestructor(K.smartPtr):K.ptrType.registeredClass.rawDestructor(K.ptr)})($)},gt=($,K,RA)=>{if(K===RA)return $;if(RA.baseClass===void 0)return null;var KA=gt($,K,RA.baseClass);return KA===null?null:RA.downcast(KA)},Xt={},$t=()=>Object.keys(Oi).length,Ge=()=>{var $=[];for(var K in Oi)Oi.hasOwnProperty(K)&&$.push(Oi[K]);return $},je=[],Mt=()=>{for(;je.length;){var $=je.pop();$.$$.deleteScheduled=!1,$.delete()}},Rt=$=>{qA=$,je.length&&qA&&qA(Mt)},Oi={},Qo=($,K)=>(K=((RA,KA)=>{for(KA===void 0&&jt("ptr should not be undefined");RA.baseClass;)KA=RA.upcast(KA),RA=RA.baseClass;return KA})($,K),Oi[K]),To=($,K)=>(K.ptrType&&K.ptr||io("makeClassHandle requires ptr and ptrType"),!!K.smartPtrType!=!!K.smartPtr&&io("Both smartPtrType and smartPtr must be specified"),K.count={value:1},No(Object.create($,{$$:{value:K}})));function oo($){var K=this.getPointee($);if(!K)return this.destructor($),null;var RA=Qo(this.registeredClass,K);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=K,RA.$$.smartPtr=$,RA.clone();var KA=RA.clone();return this.destructor($),KA}function Ae(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:K,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var pe,Fe=this.registeredClass.getActualType(K),Ue=Xt[Fe];if(!Ue)return Ae.call(this);pe=this.isConst?Ue.constPointerType:Ue.pointerType;var ot=gt(K,this.registeredClass,pe.registeredClass);return ot===null?Ae.call(this):this.isSmartPointer?To(pe.registeredClass.instancePrototype,{ptrType:pe,ptr:ot,smartPtrType:this,smartPtr:$}):To(pe.registeredClass.instancePrototype,{ptrType:pe,ptr:ot})}var No=$=>typeof FinalizationRegistry>"u"?(No=K=>K,$):(Pe=new FinalizationRegistry(K=>{it(K.$$)}),kt=K=>Pe.unregister(K),(No=K=>{var RA=K.$$;if(RA.smartPtr){var KA={$$:RA};Pe.register(K,KA,K)}return K})($));function $s(){}var rn=($,K)=>Object.defineProperty(K,"name",{value:$}),us=($,K,RA)=>{if($[K].overloadTable===void 0){var KA=$[K];$[K]=function(){return $[K].overloadTable.hasOwnProperty(arguments.length)||jt(`Function '${RA}' 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[KA.argCount]=KA}};function an($,K,RA,KA,Ae,pe,Fe,Ue){this.name=$,this.constructor=K,this.instancePrototype=RA,this.rawDestructor=KA,this.baseClass=Ae,this.getActualType=pe,this.upcast=Fe,this.downcast=Ue,this.pureVirtualFunctions=[]}var yo=($,K,RA)=>{for(;K!==RA;)K.upcast||jt(`Expected null or instance of ${RA.name}, got an instance of ${K.name}`),$=K.upcast($),K=K.baseClass;return $};function pA($,K){if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=K.$$.ptrType.registeredClass;return yo(K.$$.ptr,RA,this.registeredClass)}function Jn($,K){var RA;if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&K.$$.ptrType.isConst&&jt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);var KA=K.$$.ptrType.registeredClass;if(RA=yo(K.$$.ptr,KA,this.registeredClass),this.isSmartPointer)switch(K.$$.smartPtr===void 0&&jt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:K.$$.smartPtrType===this?RA=K.$$.smartPtr:jt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=K.$$.smartPtr;break;case 2:if(K.$$.smartPtrType===this)RA=K.$$.smartPtr;else{var Ae=K.clone();RA=this.rawShare(RA,cn.toHandle(()=>Ae.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:jt("Unsupporting sharing policy")}return RA}function Br($,K){if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`),K.$$.ptrType.isConst&&jt(`Cannot convert argument of type ${K.$$.ptrType.name} to parameter type ${this.name}`);var RA=K.$$.ptrType.registeredClass;return yo(K.$$.ptr,RA,this.registeredClass)}function Es($){return this.fromWireType(MA[$>>2])}function jr($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut,St){this.name=$,this.registeredClass=K,this.isReference=RA,this.isConst=KA,this.isSmartPointer=Ae,this.pointeeType=pe,this.sharingPolicy=Fe,this.rawGetPointee=Ue,this.rawConstructor=ot,this.rawShare=ut,this.rawDestructor=St,Ae||K.baseClass!==void 0?this.toWireType=Jn:KA?(this.toWireType=pA,this.destructorFunction=null):(this.toWireType=Br,this.destructorFunction=null)}var Pi,vs,ir=[],An=$=>{var K=ir[$];return K||($>=ir.length&&(ir.length=$+1),ir[$]=K=Pi.get($)),K},wn=($,K,RA)=>$.includes("j")?((KA,Ae,pe)=>{var Fe=u["dynCall_"+KA];return pe&&pe.length?Fe.apply(null,[Ae].concat(pe)):Fe.call(null,Ae)})($,K,RA):An(K).apply(null,RA),Jt=($,K)=>{var RA,KA,Ae,pe=($=ki($)).includes("j")?(RA=$,KA=K,Ae=[],function(){return Ae.length=0,Object.assign(Ae,arguments),wn(RA,KA,Ae)}):An(K);return typeof pe!="function"&&jt(`unknown function pointer with signature ${$}: ${K}`),pe},fg=$=>{var K=Ia($),RA=ki(K);return yn(K),RA},On=($,K)=>{var RA=[],KA={};throw K.forEach(function Ae(pe){KA[pe]||Ko[pe]||($i[pe]?$i[pe].forEach(Ae):(RA.push(pe),KA[pe]=!0))}),new vs(`${$}: `+RA.map(fg).join([", "]))},Gn=($,K)=>{for(var RA=[],KA=0;KA<$;KA++)RA.push(MA[K+4*KA>>2]);return RA},Vs=$=>{for(;$.length;){var K=$.pop();$.pop()(K)}};function Qr($,K,RA,KA,Ae,pe){var Fe=K.length;Fe<2&&jt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Ue=K[1]!==null&&RA!==null,ot=!1,ut=1;ut($ instanceof Object||jt(`${RA} with invalid "this": ${$}`),$ instanceof K.registeredClass.constructor||jt(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||jt(`cannot call emscripten binding method ${RA} on deleted object`),yo($.$$.ptr,$.$$.ptrType.registeredClass,K.registeredClass));function pr(){this.allocated=[void 0],this.freelist=[]}var po=new pr,gn=$=>{$>=po.reserved&&--po.get($).refcount===0&&po.free($)},fl=()=>{for(var $=0,K=po.reserved;K($||jt("Cannot use deleted val. handle = "+$),po.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return po.allocate({refcount:1,value:$})}}};function mr($){return this.fromWireType(tA[$>>2])}var ks,Yc,ps,rs=$=>{if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$},Bu=($,K)=>{switch(K){case 4:return function(RA){return this.fromWireType(PA[RA>>2])};case 8:return function(RA){return this.fromWireType(ge[RA>>3])};default:throw new TypeError(`invalid float width (${K}): ${$}`)}},ja=($,K,RA)=>{switch(K){case 1:return RA?KA=>lA[KA|0]:KA=>aA[KA|0];case 2:return RA?KA=>mA[KA>>1]:KA=>IA[KA>>1];case 4:return RA?KA=>tA[KA>>2]:KA=>MA[KA>>2];default:throw new TypeError(`invalid integer width (${K}): ${$}`)}},ds=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,og=($,K,RA)=>{for(var KA=K+RA,Ae=K;$[Ae]&&!(Ae>=KA);)++Ae;if(Ae-K>16&&$.buffer&&ds)return ds.decode($.subarray(K,Ae));for(var pe="";K>10,56320|1023&ut)}}else pe+=String.fromCharCode((31&Fe)<<6|Ue)}else pe+=String.fromCharCode(Fe)}return pe},LI=($,K)=>$?og(aA,$,K):"",Xo=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Zi=($,K)=>{for(var RA=$,KA=RA>>1,Ae=KA+K/2;!(KA>=Ae)&&IA[KA];)++KA;if((RA=KA<<1)-$>32&&Xo)return Xo.decode(aA.subarray($,RA));for(var pe="",Fe=0;!(Fe>=K/2);++Fe){var Ue=mA[$+2*Fe>>1];if(Ue==0)break;pe+=String.fromCharCode(Ue)}return pe},Qc=($,K,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var KA=K,Ae=(RA-=2)<2*$.length?RA/2:$.length,pe=0;pe>1]=Fe,K+=2}return mA[K>>1]=0,K-KA},sg=$=>2*$.length,yg=($,K)=>{for(var RA=0,KA="";!(RA>=K/4);){var Ae=tA[$+4*RA>>2];if(Ae==0)break;if(++RA,Ae>=65536){var pe=Ae-65536;KA+=String.fromCharCode(55296|pe>>10,56320|1023&pe)}else KA+=String.fromCharCode(Ae)}return KA},la=($,K,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var KA=K,Ae=KA+RA-4,pe=0;pe<$.length;++pe){var Fe=$.charCodeAt(pe);if(Fe>=55296&&Fe<=57343&&(Fe=65536+((1023&Fe)<<10)|1023&$.charCodeAt(++pe)),tA[K>>2]=Fe,(K+=4)+4>Ae)break}return tA[K>>2]=0,K-KA},Go=$=>{for(var K=0,RA=0;RA<$.length;++RA){var KA=$.charCodeAt(RA);KA>=55296&&KA<=57343&&++RA,K+=4}return K},Wr=($,K)=>{var RA=Ko[$];return RA===void 0&&jt(K+" has unknown type "+fg($)),RA},wo=($,K,RA)=>{var KA=[],Ae=$.toWireType(KA,RA);return KA.length&&(MA[K>>2]=cn.toHandle(KA)),Ae},Vc={},Hn=[],Js=Reflect.construct,Dg=[null,[],[]],pc=($,K)=>{var RA=Dg[$];K===0||K===10?(($===1?k:F)(og(RA,0)),RA.length=0):RA.push(K)};(()=>{for(var $=new Array(256),K=0;K<256;++K)$[K]=String.fromCharCode(K);to=$})(),uo=u.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},Ys=u.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign($s.prototype,{isAliasOf($){if(!(this instanceof $s)||!($ instanceof $s))return!1;var K=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var KA=$.$$.ptrType.registeredClass,Ae=$.$$.ptr;K.baseClass;)RA=K.upcast(RA),K=K.baseClass;for(;KA.baseClass;)Ae=KA.upcast(Ae),KA=KA.baseClass;return K===KA&&RA===Ae},clone(){if(this.$$.ptr||ce(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,K=No(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&&jt("Object already scheduled for deletion"),kt(this),it(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&&jt("Object already scheduled for deletion"),je.push(this),je.length===1&&qA&&qA(Mt),this.$$.deleteScheduled=!0,this}}),u.getInheritedInstanceCount=$t,u.getLiveInheritedInstances=Ge,u.flushPendingDeletes=Mt,u.setDelayFunction=Rt,Object.assign(jr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:Es,deleteObject($){$!==null&&$.delete()},fromWireType:oo}),vs=u.UnboundTypeError=(ks=Error,(ps=rn(Yc="UnboundTypeError",function($){this.name=Yc,this.message=$;var K=new Error($).stack;K!==void 0&&(this.stack=this.toString()+` +`+K.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(ks.prototype),ps.prototype.constructor=ps,ps.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},ps),Object.assign(pr.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($)}}),po.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),po.reserved=po.allocated.length,u.count_emval_handles=fl;var fn,Na={w:($,K,RA)=>{throw new _o($).init(K,RA),$},q:($,K,RA,KA,Ae)=>{},u:($,K,RA,KA)=>{Ms($,{name:K=ki(K),fromWireType:function(Ae){return!!Ae},toWireType:function(Ae,pe){return pe?RA:KA},argPackAdvance:8,readValueFromPointer:function(Ae){return this.fromWireType(aA[Ae])},destructorFunction:null})},y:($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut,St,Ot,li)=>{St=ki(St),pe=Jt(Ae,pe),Ue&&(Ue=Jt(Fe,Ue)),ut&&(ut=Jt(ot,ut)),li=Jt(Ot,li);var nt=(Ft=>{if(Ft===void 0)return"_unknown";var Ji=(Ft=Ft.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return Ji>=48&&Ji<=57?`_${Ft}`:Ft})(St);((Ft,Ji,qi)=>{u.hasOwnProperty(Ft)?(jt(`Cannot register public name '${Ft}' twice`),us(u,Ft,Ft),u.hasOwnProperty(qi)&&jt(`Cannot register multiple overloads of a function with the same number of arguments (${qi})!`),u[Ft].overloadTable[qi]=Ji):u[Ft]=Ji})(nt,function(){On(`Cannot construct ${St} due to unbound types`,[KA])}),bi([$,K,RA],KA?[KA]:[],function(Ft){var Ji,qi;Ft=Ft[0],qi=KA?(Ji=Ft.registeredClass).instancePrototype:$s.prototype;var Hs=rn(St,function(){if(Object.getPrototypeOf(this)!==Mi)throw new uo("Use 'new' to construct "+St);if(Wo.constructor_body===void 0)throw new uo(St+" has no accessible constructor");var xn=Wo.constructor_body[arguments.length];if(xn===void 0)throw new uo(`Tried to invoke ctor of ${St} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Wo.constructor_body).toString()}) parameters instead!`);return xn.apply(this,arguments)}),Mi=Object.create(qi,{constructor:{value:Hs}});Hs.prototype=Mi;var Wo=new an(St,Hs,Mi,li,Ji,pe,Ue,ut);Wo.baseClass&&(Wo.baseClass.__derivedClasses===void 0&&(Wo.baseClass.__derivedClasses=[]),Wo.baseClass.__derivedClasses.push(Wo));var Sg=new jr(St,Wo,!0,!1,!1),or=new jr(St+"*",Wo,!1,!1,!1),fr=new jr(St+" const*",Wo,!1,!0,!1);return Xt[$]={pointerType:or,constPointerType:fr},((xn,yl,qs)=>{u.hasOwnProperty(xn)||io("Replacing nonexistant public symbol"),u[xn].overloadTable!==void 0&&qs!==void 0?u[xn].overloadTable[qs]=yl:(u[xn]=yl,u[xn].argCount=qs)})(nt,Hs),[Sg,or,fr]})},x:($,K,RA,KA,Ae,pe)=>{var Fe=Gn(K,RA);Ae=Jt(KA,Ae),bi([],[$],function(Ue){var ot=`constructor ${(Ue=Ue[0]).name}`;if(Ue.registeredClass.constructor_body===void 0&&(Ue.registeredClass.constructor_body=[]),Ue.registeredClass.constructor_body[K-1]!==void 0)throw new uo(`Cannot register multiple constructors with identical number of parameters (${K-1}) for class '${Ue.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Ue.registeredClass.constructor_body[K-1]=()=>{On(`Cannot construct ${Ue.name} due to unbound types`,Fe)},bi([],Fe,ut=>(ut.splice(1,0,null),Ue.registeredClass.constructor_body[K-1]=Qr(ot,ut,null,Ae,pe),[])),[]})},i:($,K,RA,KA,Ae,pe,Fe,Ue,ot)=>{var ut=Gn(RA,KA);K=(St=>{const Ot=(St=St.trim()).indexOf("(");return Ot!==-1?St.substr(0,Ot):St})(K=ki(K)),pe=Jt(Ae,pe),bi([],[$],function(St){var Ot=`${(St=St[0]).name}.${K}`;function li(){On(`Cannot call ${Ot} due to unbound types`,ut)}K.startsWith("@@")&&(K=Symbol[K.substring(2)]),Ue&&St.registeredClass.pureVirtualFunctions.push(K);var nt=St.registeredClass.instancePrototype,Ft=nt[K];return Ft===void 0||Ft.overloadTable===void 0&&Ft.className!==St.name&&Ft.argCount===RA-2?(li.argCount=RA-2,li.className=St.name,nt[K]=li):(us(nt,K,Ot),nt[K].overloadTable[RA-2]=li),bi([],ut,function(Ji){var qi=Qr(Ot,Ji,St,pe,Fe);return nt[K].overloadTable===void 0?(qi.argCount=RA-2,nt[K]=qi):nt[K].overloadTable[RA-2]=qi,[]}),[]})},k:($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut)=>{K=ki(K),Ae=Jt(KA,Ae),bi([],[$],function(St){var Ot=`${(St=St[0]).name}.${K}`,li={get(){On(`Cannot access ${Ot} due to unbound types`,[RA,Fe])},enumerable:!0,configurable:!0};return li.set=ot?()=>On(`Cannot access ${Ot} due to unbound types`,[RA,Fe]):nt=>jt(Ot+" is a read-only property"),Object.defineProperty(St.registeredClass.instancePrototype,K,li),bi([],ot?[RA,Fe]:[RA],function(nt){var Ft=nt[0],Ji={get(){var Hs=Pn(this,St,Ot+" getter");return Ft.fromWireType(Ae(pe,Hs))},enumerable:!0};if(ot){ot=Jt(Ue,ot);var qi=nt[1];Ji.set=function(Hs){var Mi=Pn(this,St,Ot+" setter"),Wo=[];ot(ut,Mi,qi.toWireType(Wo,Hs)),Vs(Wo)}}return Object.defineProperty(St.registeredClass.instancePrototype,K,Ji),[]}),[]})},t:($,K)=>{Ms($,{name:K=ki(K),fromWireType:RA=>{var KA=cn.toValue(RA);return gn(RA),KA},toWireType:(RA,KA)=>cn.toHandle(KA),argPackAdvance:8,readValueFromPointer:mr,destructorFunction:null})},p:($,K,RA)=>{Ms($,{name:K=ki(K),fromWireType:KA=>KA,toWireType:(KA,Ae)=>Ae,argPackAdvance:8,readValueFromPointer:Bu(K,RA),destructorFunction:null})},g:($,K,RA,KA,Ae)=>{K=ki(K);var pe=ot=>ot;if(KA===0){var Fe=32-8*RA;pe=ot=>ot<>>Fe}var Ue=K.includes("unsigned");Ms($,{name:K,fromWireType:pe,toWireType:Ue?function(ot,ut){return this.name,ut>>>0}:function(ot,ut){return this.name,ut},argPackAdvance:8,readValueFromPointer:ja(K,RA,KA!==0),destructorFunction:null})},a:($,K,RA)=>{var KA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][K];function Ae(pe){var Fe=MA[pe>>2],Ue=MA[pe+4>>2];return new KA(lA.buffer,Ue,Fe)}Ms($,{name:RA=ki(RA),fromWireType:Ae,argPackAdvance:8,readValueFromPointer:Ae},{ignoreDuplicateRegistrations:!0})},o:($,K)=>{var RA=(K=ki(K))==="std::string";Ms($,{name:K,fromWireType(KA){var Ae,pe=MA[KA>>2],Fe=KA+4;if(RA)for(var Ue=Fe,ot=0;ot<=pe;++ot){var ut=Fe+ot;if(ot==pe||aA[ut]==0){var St=LI(Ue,ut-Ue);Ae===void 0?Ae=St:(Ae+="\0",Ae+=St),Ue=ut+1}}else{var Ot=new Array(pe);for(ot=0;ot{for(var li=0,nt=0;nt=55296&&Ft<=57343?(li+=4,++nt):li+=3}return li})(Ae):Ae.length;var Ue=ms(4+pe+1),ot=Ue+4;if(MA[Ue>>2]=pe,RA&&Fe)((Ot,li,nt,Ft)=>{if(!(Ft>0))return 0;for(var Ji=nt,qi=nt+Ft-1,Hs=0;Hs=55296&&Mi<=57343&&(Mi=65536+((1023&Mi)<<10)|1023&Ot.charCodeAt(++Hs)),Mi<=127){if(nt>=qi)break;li[nt++]=Mi}else if(Mi<=2047){if(nt+1>=qi)break;li[nt++]=192|Mi>>6,li[nt++]=128|63&Mi}else if(Mi<=65535){if(nt+2>=qi)break;li[nt++]=224|Mi>>12,li[nt++]=128|Mi>>6&63,li[nt++]=128|63&Mi}else{if(nt+3>=qi)break;li[nt++]=240|Mi>>18,li[nt++]=128|Mi>>12&63,li[nt++]=128|Mi>>6&63,li[nt++]=128|63&Mi}}li[nt]=0})(Ae,aA,ot,pe+1);else if(Fe)for(var ut=0;ut255&&(yn(ot),jt("String has UTF-16 code units that do not fit in 8 bits")),aA[ot+ut]=St}else for(ut=0;ut{var KA,Ae,pe,Fe,Ue;RA=ki(RA),K===2?(KA=Zi,Ae=Qc,Fe=sg,pe=()=>IA,Ue=1):K===4&&(KA=yg,Ae=la,Fe=Go,pe=()=>MA,Ue=2),Ms($,{name:RA,fromWireType:ot=>{for(var ut,St=MA[ot>>2],Ot=pe(),li=ot+4,nt=0;nt<=St;++nt){var Ft=ot+4+nt*K;if(nt==St||Ot[Ft>>Ue]==0){var Ji=KA(li,Ft-li);ut===void 0?ut=Ji:(ut+="\0",ut+=Ji),li=Ft+K}}return yn(ot),ut},toWireType:(ot,ut)=>{typeof ut!="string"&&jt(`Cannot pass non-string to C++ string type ${RA}`);var St=Fe(ut),Ot=ms(4+St+K);return MA[Ot>>2]=St>>Ue,Ae(ut,Ot+4,St+K),ot!==null&&ot.push(yn,Ot),Ot},argPackAdvance:8,readValueFromPointer:mr,destructorFunction(ot){yn(ot)}})},v:($,K)=>{Ms($,{isVoid:!0,name:K=ki(K),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,KA)=>{}})},j:($,K,RA)=>($=cn.toValue($),K=Wr(K,"emval::as"),wo(K,RA,$)),e:($,K,RA,KA,Ae)=>{var pe,Fe;return($=Hn[$])(K=cn.toValue(K),K[RA=(Fe=Vc[pe=RA])===void 0?ki(pe):Fe],KA,Ae)},d:gn,f:($,K,RA)=>{var KA=((ut,St)=>{for(var Ot=new Array(ut),li=0;li>2],"parameter "+li);return Ot})($,K),Ae=KA.shift();$--;var pe,Fe,Ue=new Array($),ot=`methodCaller<(${KA.map(ut=>ut.name).join(", ")}) => ${Ae.name}>`;return pe=rn(ot,(ut,St,Ot,li)=>{for(var nt=0,Ft=0;Ft<$;++Ft)Ue[Ft]=KA[Ft].readValueFromPointer(li+nt),nt+=KA[Ft].argPackAdvance;var Ji=RA===1?Js(St,Ue):St.apply(ut,Ue);for(Ft=0;Ft<$;++Ft)KA[Ft].deleteObject&&KA[Ft].deleteObject(Ue[Ft]);return wo(Ae,Ot,Ji)}),Fe=Hn.length,Hn.push(pe),Fe},c:$=>{$>4&&(po.get($).refcount+=1)},b:$=>{var K=cn.toValue($);Vs(K),gn($)},h:($,K)=>{var RA=($=Wr($,"_emval_take_value")).readValueFromPointer(K);return cn.toHandle(RA)},m:()=>{It("")},s:($,K,RA)=>aA.copyWithin($,K,K+RA),r:$=>{aA.length,It("OOM")},n:($,K,RA,KA)=>{for(var Ae=0,pe=0;pe>2],Ue=MA[K+4>>2];K+=8;for(var ot=0;ot>2]=Ae,0}},In=function(){var $={a:Na};function K(RA,KA){var Ae,pe;return In=RA.exports,_=In.z,Ae=_.buffer,u.HEAP8=lA=new Int8Array(Ae),u.HEAP16=mA=new Int16Array(Ae),u.HEAPU8=aA=new Uint8Array(Ae),u.HEAPU16=IA=new Uint16Array(Ae),u.HEAP32=tA=new Int32Array(Ae),u.HEAPU32=MA=new Uint32Array(Ae),u.HEAPF32=PA=new Float32Array(Ae),u.HEAPF64=ge=new Float64Array(Ae),Pi=In.C,pe=In.A,Be.unshift(pe),function(){if(Dt--,u.monitorRunDependencies&&u.monitorRunDependencies(Dt),Dt==0&&qt){var Fe=qt;qt=null,Fe()}}(),In}if(Dt++,u.monitorRunDependencies&&u.monitorRunDependencies(Dt),u.instantiateWasm)try{return u.instantiateWasm($,K)}catch(RA){F(`Module.instantiateWasm callback failed with error: ${RA}`),l(RA)}return gi(0,re,$,function(RA){K(RA.instance)}).catch(l),{}}(),ms=$=>(ms=In.B)($),Ia=$=>(Ia=In.D)($),yn=$=>(yn=In.E)($),Ga=$=>(Ga=In.F)($);u.dynCall_jiji=($,K,RA,KA,Ae)=>(u.dynCall_jiji=In.G)($,K,RA,KA,Ae),u._vertexShaderSource=10688;function ya(){function $(){fn||(fn=!0,u.calledRun=!0,de||(Fi(Be),r(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),function(){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Ke(u.postRun.shift());Fi(ct)}()))}Dt>0||(function(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)mt(u.preRun.shift());Fi(Ve)}(),Dt>0||(u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),$()},1)):$()))}if(qt=function $(){fn||ya(),fn||(qt=$)},u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return ya(),i.ready}})(),orA=irA,im=typeof navigator>"u"?"":navigator.userAgent,Ps=t=>new RegExp(t,"i").test(im),hc=t=>{if(Ps(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=im.match(i);if(r&&r[1])return r[1]}return""},mY=t=>{if(Ps(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=im.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},Hz=/AppleWebKit\/([\d.]+)/i.exec(im);Hz&&parseFloat(Hz[1]);var U6=Ps("iPad"),F6=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&Ps("Macintosh"),O6=Ps("iPhone")&&!U6,srA=Ps("iPod"),P6=O6||U6||srA||F6,k3=Ps("Android"),nrA=function(){if(k3){const t=im.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}();k3&&Ps("webkit")&&nrA<2.3;var rrA=Ps("Firefox"),arA=hc("Firefox");mY("Firefox");var x6=Ps("Edge"),grA=hc("Edge"),Y6=Ps("Edg"),crA=hc("Edg");mY("Edg");var V6=Ps("SogouMobileBrowser"),lrA=hc("SogouMobileBrowser"),J6=Ps("MetaSr\\s"),IrA=hc("MetaSr\\s"),uv=Ps("TBS"),urA=hc("TBS"),H6=Ps("XWEB"),ErA=hc("XWEB");Ps("MSIE\\s8\\.0");var drA=Ps("MSIE\\/\\d+");(function(){if(drA){const t=/MSIE\s(\d+)\.\d/.exec(im);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(im)&&/rv:11.0/.test(im)&&(i=11),i}return NaN})();var CrA=Ps("(micromessenger|webbrowser)"),hrA=hc("MicroMessenger"),L3=!uv&&Ps("MQQBrowser")&&Ps("COVC"),U3=!uv&&Ps("MQQBrowser")&&!Ps("COVC"),qz=U3||L3?hc("MQQBrowser"):"",q6=!uv&&Ps(" QQBrowser"),BrA=hc(" QQBrowser"),K6=!uv&&Ps("QQBrowserLite"),QrA=hc("QQBrowserLite"),j6=!uv&&Ps("MQBHD"),prA=hc("MQBHD");Ps("Windows");!P6&&Ps("MAC OS X");!k3&&Ps("Linux");Ps("CrOS");Ps("MicroMessenger");Ps("UCBrowser");Ps("Electron");var W6=Ps("MiuiBrowser"),mrA=hc("MiuiBrowser"),z6=Ps("HuaweiBrowser");Ps("Huawei")||Ps("HUAWEI");Ps("Honor")||Ps("HONOR");var frA=hc("HuaweiBrowser"),Z6=Ps("SamsungBrowser"),yrA=hc("SamsungBrowser"),X6=Ps("HeyTapBrowser"),DrA=hc("HeyTapBrowser"),$6=Ps("VivoBrowser"),SrA=hc("VivoBrowser");Ps("OpenHarmony");hc("OpenHarmony");var MrA=()=>mY("Chrome"),Kz=Ps("CriOS"),A9=Ps("Chrome"),vrA=!x6&&!J6&&!V6&&!uv&&!H6&&!Y6&&!q6&&!W6&&!z6&&!Z6&&!X6&&!$6&&A9;Ps("HeadlessChrome");var RrA=MrA(),wrA=hc("Chrome");mY("Electron");var _rA=!A9&&!U3&&!L3&&!K6&&!j6&&Ps("Safari"),e9=hc("Version"),t9=(()=>{if(F6)return e9;if(P6){const t=im.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();Number(t9.split(".")[0]);(()=>{const t=Number(t9.split(".")[0]);return t===14||t===13})();TrA();function TrA(){const t=new Map([[rrA,["Firefox",arA]],[Y6,["Edg",crA]],[vrA,["Chrome",wrA]],[Kz,["ChiOS",hc("CriOS")]],[_rA&&!Kz,["Safari",e9]],[uv,["TBS",urA]],[H6,["XWEB",ErA]],[CrA&&O6,["WeChat",hrA]],[q6,["QQ(Win)",BrA]],[U3,["QQ(Mobile)",qz]],[L3,["QQ(Mobile X5)",qz]],[K6,["QQ(Mac)",QrA]],[j6,["QQ(iPad)",prA]],[W6,["MI",mrA]],[z6,["HW",frA]],[Z6,["Samsung",yrA]],[X6,["OPPO",DrA]],[$6,["VIVO",SrA]],[x6,["EDGE",grA]],[V6,["SogouMobile",lrA]],[J6,["Sogou",IrA]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}var Ec=1e-6,T_=typeof Float32Array<"u"?Float32Array:Array,i9={};function NrA(){var t=new T_(16);return T_!=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 GrA(t){var i=new T_(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 brA(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 krA(t,i,r,l,u,p,y,w,_,k,F,j,lA,aA,mA,IA){var tA=new T_(16);return tA[0]=t,tA[1]=i,tA[2]=r,tA[3]=l,tA[4]=u,tA[5]=p,tA[6]=y,tA[7]=w,tA[8]=_,tA[9]=k,tA[10]=F,tA[11]=j,tA[12]=lA,tA[13]=aA,tA[14]=mA,tA[15]=IA,tA}function LrA(t,i,r,l,u,p,y,w,_,k,F,j,lA,aA,mA,IA,tA){return t[0]=i,t[1]=r,t[2]=l,t[3]=u,t[4]=p,t[5]=y,t[6]=w,t[7]=_,t[8]=k,t[9]=F,t[10]=j,t[11]=lA,t[12]=aA,t[13]=mA,t[14]=IA,t[15]=tA,t}function o9(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 UrA(t,i){if(t===i){var r=i[1],l=i[2],u=i[3],p=i[6],y=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]=p,t[11]=i[14],t[12]=u,t[13]=y,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 FrA(t,i){var r=i[0],l=i[1],u=i[2],p=i[3],y=i[4],w=i[5],_=i[6],k=i[7],F=i[8],j=i[9],lA=i[10],aA=i[11],mA=i[12],IA=i[13],tA=i[14],MA=i[15],PA=r*w-l*y,ge=r*_-u*y,de=r*k-p*y,Ve=l*_-u*w,Be=l*k-p*w,ct=u*k-p*_,mt=F*IA-j*mA,Ke=F*tA-lA*mA,Dt=F*MA-aA*mA,qt=j*tA-lA*IA,It=j*MA-aA*IA,re=lA*MA-aA*tA,qe=PA*re-ge*It+de*qt+Ve*Dt-Be*Ke+ct*mt;return qe?(qe=1/qe,t[0]=(w*re-_*It+k*qt)*qe,t[1]=(u*It-l*re-p*qt)*qe,t[2]=(IA*ct-tA*Be+MA*Ve)*qe,t[3]=(lA*Be-j*ct-aA*Ve)*qe,t[4]=(_*Dt-y*re-k*Ke)*qe,t[5]=(r*re-u*Dt+p*Ke)*qe,t[6]=(tA*de-mA*ct-MA*ge)*qe,t[7]=(F*ct-lA*de+aA*ge)*qe,t[8]=(y*It-w*Dt+k*mt)*qe,t[9]=(l*Dt-r*It-p*mt)*qe,t[10]=(mA*Be-IA*de+MA*PA)*qe,t[11]=(j*de-F*Be-aA*PA)*qe,t[12]=(w*Ke-y*qt-_*mt)*qe,t[13]=(r*qt-l*Ke+u*mt)*qe,t[14]=(IA*ge-mA*Ve-tA*PA)*qe,t[15]=(F*Ve-j*ge+lA*PA)*qe,t):null}function OrA(t,i){var r=i[0],l=i[1],u=i[2],p=i[3],y=i[4],w=i[5],_=i[6],k=i[7],F=i[8],j=i[9],lA=i[10],aA=i[11],mA=i[12],IA=i[13],tA=i[14],MA=i[15],PA=r*w-l*y,ge=r*_-u*y,de=r*k-p*y,Ve=l*_-u*w,Be=l*k-p*w,ct=u*k-p*_,mt=F*IA-j*mA,Ke=F*tA-lA*mA,Dt=F*MA-aA*mA,qt=j*tA-lA*IA,It=j*MA-aA*IA,re=lA*MA-aA*tA;return t[0]=w*re-_*It+k*qt,t[1]=u*It-l*re-p*qt,t[2]=IA*ct-tA*Be+MA*Ve,t[3]=lA*Be-j*ct-aA*Ve,t[4]=_*Dt-y*re-k*Ke,t[5]=r*re-u*Dt+p*Ke,t[6]=tA*de-mA*ct-MA*ge,t[7]=F*ct-lA*de+aA*ge,t[8]=y*It-w*Dt+k*mt,t[9]=l*Dt-r*It-p*mt,t[10]=mA*Be-IA*de+MA*PA,t[11]=j*de-F*Be-aA*PA,t[12]=w*Ke-y*qt-_*mt,t[13]=r*qt-l*Ke+u*mt,t[14]=IA*ge-mA*Ve-tA*PA,t[15]=F*Ve-j*ge+lA*PA,t}function PrA(t){var i=t[0],r=t[1],l=t[2],u=t[3],p=t[4],y=t[5],w=t[6],_=t[7],k=t[8],F=t[9],j=t[10],lA=t[11],aA=t[12],mA=t[13],IA=t[14],tA=i*y-r*p,MA=i*w-l*p,PA=r*w-l*y,ge=k*mA-F*aA,de=k*IA-j*aA,Ve=F*IA-j*mA;return _*(i*Ve-r*de+l*ge)-u*(p*Ve-y*de+w*ge)+t[15]*(k*PA-F*MA+j*tA)-lA*(aA*PA-mA*MA+IA*tA)}function s9(t,i,r){var l=i[0],u=i[1],p=i[2],y=i[3],w=i[4],_=i[5],k=i[6],F=i[7],j=i[8],lA=i[9],aA=i[10],mA=i[11],IA=i[12],tA=i[13],MA=i[14],PA=i[15],ge=r[0],de=r[1],Ve=r[2],Be=r[3];return t[0]=ge*l+de*w+Ve*j+Be*IA,t[1]=ge*u+de*_+Ve*lA+Be*tA,t[2]=ge*p+de*k+Ve*aA+Be*MA,t[3]=ge*y+de*F+Ve*mA+Be*PA,ge=r[4],de=r[5],Ve=r[6],Be=r[7],t[4]=ge*l+de*w+Ve*j+Be*IA,t[5]=ge*u+de*_+Ve*lA+Be*tA,t[6]=ge*p+de*k+Ve*aA+Be*MA,t[7]=ge*y+de*F+Ve*mA+Be*PA,ge=r[8],de=r[9],Ve=r[10],Be=r[11],t[8]=ge*l+de*w+Ve*j+Be*IA,t[9]=ge*u+de*_+Ve*lA+Be*tA,t[10]=ge*p+de*k+Ve*aA+Be*MA,t[11]=ge*y+de*F+Ve*mA+Be*PA,ge=r[12],de=r[13],Ve=r[14],Be=r[15],t[12]=ge*l+de*w+Ve*j+Be*IA,t[13]=ge*u+de*_+Ve*lA+Be*tA,t[14]=ge*p+de*k+Ve*aA+Be*MA,t[15]=ge*y+de*F+Ve*mA+Be*PA,t}function xrA(t,i,r){var l,u,p,y,w,_,k,F,j,lA,aA,mA,IA=r[0],tA=r[1],MA=r[2];return i===t?(t[12]=i[0]*IA+i[4]*tA+i[8]*MA+i[12],t[13]=i[1]*IA+i[5]*tA+i[9]*MA+i[13],t[14]=i[2]*IA+i[6]*tA+i[10]*MA+i[14],t[15]=i[3]*IA+i[7]*tA+i[11]*MA+i[15]):(l=i[0],u=i[1],p=i[2],y=i[3],w=i[4],_=i[5],k=i[6],F=i[7],j=i[8],lA=i[9],aA=i[10],mA=i[11],t[0]=l,t[1]=u,t[2]=p,t[3]=y,t[4]=w,t[5]=_,t[6]=k,t[7]=F,t[8]=j,t[9]=lA,t[10]=aA,t[11]=mA,t[12]=l*IA+w*tA+j*MA+i[12],t[13]=u*IA+_*tA+lA*MA+i[13],t[14]=p*IA+k*tA+aA*MA+i[14],t[15]=y*IA+F*tA+mA*MA+i[15]),t}function YrA(t,i,r){var l=r[0],u=r[1],p=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]*u,t[5]=i[5]*u,t[6]=i[6]*u,t[7]=i[7]*u,t[8]=i[8]*p,t[9]=i[9]*p,t[10]=i[10]*p,t[11]=i[11]*p,t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],t}function VrA(t,i,r,l){var u,p,y,w,_,k,F,j,lA,aA,mA,IA,tA,MA,PA,ge,de,Ve,Be,ct,mt,Ke,Dt,qt,It=l[0],re=l[1],qe=l[2],ft=Math.sqrt(It*It+re*re+qe*qe);return ft0?(r[0]=2*(w*y+F*l+_*p-k*u)/j,r[1]=2*(_*y+F*u+k*l-w*p)/j,r[2]=2*(k*y+F*p+w*u-_*l)/j):(r[0]=2*(w*y+F*l+_*p-k*u),r[1]=2*(_*y+F*u+k*l-w*p),r[2]=2*(k*y+F*p+w*u-_*l)),n9(t,i,r),t}function AaA(t,i){return t[0]=i[12],t[1]=i[13],t[2]=i[14],t}function r9(t,i){var r=i[0],l=i[1],u=i[2],p=i[4],y=i[5],w=i[6],_=i[8],k=i[9],F=i[10];return t[0]=Math.sqrt(r*r+l*l+u*u),t[1]=Math.sqrt(p*p+y*y+w*w),t[2]=Math.sqrt(_*_+k*k+F*F),t}function eaA(t,i){var r=new T_(3);r9(r,i);var l=1/r[0],u=1/r[1],p=1/r[2],y=i[0]*l,w=i[1]*u,_=i[2]*p,k=i[4]*l,F=i[5]*u,j=i[6]*p,lA=i[8]*l,aA=i[9]*u,mA=i[10]*p,IA=y+F+mA,tA=0;return IA>0?(tA=2*Math.sqrt(IA+1),t[3]=.25*tA,t[0]=(j-aA)/tA,t[1]=(lA-_)/tA,t[2]=(w-k)/tA):y>F&&y>mA?(tA=2*Math.sqrt(1+y-F-mA),t[3]=(j-aA)/tA,t[0]=.25*tA,t[1]=(w+k)/tA,t[2]=(lA+_)/tA):F>mA?(tA=2*Math.sqrt(1+F-y-mA),t[3]=(lA-_)/tA,t[0]=(w+k)/tA,t[1]=.25*tA,t[2]=(j+aA)/tA):(tA=2*Math.sqrt(1+mA-y-F),t[3]=(w-k)/tA,t[0]=(lA+_)/tA,t[1]=(j+aA)/tA,t[2]=.25*tA),t}function taA(t,i,r,l){i[0]=l[12],i[1]=l[13],i[2]=l[14];var u=l[0],p=l[1],y=l[2],w=l[4],_=l[5],k=l[6],F=l[8],j=l[9],lA=l[10];r[0]=Math.sqrt(u*u+p*p+y*y),r[1]=Math.sqrt(w*w+_*_+k*k),r[2]=Math.sqrt(F*F+j*j+lA*lA);var aA=1/r[0],mA=1/r[1],IA=1/r[2],tA=u*aA,MA=p*mA,PA=y*IA,ge=w*aA,de=_*mA,Ve=k*IA,Be=F*aA,ct=j*mA,mt=lA*IA,Ke=tA+de+mt,Dt=0;return Ke>0?(Dt=2*Math.sqrt(Ke+1),t[3]=.25*Dt,t[0]=(Ve-ct)/Dt,t[1]=(Be-PA)/Dt,t[2]=(MA-ge)/Dt):tA>de&&tA>mt?(Dt=2*Math.sqrt(1+tA-de-mt),t[3]=(Ve-ct)/Dt,t[0]=.25*Dt,t[1]=(MA+ge)/Dt,t[2]=(Be+PA)/Dt):de>mt?(Dt=2*Math.sqrt(1+de-tA-mt),t[3]=(Be-PA)/Dt,t[0]=(MA+ge)/Dt,t[1]=.25*Dt,t[2]=(Ve+ct)/Dt):(Dt=2*Math.sqrt(1+mt-tA-de),t[3]=(MA-ge)/Dt,t[0]=(Be+PA)/Dt,t[1]=(Ve+ct)/Dt,t[2]=.25*Dt),t}function iaA(t,i,r,l){var u=i[0],p=i[1],y=i[2],w=i[3],_=u+u,k=p+p,F=y+y,j=u*_,lA=u*k,aA=u*F,mA=p*k,IA=p*F,tA=y*F,MA=w*_,PA=w*k,ge=w*F,de=l[0],Ve=l[1],Be=l[2];return t[0]=(1-(mA+tA))*de,t[1]=(lA+ge)*de,t[2]=(aA-PA)*de,t[3]=0,t[4]=(lA-ge)*Ve,t[5]=(1-(j+tA))*Ve,t[6]=(IA+MA)*Ve,t[7]=0,t[8]=(aA+PA)*Be,t[9]=(IA-MA)*Be,t[10]=(1-(j+mA))*Be,t[11]=0,t[12]=r[0],t[13]=r[1],t[14]=r[2],t[15]=1,t}function oaA(t,i,r,l,u){var p=i[0],y=i[1],w=i[2],_=i[3],k=p+p,F=y+y,j=w+w,lA=p*k,aA=p*F,mA=p*j,IA=y*F,tA=y*j,MA=w*j,PA=_*k,ge=_*F,de=_*j,Ve=l[0],Be=l[1],ct=l[2],mt=u[0],Ke=u[1],Dt=u[2],qt=(1-(IA+MA))*Ve,It=(aA+de)*Ve,re=(mA-ge)*Ve,qe=(aA-de)*Be,ft=(1-(lA+MA))*Be,si=(tA+PA)*Be,Vt=(mA+ge)*ct,gi=(tA-PA)*ct,Fi=(1-(lA+IA))*ct;return t[0]=qt,t[1]=It,t[2]=re,t[3]=0,t[4]=qe,t[5]=ft,t[6]=si,t[7]=0,t[8]=Vt,t[9]=gi,t[10]=Fi,t[11]=0,t[12]=r[0]+mt-(qt*mt+qe*Ke+Vt*Dt),t[13]=r[1]+Ke-(It*mt+ft*Ke+gi*Dt),t[14]=r[2]+Dt-(re*mt+si*Ke+Fi*Dt),t[15]=1,t}function saA(t,i){var r=i[0],l=i[1],u=i[2],p=i[3],y=r+r,w=l+l,_=u+u,k=r*y,F=l*y,j=l*w,lA=u*y,aA=u*w,mA=u*_,IA=p*y,tA=p*w,MA=p*_;return t[0]=1-j-mA,t[1]=F+MA,t[2]=lA-tA,t[3]=0,t[4]=F-MA,t[5]=1-k-mA,t[6]=aA+IA,t[7]=0,t[8]=lA+tA,t[9]=aA-IA,t[10]=1-k-j,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t}function naA(t,i,r,l,u,p,y){var w=1/(r-i),_=1/(u-l),k=1/(p-y);return t[0]=2*p*w,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=2*p*_,t[6]=0,t[7]=0,t[8]=(r+i)*w,t[9]=(u+l)*_,t[10]=(y+p)*k,t[11]=-1,t[12]=0,t[13]=0,t[14]=y*p*2*k,t[15]=0,t}function a9(t,i,r,l,u){var p=1/Math.tan(i/2);if(t[0]=p/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=p,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,u!=null&&u!==1/0){var y=1/(l-u);t[10]=(u+l)*y,t[14]=2*u*l*y}else t[10]=-1,t[14]=-2*l;return t}ZnA(i9,{add:()=>CaA,adjoint:()=>OrA,clone:()=>GrA,copy:()=>brA,create:()=>NrA,decompose:()=>taA,determinant:()=>PrA,equals:()=>paA,exactEquals:()=>QaA,frob:()=>daA,fromQuat:()=>saA,fromQuat2:()=>$rA,fromRotation:()=>WrA,fromRotationTranslation:()=>n9,fromRotationTranslationScale:()=>iaA,fromRotationTranslationScaleOrigin:()=>oaA,fromScaling:()=>jrA,fromTranslation:()=>KrA,fromValues:()=>krA,fromXRotation:()=>zrA,fromYRotation:()=>ZrA,fromZRotation:()=>XrA,frustum:()=>naA,getRotation:()=>eaA,getScaling:()=>r9,getTranslation:()=>AaA,identity:()=>o9,invert:()=>FrA,lookAt:()=>IaA,mul:()=>maA,multiply:()=>s9,multiplyScalar:()=>haA,multiplyScalarAndAdd:()=>BaA,ortho:()=>caA,orthoNO:()=>g9,orthoZO:()=>laA,perspective:()=>raA,perspectiveFromFieldOfView:()=>gaA,perspectiveNO:()=>a9,perspectiveZO:()=>aaA,rotate:()=>VrA,rotateX:()=>JrA,rotateY:()=>HrA,rotateZ:()=>qrA,scale:()=>YrA,set:()=>LrA,str:()=>EaA,sub:()=>faA,subtract:()=>c9,targetTo:()=>uaA,translate:()=>xrA,transpose:()=>UrA});var raA=a9;function aaA(t,i,r,l,u){var p=1/Math.tan(i/2);if(t[0]=p/r,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=p,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=-1,t[12]=0,t[13]=0,t[15]=0,u!=null&&u!==1/0){var y=1/(l-u);t[10]=u*y,t[14]=u*l*y}else t[10]=-1,t[14]=-l;return t}function gaA(t,i,r,l){var u=Math.tan(i.upDegrees*Math.PI/180),p=Math.tan(i.downDegrees*Math.PI/180),y=Math.tan(i.leftDegrees*Math.PI/180),w=Math.tan(i.rightDegrees*Math.PI/180),_=2/(y+w),k=2/(u+p);return t[0]=_,t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[5]=k,t[6]=0,t[7]=0,t[8]=-(y-w)*_*.5,t[9]=(u-p)*k*.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 g9(t,i,r,l,u,p,y){var w=1/(i-r),_=1/(l-u),k=1/(p-y);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*k,t[11]=0,t[12]=(i+r)*w,t[13]=(u+l)*_,t[14]=(y+p)*k,t[15]=1,t}var caA=g9;function laA(t,i,r,l,u,p,y){var w=1/(i-r),_=1/(l-u),k=1/(p-y);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]=k,t[11]=0,t[12]=(i+r)*w,t[13]=(u+l)*_,t[14]=p*k,t[15]=1,t}function IaA(t,i,r,l){var u,p,y,w,_,k,F,j,lA,aA,mA=i[0],IA=i[1],tA=i[2],MA=l[0],PA=l[1],ge=l[2],de=r[0],Ve=r[1],Be=r[2];return Math.abs(mA-de)0&&(F*=aA=1/Math.sqrt(aA),j*=aA,lA*=aA);var mA=_*lA-k*j,IA=k*F-w*lA,tA=w*j-_*F;return(aA=mA*mA+IA*IA+tA*tA)>0&&(mA*=aA=1/Math.sqrt(aA),IA*=aA,tA*=aA),t[0]=mA,t[1]=IA,t[2]=tA,t[3]=0,t[4]=j*tA-lA*IA,t[5]=lA*mA-F*tA,t[6]=F*IA-j*mA,t[7]=0,t[8]=F,t[9]=j,t[10]=lA,t[11]=0,t[12]=u,t[13]=p,t[14]=y,t[15]=1,t}function EaA(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 daA(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 CaA(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 c9(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 haA(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 BaA(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 QaA(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 paA(t,i){var r=t[0],l=t[1],u=t[2],p=t[3],y=t[4],w=t[5],_=t[6],k=t[7],F=t[8],j=t[9],lA=t[10],aA=t[11],mA=t[12],IA=t[13],tA=t[14],MA=t[15],PA=i[0],ge=i[1],de=i[2],Ve=i[3],Be=i[4],ct=i[5],mt=i[6],Ke=i[7],Dt=i[8],qt=i[9],It=i[10],re=i[11],qe=i[12],ft=i[13],si=i[14],Vt=i[15];return Math.abs(r-PA)<=Ec*Math.max(1,Math.abs(r),Math.abs(PA))&&Math.abs(l-ge)<=Ec*Math.max(1,Math.abs(l),Math.abs(ge))&&Math.abs(u-de)<=Ec*Math.max(1,Math.abs(u),Math.abs(de))&&Math.abs(p-Ve)<=Ec*Math.max(1,Math.abs(p),Math.abs(Ve))&&Math.abs(y-Be)<=Ec*Math.max(1,Math.abs(y),Math.abs(Be))&&Math.abs(w-ct)<=Ec*Math.max(1,Math.abs(w),Math.abs(ct))&&Math.abs(_-mt)<=Ec*Math.max(1,Math.abs(_),Math.abs(mt))&&Math.abs(k-Ke)<=Ec*Math.max(1,Math.abs(k),Math.abs(Ke))&&Math.abs(F-Dt)<=Ec*Math.max(1,Math.abs(F),Math.abs(Dt))&&Math.abs(j-qt)<=Ec*Math.max(1,Math.abs(j),Math.abs(qt))&&Math.abs(lA-It)<=Ec*Math.max(1,Math.abs(lA),Math.abs(It))&&Math.abs(aA-re)<=Ec*Math.max(1,Math.abs(aA),Math.abs(re))&&Math.abs(mA-qe)<=Ec*Math.max(1,Math.abs(mA),Math.abs(qe))&&Math.abs(IA-ft)<=Ec*Math.max(1,Math.abs(IA),Math.abs(ft))&&Math.abs(tA-si)<=Ec*Math.max(1,Math.abs(tA),Math.abs(si))&&Math.abs(MA-Vt)<=Ec*Math.max(1,Math.abs(MA),Math.abs(Vt))}var maA=s9,faA=c9,qk=`#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; +}`,F3=t=>`precision highp float; +uniform sampler2D mask;in vec2 v_texCoord; +out vec4 outColor; +void main() {${t}}`,yaA=`#version 300 es +uniform sampler2D lastMask; +${F3(`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; + const float threshold = 0.3; + highp float blendedMask = diff < threshold + ? previous * (1.0 - smoothFactor) + current * smoothFactor + : current; + outColor = vec4(blendedMask,0.0,0.0, 1.0);`)} +`,DaA=`#version 300 es +${F3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); + float size = 3.0; + int sizeDb = int(size*size); + float samples[9]; + int idx = 0; + float side = (size - 1.0) / 2.0; + for (float x = -side; x <= side; x += 1.0) { + for (float y = -side; y <= side; y += 1.0) { + vec2 sampleCoord = v_texCoord + vec2(x, y) * o; + int index = int((x + 1.0) * size + (y + 1.0)); + samples[index] = texture(mask, sampleCoord).r; + } + } + for (int i = 0; i < sizeDb - 1; i++) { + for (int j = 0; j < sizeDb - 1 - i; j++) { + if (samples[j] > samples[j + 1]) { + float temp = samples[j]; + samples[j] = samples[j + 1]; + samples[j + 1] = temp; + } + } + } + float endR=samples[sizeDb/2]>0.5?1.0:0.0; + outColor = vec4(endR, 0.0, 0.0, 1.0);`)} +`,SaA=`#version 300 es +${F3(` vec2 o = 1.0 / vec2(textureSize(mask, 0)); + float size = 3.0; + float side = (size - 1.0) / 2.0; + float stronglyEroded = 1.0; + for (float x = -side; x <= side; x += 1.0) { + for (float y = -side; y <= side; y += 1.0) { + vec2 sampleCoord = v_texCoord + vec2(x, y) * o; + stronglyEroded = min(stronglyEroded, texture(mask, sampleCoord).r); + } + } + outColor = vec4(stronglyEroded, 0.0, 0.0, 1.0);`)} +`,MaA=`#version 300 es +precision highp float; +uniform sampler2D mask; +uniform sampler2D originalMask; +uniform sampler2D maskEdge; +in vec2 v_texCoord; +out vec4 outColor; +float u_highThreshold = 0.9; +float u_smoothSigma = 2.0; +float u_featherRadius = 4.0; +float balancedTransition(float value) { + return value * value * (3.0 - 2.0 * value); +} +float hybridBlur(sampler2D tex, vec2 uv, vec2 texelSize, float edgeIntensity, float sigma) { + float edgeWeight = smoothstep(u_highThreshold * 0.8, u_highThreshold, edgeIntensity); + if (edgeWeight < u_highThreshold * 0.8) { + return texture(tex, uv).r; + } + float adaptiveRadius = mix(u_featherRadius * 0.5, u_featherRadius * 1.5, edgeWeight); + int kernelSize = int(ceil(2.5 * sigma)); + float sum = 0.0; + float weightSum = 0.0; + for (int i = -kernelSize; i <= kernelSize; i++) { + for (int j = -kernelSize; j <= kernelSize; j++) { + vec2 offset = vec2(float(i), float(j)) * texelSize * adaptiveRadius; + vec2 sampleUV = uv + offset; + float sampleValue = texture(originalMask, sampleUV).r; + float dist = length(vec2(i, j)) / float(kernelSize); + float weight = 1.0 - balancedTransition(dist); + sum += sampleValue * weight; + weightSum += weight; + } + } + return sum / weightSum; +} +void main() { + vec2 texelSize = 1.0 / vec2(textureSize(mask, 0)); + float edge = texture(maskEdge, v_texCoord).r; + float centerValue = texture(mask, v_texCoord).r; + float smoothedValue = hybridBlur(mask, v_texCoord, texelSize, edge, u_smoothSigma); + float finalAlpha; + if (edge == 1.0) { + finalAlpha = smoothedValue; + } else if (centerValue > 0.70) { + finalAlpha = 1.0; + } else if (centerValue < 0.30) { + finalAlpha = 0.0; + } else { + float t = balancedTransition((centerValue - 0.30)); + finalAlpha = mix(centerValue, smoothedValue, 1.0 - t * 0.95); + } + outColor = vec4(finalAlpha, 0.0, 0.0, 1.0); +} +`,vaA=`#version 300 es +precision highp float; +uniform sampler2D mask; +in vec2 v_texCoord; +out vec4 outColor; +float u_gradientScale = 0.25; +const float SOBEL_KERNEL_X[9] = float[9]( + -1.0, 0.0, 1.0, + -2.0, 0.0, 2.0, + -1.0, 0.0, 1.0 +); +const float SOBEL_KERNEL_Y[9] = float[9]( + -1.0, -2.0, -1.0, + 0.0, 0.0, 0.0, + 1.0, 2.0, 1.0 +); +float nonMaxSuppression(float gradient, vec2 uv, vec2 texelSize, float angle) { + vec2 dir = vec2(cos(angle), sin(angle)); + vec2 offset1 = dir * texelSize; + vec2 offset2 = -dir * texelSize; + float n1 = texture(mask, uv + offset1).r; + float n2 = texture(mask, uv + offset2).r; + return (gradient >= n1 && gradient >= n2) ? gradient : 0.0; +} +void main() { + vec2 o = 1.0 / vec2(textureSize(mask, 0)); + float gx = 0.0, gy = 0.0; + for (int i = -1; i <= 1; i++) { + for (int j = -1; j <= 1; j++) { + vec2 offset = vec2(float(i), float(j)) * o; + float maskValue = texture(mask, v_texCoord + offset).r; + int idx = (i+1)*3 + (j+1); + gx += maskValue * SOBEL_KERNEL_X[idx]; + gy += maskValue * SOBEL_KERNEL_Y[idx]; + } + } + float gradient = sqrt(gx*gx + gy*gy) * u_gradientScale; + float angle = atan(gy, gx); + float nmsEdge = nonMaxSuppression(gradient, v_texCoord, o, angle); + float edge = nmsEdge > 0.0 ? 1.0 : 0.0; + outColor = vec4(edge, 0.0, 0.0, 1.0); +} +`,RaA=class{constructor(){Jg(this,"gl"),Jg(this,"positionBuffer"),Jg(this,"texCoordBuffer"),Jg(this,"ratio"),Jg(this,"_tdProgram"),Jg(this,"_kcProgram"),Jg(this,"_mdProgram"),Jg(this,"_edgeProgram"),Jg(this,"_borderProgram"),Jg(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(qk,yaA,["mask","lastMask"]),this._mdProgram=this.createProgram(qk,DaA,["mask"]),this._kcProgram=this.createProgram(qk,SaA,["mask"]),this._borderProgram=this.createProgram(qk,MaA,["mask","maskEdge","originalMask"]),this._edgeProgram=this.createProgram(qk,vaA,["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,u=this.createShader(l.FRAGMENT_SHADER,i),p=this.createShader(l.VERTEX_SHADER,t),y=l.createProgram();if(l.attachShader(y,p),l.attachShader(y,u),l.linkProgram(y),!l.getProgramParameter(y,l.LINK_STATUS))throw new Error(`${l.getProgramInfoLog(y)}`);return l.useProgram(y),this.setAttributes(this.positionBuffer,this.texCoordBuffer),r.forEach((w,_)=>{l.uniform1i(l.getUniformLocation(y,w),1+_)}),y}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:u}=this;let p,y;u.useProgram(t),this.ratio===16/9?(p=640,y=360):(p=640,y=480);const w=u.createTexture();u.activeTexture(u.TEXTURE0),u.bindTexture(u.TEXTURE_2D,w),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,u.LINEAR),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,u.LINEAR),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),u.pixelStorei(u.PACK_ALIGNMENT,1),u.pixelStorei(u.UNPACK_ALIGNMENT,1),u.texImage2D(u.TEXTURE_2D,0,u.RGBA,p,y,0,u.RGBA,u.UNSIGNED_BYTE,null);const _=this.createFramebuffer(w);return i.forEach((k,F)=>{k&&(u.activeTexture(u.TEXTURE1+F),u.bindTexture(u.TEXTURE_2D,k||null))}),this.setAttributes(this.positionBuffer,this.texCoordBuffer),u.viewport(0,0,p,y),u.drawArrays(u.TRIANGLE_STRIP,0,4),r&&i.forEach((k,F)=>{k&&l!==F&&u.deleteTexture(k)}),u.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)}},waA=new RaA,_aA=(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))(_aA||{}),TaA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},e_=570703,jK=0,l9=class I9{constructor(i){this.core=i,Jg(this,"seq"),Jg(this,"_core"),Jg(this,"log"),Jg(this,"preLoadPromise"),Jg(this,"startResolve"),Jg(this,"startReject"),Jg(this,"mediaPipeSolutions"),Jg(this,"assetsPath"),Jg(this,"currentType"),Jg(this,"onAbort"),Jg(this,"isAborted",!1),jK+=1,this.seq=jK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${jK}`}),this.log.info("created"),i.assetsPath&&(this.preLoadPromise=this.preload(i.assetsPath))}static isSupported(){if(RrA<90)return!1;const i=document.createElement("canvas").getContext("webgl2",TaA);return!!(i&&i instanceof WebGL2RenderingContext)}async preload(i){try{this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await orA());const r=l=>{var u;this.core.kvStatManager.addEnum({key:e_,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(),(u=this.onAbort)==null||u.call(this,l)};this._core.room.videoManager.initVirtualBackground(r,i9,waA),await this._core.initVisionTaskRegistry(i,["ImageSegmenter"])}catch(r){const{RtcError:l,ErrorCode:u}=this._core.errorModule;throw new l({code:u.INVALID_OPERATION,message:`VirtualBackground preload error, please redeploy the assets of the npm package. detail: ${r}`})}}getName(){return I9.Name}getAlias(){return"vb"}getValidateRule(i){switch(i){case"start":return ArA(this._core);case"update":return erA(this._core);case"stop":return trA(this._core)}}getGroup(){return"vb"}getKVTypeValue(i=!1,r=!1,l="NONE"){let u=0;switch(this.currentType){case"blur":u|=0;break;case"image":u|=1;break;case"color":u|=2}switch(i&&(u|=256),r&&(u|=512),l){case"ABORT_IN_INFERENCE":u|=4096;break;case"ABORT_IN_VIDEO_MANAGER":u|=8192;break;case"OTHER":u|=61440}return u}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:u=3,onAbort:p}=i;this.currentType=r,this.onAbort=p,r==="color"&&typeof i.color=="string"&&(i.color=this.hexToRgb(i.color));const{auth:y}=await XnA({sdkAppId:i.sdkAppId,userId:i.userId,userSig:i.userSig,core:this._core}),{RtcError:w,ErrorCodeDictionary:_,ErrorCode:k}=this._core.errorModule;if(!y){const F=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:F}})}if(!this.preLoadPromise){if(!this._core.assetsPath)throw new w({code:k.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:u,enableFaceCentering:i.enableFaceCentering,enableEffectOptimization:i.enableEffectOptimization,color:i.color,onAbort:F=>{var j;this.core.kvStatManager.addEnum({key:e_,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,F)}}).then(()=>{this.core.kvStatManager.addEnum({key:e_,value:this.getKVTypeValue(!1,this.isAborted,"NONE")})}).catch(F=>{throw this.core.kvStatManager.addEnum({key:e_,value:this.getKVTypeValue(!0,this.isAborted,"OTHER")}),F})}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:e_,value:this.getKVTypeValue(!1,!1,"NONE")})}).catch(()=>{this.core.kvStatManager.addEnum({key:e_,value:this.getKVTypeValue(!0,!1,"OTHER")})})}async stop(){return this.core.room.videoManager.setVirtualBackground()}};Jg(l9,"Name","VirtualBackground");var u9=l9,NaA=u9;const GaA=Object.freeze(Object.defineProperty({__proto__:null,VirtualBackground:u9,default:NaA},Symbol.toStringTag,{value:"Module"})),baA=ZL(GaA);var kaA=Object.defineProperty,LaA=(t,i,r)=>i in t?kaA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,sL=(t,i,r)=>LaA(t,typeof i!="symbol"?i+"":i,r);function UaA(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,u){const{RtcError:p,ErrorCode:y,ErrorCodeDictionary:w}=t.errorModule;if(t.utils.isOverseaSdkAppId(i.sdkAppId))throw new p({code:y.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 FaA(t){return{name:"StopBasicBeautyOptions",required:!1}}var OaA=(()=>{var t=typeof document<"u"&&document.currentScript?document.currentScript.src:void 0;return function(i={}){var r,l,u=i;u.ready=new Promise(($,K)=>{r=$,l=K});var p=Object.assign({},u),y="";typeof document<"u"&&document.currentScript&&(y=document.currentScript.src),t&&(y=t),y=y.indexOf("blob:")!==0?y.substr(0,y.replace(/[?#].*/,"").lastIndexOf("/")+1):"";var w,_,k=u.print||console.log.bind(console),F=u.printErr||console.error.bind(console);function j($){if(si($))return function(K){for(var RA=atob(K),KA=new Uint8Array(RA.length),Ae=0;Ae$.startsWith(ft);function Vt($){return Promise.resolve().then(()=>function(K){if(K==re&&w)return new Uint8Array(w);var RA=j(K);if(RA)return RA;throw"both async and sync fetching of the wasm failed"}($))}function gi($,K,RA,KA){return function(Ae,pe,Fe){return Vt(Ae).then(Ue=>WebAssembly.instantiate(Ue,pe)).then(Ue=>Ue).then(Fe,Ue=>{F(`failed to asynchronously prepare wasm: ${Ue}`),It(Ue)})}(K,RA,KA)}si(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/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=")||(qe=re,re=u.locateFile?u.locateFile(qe,y):y+qe);var Fi=$=>{for(;$.length>0;)$.shift()(u)};u.noExitRuntime;function _o($){this.excPtr=$,this.ptr=$-24,this.set_type=function(K){MA[this.ptr+4>>2]=K},this.get_type=function(){return MA[this.ptr+4>>2]},this.set_destructor=function(K){MA[this.ptr+8>>2]=K},this.get_destructor=function(){return MA[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,RA){this.set_adjusted_ptr(0),this.set_type(K),this.set_destructor(RA)},this.set_adjusted_ptr=function(K){MA[this.ptr+16>>2]=K},this.get_adjusted_ptr=function(){return MA[this.ptr+16>>2]},this.get_exception_ptr=function(){if(Ga(this.get_type()))return MA[this.excPtr>>2];var K=this.get_adjusted_ptr();return K!==0?K:this.excPtr}}var to,uo,Ys,ki=$=>{for(var K="",RA=$;aA[RA];)K+=to[aA[RA++]];return K},os={},Ko={},$i={},jt=$=>{throw new uo($)},io=$=>{throw new Ys($)},bi=($,K,RA)=>{function KA(Ue){var ot=RA(Ue);ot.length!==$.length&&io("Mismatched type converter count");for(var ut=0;ut<$.length;++ut)Ms($[ut],ot[ut])}$.forEach(function(Ue){$i[Ue]=K});var Ae=new Array(K.length),pe=[],Fe=0;K.forEach((Ue,ot)=>{Ko.hasOwnProperty(Ue)?Ae[ot]=Ko[Ue]:(pe.push(Ue),os.hasOwnProperty(Ue)||(os[Ue]=[]),os[Ue].push(()=>{Ae[ot]=Ko[Ue],++Fe===pe.length&&KA(Ae)}))}),pe.length===0&&KA(Ae)};function Ms($,K,RA={}){if(!("argPackAdvance"in K))throw new TypeError("registerType registeredInstance requires argPackAdvance");return function(KA,Ae,pe={}){var Fe=Ae.name;if(KA||jt(`type "${Fe}" must have a positive integer typeid pointer`),Ko.hasOwnProperty(KA)){if(pe.ignoreDuplicateRegistrations)return;jt(`Cannot register type '${Fe}' twice`)}if(Ko[KA]=Ae,delete $i[KA],os.hasOwnProperty(KA)){var Ue=os[KA];delete os[KA],Ue.forEach(ot=>ot())}}($,K,RA)}var qA,ce=$=>{jt($.$$.ptrType.registeredClass.name+" instance already deleted")},Pe=!1,kt=$=>{},it=$=>{$.count.value-=1,$.count.value===0&&(K=>{K.smartPtr?K.smartPtrType.rawDestructor(K.smartPtr):K.ptrType.registeredClass.rawDestructor(K.ptr)})($)},gt=($,K,RA)=>{if(K===RA)return $;if(RA.baseClass===void 0)return null;var KA=gt($,K,RA.baseClass);return KA===null?null:RA.downcast(KA)},Xt={},$t=()=>Object.keys(Oi).length,Ge=()=>{var $=[];for(var K in Oi)Oi.hasOwnProperty(K)&&$.push(Oi[K]);return $},je=[],Mt=()=>{for(;je.length;){var $=je.pop();$.$$.deleteScheduled=!1,$.delete()}},Rt=$=>{qA=$,je.length&&qA&&qA(Mt)},Oi={},Qo=($,K)=>(K=((RA,KA)=>{for(KA===void 0&&jt("ptr should not be undefined");RA.baseClass;)KA=RA.upcast(KA),RA=RA.baseClass;return KA})($,K),Oi[K]),To=($,K)=>(K.ptrType&&K.ptr||io("makeClassHandle requires ptr and ptrType"),!!K.smartPtrType!=!!K.smartPtr&&io("Both smartPtrType and smartPtr must be specified"),K.count={value:1},No(Object.create($,{$$:{value:K}})));function oo($){var K=this.getPointee($);if(!K)return this.destructor($),null;var RA=Qo(this.registeredClass,K);if(RA!==void 0){if(RA.$$.count.value===0)return RA.$$.ptr=K,RA.$$.smartPtr=$,RA.clone();var KA=RA.clone();return this.destructor($),KA}function Ae(){return this.isSmartPointer?To(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:K,smartPtrType:this,smartPtr:$}):To(this.registeredClass.instancePrototype,{ptrType:this,ptr:$})}var pe,Fe=this.registeredClass.getActualType(K),Ue=Xt[Fe];if(!Ue)return Ae.call(this);pe=this.isConst?Ue.constPointerType:Ue.pointerType;var ot=gt(K,this.registeredClass,pe.registeredClass);return ot===null?Ae.call(this):this.isSmartPointer?To(pe.registeredClass.instancePrototype,{ptrType:pe,ptr:ot,smartPtrType:this,smartPtr:$}):To(pe.registeredClass.instancePrototype,{ptrType:pe,ptr:ot})}var No=$=>typeof FinalizationRegistry>"u"?(No=K=>K,$):(Pe=new FinalizationRegistry(K=>{it(K.$$)}),kt=K=>Pe.unregister(K),(No=K=>{var RA=K.$$;if(RA.smartPtr){var KA={$$:RA};Pe.register(K,KA,K)}return K})($));function $s(){}var rn=($,K)=>Object.defineProperty(K,"name",{value:$}),us=($,K,RA)=>{if($[K].overloadTable===void 0){var KA=$[K];$[K]=function(){return $[K].overloadTable.hasOwnProperty(arguments.length)||jt(`Function '${RA}' 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[KA.argCount]=KA}};function an($,K,RA,KA,Ae,pe,Fe,Ue){this.name=$,this.constructor=K,this.instancePrototype=RA,this.rawDestructor=KA,this.baseClass=Ae,this.getActualType=pe,this.upcast=Fe,this.downcast=Ue,this.pureVirtualFunctions=[]}var yo=($,K,RA)=>{for(;K!==RA;)K.upcast||jt(`Expected null or instance of ${RA.name}, got an instance of ${K.name}`),$=K.upcast($),K=K.baseClass;return $};function pA($,K){if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`);var RA=K.$$.ptrType.registeredClass;return yo(K.$$.ptr,RA,this.registeredClass)}function Jn($,K){var RA;if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),this.isSmartPointer?(RA=this.rawConstructor(),$!==null&&$.push(this.rawDestructor,RA),RA):0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`),!this.isConst&&K.$$.ptrType.isConst&&jt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);var KA=K.$$.ptrType.registeredClass;if(RA=yo(K.$$.ptr,KA,this.registeredClass),this.isSmartPointer)switch(K.$$.smartPtr===void 0&&jt("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:K.$$.smartPtrType===this?RA=K.$$.smartPtr:jt(`Cannot convert argument of type ${K.$$.smartPtrType?K.$$.smartPtrType.name:K.$$.ptrType.name} to parameter type ${this.name}`);break;case 1:RA=K.$$.smartPtr;break;case 2:if(K.$$.smartPtrType===this)RA=K.$$.smartPtr;else{var Ae=K.clone();RA=this.rawShare(RA,cn.toHandle(()=>Ae.delete())),$!==null&&$.push(this.rawDestructor,RA)}break;default:jt("Unsupporting sharing policy")}return RA}function Br($,K){if(K===null)return this.isReference&&jt(`null is not a valid ${this.name}`),0;K.$$||jt(`Cannot pass "${rs(K)}" as a ${this.name}`),K.$$.ptr||jt(`Cannot pass deleted object as a pointer of type ${this.name}`),K.$$.ptrType.isConst&&jt(`Cannot convert argument of type ${K.$$.ptrType.name} to parameter type ${this.name}`);var RA=K.$$.ptrType.registeredClass;return yo(K.$$.ptr,RA,this.registeredClass)}function Es($){return this.fromWireType(MA[$>>2])}function jr($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut,St){this.name=$,this.registeredClass=K,this.isReference=RA,this.isConst=KA,this.isSmartPointer=Ae,this.pointeeType=pe,this.sharingPolicy=Fe,this.rawGetPointee=Ue,this.rawConstructor=ot,this.rawShare=ut,this.rawDestructor=St,Ae||K.baseClass!==void 0?this.toWireType=Jn:KA?(this.toWireType=pA,this.destructorFunction=null):(this.toWireType=Br,this.destructorFunction=null)}var Pi,vs,ir=[],An=$=>{var K=ir[$];return K||($>=ir.length&&(ir.length=$+1),ir[$]=K=Pi.get($)),K},wn=($,K,RA)=>$.includes("j")?((KA,Ae,pe)=>{var Fe=u["dynCall_"+KA];return pe&&pe.length?Fe.apply(null,[Ae].concat(pe)):Fe.call(null,Ae)})($,K,RA):An(K).apply(null,RA),Jt=($,K)=>{var RA,KA,Ae,pe=($=ki($)).includes("j")?(RA=$,KA=K,Ae=[],function(){return Ae.length=0,Object.assign(Ae,arguments),wn(RA,KA,Ae)}):An(K);return typeof pe!="function"&&jt(`unknown function pointer with signature ${$}: ${K}`),pe},fg=$=>{var K=Ia($),RA=ki(K);return yn(K),RA},On=($,K)=>{var RA=[],KA={};throw K.forEach(function Ae(pe){KA[pe]||Ko[pe]||($i[pe]?$i[pe].forEach(Ae):(RA.push(pe),KA[pe]=!0))}),new vs(`${$}: `+RA.map(fg).join([", "]))},Gn=($,K)=>{for(var RA=[],KA=0;KA<$;KA++)RA.push(MA[K+4*KA>>2]);return RA},Vs=$=>{for(;$.length;){var K=$.pop();$.pop()(K)}};function Qr($,K,RA,KA,Ae,pe){var Fe=K.length;Fe<2&&jt("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var Ue=K[1]!==null&&RA!==null,ot=!1,ut=1;ut($ instanceof Object||jt(`${RA} with invalid "this": ${$}`),$ instanceof K.registeredClass.constructor||jt(`${RA} incompatible with "this" of type ${$.constructor.name}`),$.$$.ptr||jt(`cannot call emscripten binding method ${RA} on deleted object`),yo($.$$.ptr,$.$$.ptrType.registeredClass,K.registeredClass));function pr(){this.allocated=[void 0],this.freelist=[]}var po=new pr,gn=$=>{$>=po.reserved&&--po.get($).refcount===0&&po.free($)},fl=()=>{for(var $=0,K=po.reserved;K($||jt("Cannot use deleted val. handle = "+$),po.get($).value),toHandle:$=>{switch($){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return po.allocate({refcount:1,value:$})}}};function mr($){return this.fromWireType(tA[$>>2])}var ks,Yc,ps,rs=$=>{if($===null)return"null";var K=typeof $;return K==="object"||K==="array"||K==="function"?$.toString():""+$},Bu=($,K)=>{switch(K){case 4:return function(RA){return this.fromWireType(PA[RA>>2])};case 8:return function(RA){return this.fromWireType(ge[RA>>3])};default:throw new TypeError(`invalid float width (${K}): ${$}`)}},ja=($,K,RA)=>{switch(K){case 1:return RA?KA=>lA[KA|0]:KA=>aA[KA|0];case 2:return RA?KA=>mA[KA>>1]:KA=>IA[KA>>1];case 4:return RA?KA=>tA[KA>>2]:KA=>MA[KA>>2];default:throw new TypeError(`invalid integer width (${K}): ${$}`)}},ds=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0,og=($,K,RA)=>{for(var KA=K+RA,Ae=K;$[Ae]&&!(Ae>=KA);)++Ae;if(Ae-K>16&&$.buffer&&ds)return ds.decode($.subarray(K,Ae));for(var pe="";K>10,56320|1023&ut)}}else pe+=String.fromCharCode((31&Fe)<<6|Ue)}else pe+=String.fromCharCode(Fe)}return pe},LI=($,K)=>$?og(aA,$,K):"",Xo=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0,Zi=($,K)=>{for(var RA=$,KA=RA>>1,Ae=KA+K/2;!(KA>=Ae)&&IA[KA];)++KA;if((RA=KA<<1)-$>32&&Xo)return Xo.decode(aA.subarray($,RA));for(var pe="",Fe=0;!(Fe>=K/2);++Fe){var Ue=mA[$+2*Fe>>1];if(Ue==0)break;pe+=String.fromCharCode(Ue)}return pe},Qc=($,K,RA)=>{if(RA===void 0&&(RA=2147483647),RA<2)return 0;for(var KA=K,Ae=(RA-=2)<2*$.length?RA/2:$.length,pe=0;pe>1]=Fe,K+=2}return mA[K>>1]=0,K-KA},sg=$=>2*$.length,yg=($,K)=>{for(var RA=0,KA="";!(RA>=K/4);){var Ae=tA[$+4*RA>>2];if(Ae==0)break;if(++RA,Ae>=65536){var pe=Ae-65536;KA+=String.fromCharCode(55296|pe>>10,56320|1023&pe)}else KA+=String.fromCharCode(Ae)}return KA},la=($,K,RA)=>{if(RA===void 0&&(RA=2147483647),RA<4)return 0;for(var KA=K,Ae=KA+RA-4,pe=0;pe<$.length;++pe){var Fe=$.charCodeAt(pe);if(Fe>=55296&&Fe<=57343&&(Fe=65536+((1023&Fe)<<10)|1023&$.charCodeAt(++pe)),tA[K>>2]=Fe,(K+=4)+4>Ae)break}return tA[K>>2]=0,K-KA},Go=$=>{for(var K=0,RA=0;RA<$.length;++RA){var KA=$.charCodeAt(RA);KA>=55296&&KA<=57343&&++RA,K+=4}return K},Wr=($,K)=>{var RA=Ko[$];return RA===void 0&&jt(K+" has unknown type "+fg($)),RA},wo=($,K,RA)=>{var KA=[],Ae=$.toWireType(KA,RA);return KA.length&&(MA[K>>2]=cn.toHandle(KA)),Ae},Vc={},Hn=[],Js=Reflect.construct,Dg=[null,[],[]],pc=($,K)=>{var RA=Dg[$];K===0||K===10?(($===1?k:F)(og(RA,0)),RA.length=0):RA.push(K)};(()=>{for(var $=new Array(256),K=0;K<256;++K)$[K]=String.fromCharCode(K);to=$})(),uo=u.BindingError=class extends Error{constructor($){super($),this.name="BindingError"}},Ys=u.InternalError=class extends Error{constructor($){super($),this.name="InternalError"}},Object.assign($s.prototype,{isAliasOf($){if(!(this instanceof $s)||!($ instanceof $s))return!1;var K=this.$$.ptrType.registeredClass,RA=this.$$.ptr;$.$$=$.$$;for(var KA=$.$$.ptrType.registeredClass,Ae=$.$$.ptr;K.baseClass;)RA=K.upcast(RA),K=K.baseClass;for(;KA.baseClass;)Ae=KA.upcast(Ae),KA=KA.baseClass;return K===KA&&RA===Ae},clone(){if(this.$$.ptr||ce(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var $,K=No(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&&jt("Object already scheduled for deletion"),kt(this),it(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&&jt("Object already scheduled for deletion"),je.push(this),je.length===1&&qA&&qA(Mt),this.$$.deleteScheduled=!0,this}}),u.getInheritedInstanceCount=$t,u.getLiveInheritedInstances=Ge,u.flushPendingDeletes=Mt,u.setDelayFunction=Rt,Object.assign(jr.prototype,{getPointee($){return this.rawGetPointee&&($=this.rawGetPointee($)),$},destructor($){this.rawDestructor&&this.rawDestructor($)},argPackAdvance:8,readValueFromPointer:Es,deleteObject($){$!==null&&$.delete()},fromWireType:oo}),vs=u.UnboundTypeError=(ks=Error,(ps=rn(Yc="UnboundTypeError",function($){this.name=Yc,this.message=$;var K=new Error($).stack;K!==void 0&&(this.stack=this.toString()+` +`+K.replace(/^Error(:[^\n]*)?\n/,""))})).prototype=Object.create(ks.prototype),ps.prototype.constructor=ps,ps.prototype.toString=function(){return this.message===void 0?this.name:`${this.name}: ${this.message}`},ps),Object.assign(pr.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($)}}),po.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),po.reserved=po.allocated.length,u.count_emval_handles=fl;var fn,Na={w:($,K,RA)=>{throw new _o($).init(K,RA),$},q:($,K,RA,KA,Ae)=>{},u:($,K,RA,KA)=>{Ms($,{name:K=ki(K),fromWireType:function(Ae){return!!Ae},toWireType:function(Ae,pe){return pe?RA:KA},argPackAdvance:8,readValueFromPointer:function(Ae){return this.fromWireType(aA[Ae])},destructorFunction:null})},y:($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut,St,Ot,li)=>{St=ki(St),pe=Jt(Ae,pe),Ue&&(Ue=Jt(Fe,Ue)),ut&&(ut=Jt(ot,ut)),li=Jt(Ot,li);var nt=(Ft=>{if(Ft===void 0)return"_unknown";var Ji=(Ft=Ft.replace(/[^a-zA-Z0-9_]/g,"$")).charCodeAt(0);return Ji>=48&&Ji<=57?`_${Ft}`:Ft})(St);((Ft,Ji,qi)=>{u.hasOwnProperty(Ft)?(jt(`Cannot register public name '${Ft}' twice`),us(u,Ft,Ft),u.hasOwnProperty(qi)&&jt(`Cannot register multiple overloads of a function with the same number of arguments (${qi})!`),u[Ft].overloadTable[qi]=Ji):u[Ft]=Ji})(nt,function(){On(`Cannot construct ${St} due to unbound types`,[KA])}),bi([$,K,RA],KA?[KA]:[],function(Ft){var Ji,qi;Ft=Ft[0],qi=KA?(Ji=Ft.registeredClass).instancePrototype:$s.prototype;var Hs=rn(St,function(){if(Object.getPrototypeOf(this)!==Mi)throw new uo("Use 'new' to construct "+St);if(Wo.constructor_body===void 0)throw new uo(St+" has no accessible constructor");var xn=Wo.constructor_body[arguments.length];if(xn===void 0)throw new uo(`Tried to invoke ctor of ${St} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(Wo.constructor_body).toString()}) parameters instead!`);return xn.apply(this,arguments)}),Mi=Object.create(qi,{constructor:{value:Hs}});Hs.prototype=Mi;var Wo=new an(St,Hs,Mi,li,Ji,pe,Ue,ut);Wo.baseClass&&(Wo.baseClass.__derivedClasses===void 0&&(Wo.baseClass.__derivedClasses=[]),Wo.baseClass.__derivedClasses.push(Wo));var Sg=new jr(St,Wo,!0,!1,!1),or=new jr(St+"*",Wo,!1,!1,!1),fr=new jr(St+" const*",Wo,!1,!0,!1);return Xt[$]={pointerType:or,constPointerType:fr},((xn,yl,qs)=>{u.hasOwnProperty(xn)||io("Replacing nonexistant public symbol"),u[xn].overloadTable!==void 0&&qs!==void 0?u[xn].overloadTable[qs]=yl:(u[xn]=yl,u[xn].argCount=qs)})(nt,Hs),[Sg,or,fr]})},x:($,K,RA,KA,Ae,pe)=>{var Fe=Gn(K,RA);Ae=Jt(KA,Ae),bi([],[$],function(Ue){var ot=`constructor ${(Ue=Ue[0]).name}`;if(Ue.registeredClass.constructor_body===void 0&&(Ue.registeredClass.constructor_body=[]),Ue.registeredClass.constructor_body[K-1]!==void 0)throw new uo(`Cannot register multiple constructors with identical number of parameters (${K-1}) for class '${Ue.name}'! Overload resolution is currently only performed using the parameter count, not actual type info!`);return Ue.registeredClass.constructor_body[K-1]=()=>{On(`Cannot construct ${Ue.name} due to unbound types`,Fe)},bi([],Fe,ut=>(ut.splice(1,0,null),Ue.registeredClass.constructor_body[K-1]=Qr(ot,ut,null,Ae,pe),[])),[]})},i:($,K,RA,KA,Ae,pe,Fe,Ue,ot)=>{var ut=Gn(RA,KA);K=(St=>{const Ot=(St=St.trim()).indexOf("(");return Ot!==-1?St.substr(0,Ot):St})(K=ki(K)),pe=Jt(Ae,pe),bi([],[$],function(St){var Ot=`${(St=St[0]).name}.${K}`;function li(){On(`Cannot call ${Ot} due to unbound types`,ut)}K.startsWith("@@")&&(K=Symbol[K.substring(2)]),Ue&&St.registeredClass.pureVirtualFunctions.push(K);var nt=St.registeredClass.instancePrototype,Ft=nt[K];return Ft===void 0||Ft.overloadTable===void 0&&Ft.className!==St.name&&Ft.argCount===RA-2?(li.argCount=RA-2,li.className=St.name,nt[K]=li):(us(nt,K,Ot),nt[K].overloadTable[RA-2]=li),bi([],ut,function(Ji){var qi=Qr(Ot,Ji,St,pe,Fe);return nt[K].overloadTable===void 0?(qi.argCount=RA-2,nt[K]=qi):nt[K].overloadTable[RA-2]=qi,[]}),[]})},k:($,K,RA,KA,Ae,pe,Fe,Ue,ot,ut)=>{K=ki(K),Ae=Jt(KA,Ae),bi([],[$],function(St){var Ot=`${(St=St[0]).name}.${K}`,li={get(){On(`Cannot access ${Ot} due to unbound types`,[RA,Fe])},enumerable:!0,configurable:!0};return li.set=ot?()=>On(`Cannot access ${Ot} due to unbound types`,[RA,Fe]):nt=>jt(Ot+" is a read-only property"),Object.defineProperty(St.registeredClass.instancePrototype,K,li),bi([],ot?[RA,Fe]:[RA],function(nt){var Ft=nt[0],Ji={get(){var Hs=Pn(this,St,Ot+" getter");return Ft.fromWireType(Ae(pe,Hs))},enumerable:!0};if(ot){ot=Jt(Ue,ot);var qi=nt[1];Ji.set=function(Hs){var Mi=Pn(this,St,Ot+" setter"),Wo=[];ot(ut,Mi,qi.toWireType(Wo,Hs)),Vs(Wo)}}return Object.defineProperty(St.registeredClass.instancePrototype,K,Ji),[]}),[]})},t:($,K)=>{Ms($,{name:K=ki(K),fromWireType:RA=>{var KA=cn.toValue(RA);return gn(RA),KA},toWireType:(RA,KA)=>cn.toHandle(KA),argPackAdvance:8,readValueFromPointer:mr,destructorFunction:null})},p:($,K,RA)=>{Ms($,{name:K=ki(K),fromWireType:KA=>KA,toWireType:(KA,Ae)=>Ae,argPackAdvance:8,readValueFromPointer:Bu(K,RA),destructorFunction:null})},g:($,K,RA,KA,Ae)=>{K=ki(K);var pe=ot=>ot;if(KA===0){var Fe=32-8*RA;pe=ot=>ot<>>Fe}var Ue=K.includes("unsigned");Ms($,{name:K,fromWireType:pe,toWireType:Ue?function(ot,ut){return this.name,ut>>>0}:function(ot,ut){return this.name,ut},argPackAdvance:8,readValueFromPointer:ja(K,RA,KA!==0),destructorFunction:null})},a:($,K,RA)=>{var KA=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array][K];function Ae(pe){var Fe=MA[pe>>2],Ue=MA[pe+4>>2];return new KA(lA.buffer,Ue,Fe)}Ms($,{name:RA=ki(RA),fromWireType:Ae,argPackAdvance:8,readValueFromPointer:Ae},{ignoreDuplicateRegistrations:!0})},o:($,K)=>{var RA=(K=ki(K))==="std::string";Ms($,{name:K,fromWireType(KA){var Ae,pe=MA[KA>>2],Fe=KA+4;if(RA)for(var Ue=Fe,ot=0;ot<=pe;++ot){var ut=Fe+ot;if(ot==pe||aA[ut]==0){var St=LI(Ue,ut-Ue);Ae===void 0?Ae=St:(Ae+="\0",Ae+=St),Ue=ut+1}}else{var Ot=new Array(pe);for(ot=0;ot{for(var li=0,nt=0;nt=55296&&Ft<=57343?(li+=4,++nt):li+=3}return li})(Ae):Ae.length;var Ue=ms(4+pe+1),ot=Ue+4;if(MA[Ue>>2]=pe,RA&&Fe)((Ot,li,nt,Ft)=>{if(!(Ft>0))return 0;for(var Ji=nt,qi=nt+Ft-1,Hs=0;Hs=55296&&Mi<=57343&&(Mi=65536+((1023&Mi)<<10)|1023&Ot.charCodeAt(++Hs)),Mi<=127){if(nt>=qi)break;li[nt++]=Mi}else if(Mi<=2047){if(nt+1>=qi)break;li[nt++]=192|Mi>>6,li[nt++]=128|63&Mi}else if(Mi<=65535){if(nt+2>=qi)break;li[nt++]=224|Mi>>12,li[nt++]=128|Mi>>6&63,li[nt++]=128|63&Mi}else{if(nt+3>=qi)break;li[nt++]=240|Mi>>18,li[nt++]=128|Mi>>12&63,li[nt++]=128|Mi>>6&63,li[nt++]=128|63&Mi}}li[nt]=0})(Ae,aA,ot,pe+1);else if(Fe)for(var ut=0;ut255&&(yn(ot),jt("String has UTF-16 code units that do not fit in 8 bits")),aA[ot+ut]=St}else for(ut=0;ut{var KA,Ae,pe,Fe,Ue;RA=ki(RA),K===2?(KA=Zi,Ae=Qc,Fe=sg,pe=()=>IA,Ue=1):K===4&&(KA=yg,Ae=la,Fe=Go,pe=()=>MA,Ue=2),Ms($,{name:RA,fromWireType:ot=>{for(var ut,St=MA[ot>>2],Ot=pe(),li=ot+4,nt=0;nt<=St;++nt){var Ft=ot+4+nt*K;if(nt==St||Ot[Ft>>Ue]==0){var Ji=KA(li,Ft-li);ut===void 0?ut=Ji:(ut+="\0",ut+=Ji),li=Ft+K}}return yn(ot),ut},toWireType:(ot,ut)=>{typeof ut!="string"&&jt(`Cannot pass non-string to C++ string type ${RA}`);var St=Fe(ut),Ot=ms(4+St+K);return MA[Ot>>2]=St>>Ue,Ae(ut,Ot+4,St+K),ot!==null&&ot.push(yn,Ot),Ot},argPackAdvance:8,readValueFromPointer:mr,destructorFunction(ot){yn(ot)}})},v:($,K)=>{Ms($,{isVoid:!0,name:K=ki(K),argPackAdvance:0,fromWireType:()=>{},toWireType:(RA,KA)=>{}})},j:($,K,RA)=>($=cn.toValue($),K=Wr(K,"emval::as"),wo(K,RA,$)),e:($,K,RA,KA,Ae)=>{var pe,Fe;return($=Hn[$])(K=cn.toValue(K),K[RA=(Fe=Vc[pe=RA])===void 0?ki(pe):Fe],KA,Ae)},d:gn,f:($,K,RA)=>{var KA=((ut,St)=>{for(var Ot=new Array(ut),li=0;li>2],"parameter "+li);return Ot})($,K),Ae=KA.shift();$--;var pe,Fe,Ue=new Array($),ot=`methodCaller<(${KA.map(ut=>ut.name).join(", ")}) => ${Ae.name}>`;return pe=rn(ot,(ut,St,Ot,li)=>{for(var nt=0,Ft=0;Ft<$;++Ft)Ue[Ft]=KA[Ft].readValueFromPointer(li+nt),nt+=KA[Ft].argPackAdvance;var Ji=RA===1?Js(St,Ue):St.apply(ut,Ue);for(Ft=0;Ft<$;++Ft)KA[Ft].deleteObject&&KA[Ft].deleteObject(Ue[Ft]);return wo(Ae,Ot,Ji)}),Fe=Hn.length,Hn.push(pe),Fe},c:$=>{$>4&&(po.get($).refcount+=1)},b:$=>{var K=cn.toValue($);Vs(K),gn($)},h:($,K)=>{var RA=($=Wr($,"_emval_take_value")).readValueFromPointer(K);return cn.toHandle(RA)},m:()=>{It("")},s:($,K,RA)=>aA.copyWithin($,K,K+RA),r:$=>{aA.length,It("OOM")},n:($,K,RA,KA)=>{for(var Ae=0,pe=0;pe>2],Ue=MA[K+4>>2];K+=8;for(var ot=0;ot>2]=Ae,0}},In=function(){var $={a:Na};function K(RA,KA){var Ae,pe;return In=RA.exports,_=In.z,Ae=_.buffer,u.HEAP8=lA=new Int8Array(Ae),u.HEAP16=mA=new Int16Array(Ae),u.HEAPU8=aA=new Uint8Array(Ae),u.HEAPU16=IA=new Uint16Array(Ae),u.HEAP32=tA=new Int32Array(Ae),u.HEAPU32=MA=new Uint32Array(Ae),u.HEAPF32=PA=new Float32Array(Ae),u.HEAPF64=ge=new Float64Array(Ae),Pi=In.C,pe=In.A,Be.unshift(pe),function(){if(Dt--,u.monitorRunDependencies&&u.monitorRunDependencies(Dt),Dt==0&&qt){var Fe=qt;qt=null,Fe()}}(),In}if(Dt++,u.monitorRunDependencies&&u.monitorRunDependencies(Dt),u.instantiateWasm)try{return u.instantiateWasm($,K)}catch(RA){F(`Module.instantiateWasm callback failed with error: ${RA}`),l(RA)}return gi(0,re,$,function(RA){K(RA.instance)}).catch(l),{}}(),ms=$=>(ms=In.B)($),Ia=$=>(Ia=In.D)($),yn=$=>(yn=In.E)($),Ga=$=>(Ga=In.F)($);u.dynCall_jiji=($,K,RA,KA,Ae)=>(u.dynCall_jiji=In.G)($,K,RA,KA,Ae),u._vertexShaderSource=10688;function ya(){function $(){fn||(fn=!0,u.calledRun=!0,de||(Fi(Be),r(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),function(){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)Ke(u.postRun.shift());Fi(ct)}()))}Dt>0||(function(){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)mt(u.preRun.shift());Fi(Ve)}(),Dt>0||(u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),$()},1)):$()))}if(qt=function $(){fn||ya(),fn||(qt=$)},u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();return ya(),i.ready}})(),PaA=OaA,WK=0,E9=class d9{constructor(i){this.core=i,sL(this,"seq"),sL(this,"_core"),sL(this,"log"),sL(this,"beautyParams"),WK+=1,this.seq=WK,this._core=i,this.log=i.log.createChild({id:`${this.getAlias()}${WK}`}),this.log.info("created")}getName(){return d9.Name}getAlias(){return"bb"}getValidateRule(i){switch(i){case"start":case"update":return UaA(this._core);case"stop":return FaA(this._core)}}getGroup(){return"bb"}async start(i){this._core.room.videoManager.Wasm||(this._core.room.videoManager.Wasm=await PaA()),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,u=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:l,ruddy:u})}async update(i){const r=this._core.utils.isUndefined(i.beauty)?.5:i.beauty,l=this._core.utils.isUndefined(i.brightness)?.5:i.brightness,u=this._core.utils.isUndefined(i.ruddy)?.5:i.ruddy;return this._core.room.videoManager.setBeautyParams({beauty:r,brightness:l,ruddy:u})}async stop(){return this._core.room.videoManager.renderMode="auto",this._core.room.videoManager.stopBeauty()}destroy(){this._core.room.videoManager.renderMode="auto"}};sL(E9,"Name","BasicBeauty");var C9=E9,xaA=C9;const YaA=Object.freeze(Object.defineProperty({__proto__:null,BasicBeauty:C9,default:xaA},Symbol.toStringTag,{value:"Module"})),VaA=ZL(YaA);var JaA=Object.defineProperty,HaA=(t,i,r)=>i in t?JaA(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,m1=(t,i,r)=>HaA(t,typeof i!="symbol"?i+"":i,r),qaA={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}}},KaA={name:"option",required:!0,properties:{transcriberRobotId:{type:"string",required:!0}}},jaA=new Set([2002,4003]),h9=class B9{constructor(i){this.core=i,m1(this,"disableRandomCall",!0),m1(this,"activeTranscriberMap",new Map),m1(this,"_log"),this._log=this.core.log.createChild({id:`${this.getAlias()}`})}getName(){return B9.Name}getAlias(){return"rt-trans"}getGroup(){return"*"}getValidateRule(i){switch(i){case"start":return qaA;case"update":return{};case"stop":return KaA}}async start(i){var r;const{RtcError:l,ErrorCode:u}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new l({code:u.ENV_NOT_SUPPORTED});const{sourceLanguage:p,translationLanguages:y,userIdsToTranscribe:w="all",transcriberRobotId:_}=i,k=_||`transcriber_${this.core.room.roomId}_robot_${this.core.room.userId}`,F={sdkappid:this.core.room.sdkAppId,roomid:String(this.core.room.roomId),roomType:this.core.room.useStringRoomId?1:0,agentParam:{cdnRobotUserid:k,lifecycleUserid:this.core.room.userId,maxIdletime:30},subscribeParams:{subUsers:[]},asrParams:{lang:p,vadSilenceTime:1e3},translationParams:{mode:1,targetLangs:[""]}};y&&y.length>0&&(F.translationParams.mode=1,F.translationParams.targetLangs=Array.isArray(y)?y:[y]),w==="all"?F.subscribeParams.subUsers=[]:Array.isArray(w)?F.subscribeParams.subUsers=w.map(j=>({userId:j,roomType:this.core.room.useStringRoomId?1:0,roomid:String(this.core.room.roomId)})):w&&(F.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(F)}`);const j=await this.core.room.sendSignalMessage({command:"start_cloud_transcription",responseCommand:String(8268),data:F,retries:0}),{code:lA,data:aA}=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:aA}),new l({code:u.SERVER_ERROR,extraCode:lA,message:IA})}const{taskId:mA}=aA;if(!mA)throw this._log.error("taskId is required",{data:j.data}),new l({code:u.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:u}=this.core.errorModule;if(!this.core.room.sendSignalMessage)throw new l({code:u.ENV_NOT_SUPPORTED});try{const p=await this.core.room.sendSignalMessage({command:"stop_cloud_transcription",responseCommand:String(8270),data:{taskId:i},retries:3});if(p.data.code!==0){const y=p.data.code,w=((r=p.data)==null?void 0:r.message)||"";if(!jaA.has(y))throw this._log.error("stop_cloud_transcription failed",{extraCode:y,reason:w,data:p.data.data}),new l({code:u.SERVER_ERROR,extraCode:y,message:w});this._log.warn("stop_cloud_transcription ignored error",{extraCode:y,reason:w,data:p.data.data})}this.activeTranscriberMap.delete(i)}catch(p){throw this._log.error("stop_cloud_transcription failed",{error:p}),p}}destroy(){this.activeTranscriberMap.clear()}};m1(h9,"Name","RealtimeTranscriber");var Q9=h9,WaA=Q9;const zaA=Object.freeze(Object.defineProperty({__proto__:null,RealtimeTranscriber:Q9,default:WaA},Symbol.toStringTag,{value:"Module"})),ZaA=ZL(zaA);var XaA=Object.create,eU=Object.defineProperty,$aA=Object.defineProperties,p9=Object.getOwnPropertyDescriptor,AgA=Object.getOwnPropertyDescriptors,m9=Object.getOwnPropertyNames,O1=Object.getOwnPropertySymbols,egA=Object.getPrototypeOf,O3=Object.prototype.hasOwnProperty,f9=Object.prototype.propertyIsEnumerable,Hj=(t,i,r)=>i in t?eU(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,Rn=(t,i)=>{for(var r in i||(i={}))O3.call(i,r)&&Hj(t,r,i[r]);if(O1)for(var r of O1(i))f9.call(i,r)&&Hj(t,r,i[r]);return t},zh=(t,i)=>$aA(t,AgA(i)),tgA=(t,i)=>{var r={};for(var l in t)O3.call(t,l)&&i.indexOf(l)<0&&(r[l]=t[l]);if(t!=null&&O1)for(var l of O1(t))i.indexOf(l)<0&&f9.call(t,l)&&(r[l]=t[l]);return r},tU=(t,i)=>function(){return i||(0,t[m9(t)[0]])((i={exports:{}}).exports,i),i.exports},P3=(t,i)=>{for(var r in i)eU(t,r,{get:i[r],enumerable:!0})},igA=(t,i,r,l)=>{if(i&&typeof i=="object"||typeof i=="function")for(let u of m9(i))O3.call(t,u)||u===r||eU(t,u,{get:()=>i[u],enumerable:!(l=p9(i,u))||l.enumerable});return t},O_=(t,i,r)=>(r=t!=null?XaA(egA(t)):{},igA(eU(r,"default",{value:t,enumerable:!0}),t)),dc=(t,i,r,l)=>{for(var u,p=p9(i,r),y=t.length-1;y>=0;y--)(u=t[y])&&(p=u(i,r,p)||p);return p&&eU(i,r,p),p},Ee=(t,i,r)=>Hj(t,typeof i!="symbol"?i+"":i,r),iU=tU({"../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(t,i){var r=Object.prototype.hasOwnProperty,l="~";function u(){}function p(k,F,j){this.fn=k,this.context=F,this.once=j||!1}function y(k,F,j,lA,aA){if(typeof j!="function")throw new TypeError("The listener must be a function");var mA=new p(j,lA||k,aA),IA=l?l+F:F;return k._events[IA]?k._events[IA].fn?k._events[IA]=[k._events[IA],mA]:k._events[IA].push(mA):(k._events[IA]=mA,k._eventsCount++),k}function w(k,F){--k._eventsCount===0?k._events=new u:delete k._events[F]}function _(){this._events=new u,this._eventsCount=0}Object.create&&(u.prototype=Object.create(null),new u().__proto__||(l=!1)),_.prototype.eventNames=function(){var k,F,j=[];if(this._eventsCount===0)return j;for(F in k=this._events)r.call(k,F)&&j.push(l?F.slice(1):F);return Object.getOwnPropertySymbols?j.concat(Object.getOwnPropertySymbols(k)):j},_.prototype.listeners=function(k){var F=l?l+k:k,j=this._events[F];if(!j)return[];if(j.fn)return[j.fn];for(var lA=0,aA=j.length,mA=new Array(aA);lA1&&(y[_[0]]=void 0),y};t.parseParams=function(y){return y.split(/;\s?/).reduce(p,{})},t.parseFmtpConfig=t.parseParams,t.parsePayloads=function(y){return y.toString().split(" ").map(Number)},t.parseRemoteCandidates=function(y){for(var w=[],_=y.split(" ").map(i),k=0;k<_.length;k+=3)w.push({component:_[k],ip:_[k+1],port:_[k+2]});return w},t.parseImageAttributes=function(y){return y.split(" ").map(function(w){return w.substring(1,w.length-1).split(",").reduce(p,{})})},t.parseSimulcastStreamList=function(y){return y.split(";").map(function(w){return w.split(",").map(function(_){var k,F=!1;return _[0]!=="~"?k=i(_):(k=i(_.substring(1,_.length)),F=!0),{scid:k,paused:F}})})}}}),sgA=tU({"../node_modules/.pnpm/sdp-transform@2.15.0/node_modules/sdp-transform/lib/writer.js"(t,i){var r=x3(),l=/%[sdv%]/g,u=function(_){var k=1,F=arguments,j=F.length;return _.replace(l,function(lA){if(k>=j)return lA;var aA=F[k];switch(k+=1,lA){case"%%":return"%";case"%s":return String(aA);case"%d":return Number(aA);case"%v":return""}})},p=function(_,k,F){var j=[_+"="+(k.format instanceof Function?k.format(k.push?F:F[k.name]):k.format)];if(k.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,u){const{RtcError:p,ErrorCode:y,ErrorCodeDictionary:w}=t.errorModule;if(!r)return;const{width:_,height:k}=r;if(_&&k&&_*k>8294400)throw new p({code:y.INVALID_PARAMETER,message:"The mix resolution cannot be set higher than 3840 * 2160."})}}),D9=t=>({required:!1,type:["string",HTMLElement,null],validate(i,r,l){const{RtcError:u,ErrorCode:p,ErrorCodeDictionary:y}=t.errorModule;if(t.utils.isString(i)&&!document.getElementById(i))throw new u({code:p.INVALID_PARAMETER,extraCode:y.INVALID_ELEMENT_ID,fnName:l,messageParams:{key:r}})}}),oU=(t,i=!0)=>({type:"object",required:i,properties:Rn({},rgA),validate(r,l,u){const{RtcError:p,ErrorCode:y,ErrorCodeDictionary:w}=t.errorModule;if(r){if(r.fillMode&&!["contain","cover","fill"].includes(r.fillMode))throw new p({code:y.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The fillMode parameter must be 'contain', 'cover' or 'fill'",fnName:u});if(r.rotation&&![0,90,180,270].includes(r.rotation))throw new p({code:y.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,message:"The rotation parameter must be 0, 90, 180 or 270",fnName:u})}}}),S9=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({},oU(t))}}}),M9=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({},oU(t))},validate(i,r,l){const{RtcError:u,ErrorCode:p,ErrorCodeDictionary:y}=t.errorModule;if(!t.rtcDectection.isScreenCaptureApiAvailable())throw new u({code:p.ENV_NOT_SUPPORTED,fnName:l,extraCode:y.NOT_SUPPORTED_SCREEN_SHARE})}}}),v9=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({},oU(t))}}}),R9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},oU(t))}}}),w9=t=>({type:"array",required:!1,arrayItem:{type:"object",properties:{id:{required:!0,type:"string"},url:{required:!0,type:"string"},layout:Rn({},oU(t))}}});function agA(t){return{name:"VideoMixerOptions",type:"object",required:!0,allowEmpty:!1,properties:{view:Rn({},D9(t)),canvasInfo:Rn({},y9(t,!0)),camera:Rn({},S9(t)),screen:Rn({},M9(t)),text:Rn({},v9(t)),image:Rn({},R9(t)),video:Rn({},w9(t))},validate(i,r,l,u){const{RtcError:p,ErrorCode:y,ErrorCodeDictionary:w}=t.errorModule;if(t.environment.isMobile())throw new p({code:y.ENV_NOT_SUPPORTED,message:"VideoMixer is not supported on mobile devices currently"});const{onScreenShareStop:_}=i;if(_&&!t.utils.isFunction(_))throw new p({code:y.INVALID_PARAMETER,extraCode:w.INVALID_PARAMETER_TYPE,fnName:l,messageParams:{key:"onScreenShareStop",value:typeof _,rule:{type:"Function"}}})}}}function ggA(t){return{name:"VideoMixerOptions",type:"object",required:!1,allowEmpty:!1,properties:{view:Rn({},D9(t)),canvasInfo:Rn({},y9(t)),camera:Rn({},S9(t)),screen:Rn({},M9(t)),text:Rn({},v9(t)),image:Rn({},R9(t)),video:Rn({},w9(t))}}}function cgA(t){return{name:"StopVideoMixerOptions",required:!1}}var _9=(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))(_9||{}),Hg=_9,lgA=function(t){for(const i in Hg)if(Hg[i]===t)return i;return"UNKNOWN"},IgA=class extends Error{constructor({name:t="RtcError",message:i,code:r=Hg.UNKNOWN,extraCode:l=0,constraint:u}){const p=`<${lgA(r)} 0x${r.toString(16)}>`,y=`${i}${u?` constraint: ${u}`:""}${i?.includes(p)?"":` ${p}`}`;super(y),Ee(this,"code"),Ee(this,"extraCode"),Ee(this,"message"),Ee(this,"originMessage"),Ee(this,"name"),Ee(this,"constraint"),this.code=r,this.extraCode=l,this.name=t,this.message=y,this.constraint=u,this.originMessage=i}getCode(){return this.code}getExtraCode(){return this.extraCode}toString(){return this.originMessage}},Bl=IgA,ugA=0,Y3=function(){return Date.now()+ugA},T9=function(){const t=new Date;return t.setTime(Y3()),t.toLocaleString()},EgA=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}`},dgA={};P3(dgA,{REPORT_TYPE:()=>X9,buildSSOPackage:()=>q3,bytes2ms:()=>VgA,calculateScaleResolutionDownNumber:()=>z9,concatArrayBuffers:()=>EcA,convertObjectNumberToInt:()=>j9,copyProperties:()=>YgA,deepClone:()=>Y1,deepCloneBasic:()=>A3,deepMerge:()=>H9,delay:()=>G_,fibonacci:()=>H3,formatedTime:()=>rcA,getConstructorName:()=>WgA,getContainerFromElement:()=>scA,getEnv:()=>kgA,getFirst16Bits:()=>CcA,getInternalVersion:()=>$gA,getLast16Bits:()=>dcA,getLoggerUrl:()=>V3,getMediaStreamTrackInfo:()=>lcA,getMuteStateFromFlag:()=>J9,getNetworkType:()=>J3,getNumNetworkType:()=>xgA,getReconnectionTimeout:()=>qgA,getStringByteLength:()=>acA,getTestSignalDomain:()=>UgA,getTurnServer:()=>tcA,getUint32Version:()=>K9,getValueType:()=>gv,getViewListFromView:()=>ocA,glog:()=>HgA,ipv4ToUint32:()=>icA,isArray:()=>VC,isAudioWorkletSupported:()=>zgA,isBoolean:()=>tv,isConstructor:()=>V9,isEmpty:()=>ecA,isFunction:()=>ev,isLangChinese:()=>Gy,isMediaStreamTrack:()=>KgA,isNumber:()=>cv,isObject:()=>zM,isOverseaSdkAppId:()=>x1,isPlainObject:()=>N_,isPortrait:()=>q9,isPromise:()=>Y9,isRemoteTrack:()=>jgA,isRotate90Or270:()=>Z9,isSetSinkIdSupported:()=>ZgA,isString:()=>HC,isUndefined:()=>$n,isVideoMixerOutputTrack:()=>K3,loadImage:()=>gcA,loadVideo:()=>IcA,ms2bytes:()=>JgA,ms2samples:()=>x9,normalizeUrl:()=>ccA,performanceNow:()=>Pc,promiseAny:()=>XgA,samples2ms:()=>P9,setNetworkTypeFromWebRTC:()=>PgA,stringify:()=>by,stringifyIncludeValue:()=>$j,throttlePromise:()=>W9});var P1="5.0.0",N9=typeof importScripts<"u",G9=typeof registerProcessor<"u",CgA="web.sdk.qcloud.com",qj=`https://${CgA}/trtc/webrtc/doc`,jz="https://cloud.tencent.com/document/product/647/85386",Wz="https://trtc.io/document/56025",hgA="https://yun.tim.qq.com",BgA="https://apisgp.my-imcloud.com",QgA="trtc_error_assistance",b9={LOG:"jssdk_log"},zK={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_||{}),k9={unknown:0,wifi:1,"4g":2,"3g":3,"2g":4,wired:5,"5g":6},pgA=6048e5,mgA={"480p_2":{width:640,height:480,frameRate:15,bitrate:500}},fgA=mgA["480p_2"],zt={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"},zz=1,ygA=2,DgA=4,Zz=8,Xz=64,$z=16,SgA=256,yL={PLAYER_ERROR:"player-error",LOAD_WORKLET:"load-worklet",GET_USER_MEDIA_RETRY:"getUserMedia-retry"},MgA="unified-plan",I_=5,L9="default",A1=2e3,U9=["width","height","frameRate","facingMode","sampleRate","sampleSize","channelCount","deviceId","min","max"],vgA={alpha:!0,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"},RgA=function(t,i,r,l){return new(r||(r=Promise))(function(u,p){function y(k){try{_(l.next(k))}catch(F){p(F)}}function w(k){try{_(l.throw(k))}catch(F){p(F)}}function _(k){var F;k.done?u(k.value):(F=k.value,F instanceof r?F:new r(function(j){j(F)})).then(y,w)}_((l=l.apply(t,[])).next())})},Kj=Symbol(32),jj=Symbol(16),Wj=Symbol(8),R_=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 RgA(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=u=>{delete this.lastReadPromise,delete this.resolve,delete this.need,i(u)},this.demand(t,!0)||(l=this.pull)===null||l===void 0||l.call(this,t)})})}readU32(){return this.read(Kj)}readU16(){return this.read(jj)}readU8(){return this.read(Wj)}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=u=>i.length<(r=u);if(typeof this.need=="number"){if(l(this.need))return;t=i.subarray(0,r)}else if(this.need===Kj){if(l(4))return;t=i[0]<<24|i[1]<<16|i[2]<<8|i[3]}else if(this.need===jj){if(l(2))return;t=i[0]<<8|i[1]}else if(this.need===Wj){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}};R_.U32=Kj,R_.U16=jj,R_.U8=Wj;var wgA=128;function ZK(t){const i=new R_;for(;t>=128;)i.malloc(1)[0]=255&t|wgA,t>>>=7;return i.malloc(1)[0]=255&t,i.buffer||new Uint8Array(0)}function zj(t,i=0){const r=new R_,l=i<<3;switch(typeof t){case"boolean":const u=r.malloc(2);u[0]=l,u[1]=t?1:0;break;case"number":r.malloc(1)[0]=l,r.write(ZK(t));break;case"string":r.malloc(1)[0]=2|l;const p=new TextEncoder().encode(t);r.write(ZK(p.length));const y=r.malloc(p.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 ZE(t,i){return t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3]}function t8(t,i){return t[i]}function Kk(t,i,r){return new TextDecoder().decode(_gA(t,i,r))}function _gA(t,i,r){return t.slice(i,i+r)}var XK=0,Zj=2654435769,Xj=16,i8=4,DL=2,SL=7;function TgA(t,i,r,l="AVQualityReportSvc.C2S",u=2e3,p=2,y=30){return{version:u,encryption:p,d2:"",d2Len:0,uinType:y,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 NgA(t,i){const r=new A8,l=TgA(i,t,XK);XK=XK+1&2147483647,r.writeInt32(0),r.writeInt32(l.version),r.writeByte(l.encryption);const u=new TextEncoder().encode(l.d2);r.writeInt32(u.length+4),u&&r.writeBytes(u),r.writeByte(l.uinType);const p=new TextEncoder().encode(l.uin);r.writeInt32(p.length+4),p.length&&r.writeBytes(p);const y=new A8;y.writeInt32(0),y.writeInt32(l.reqHead.seqNumber),y.writeInt32(l.reqHead.appId),y.writeByte(l.reqHead.appId>>>24&255),y.writeByte(l.reqHead.appId>>>16&255),y.writeByte(l.reqHead.appId>>>8&255),y.writeByte(255&l.reqHead.appId);for(let PA=4;PA<16;PA++)y.writeByte(0);const w=new TextEncoder().encode(l.reqHead.a2);y.writeInt32(w.length+4),w.length&&y.writeBytes(w);const _=new TextEncoder().encode(l.reqHead.serviceCmd);y.writeInt32(_.length+4),_.length&&y.writeBytes(_);const k=new TextEncoder().encode(l.reqHead.cookie);y.writeInt32(k.length+4),k.length&&y.writeBytes(k);const F=new TextEncoder().encode(l.reqHead.imei);y.writeInt32(F.length+4),F.length&&y.writeBytes(F);const j=new TextEncoder().encode(l.reqHead.ksid);y.writeInt32(j.length+4),j.length&&y.writeBytes(j);const lA=new TextEncoder().encode(l.reqHead.clientVersionInfo);y.writeInt16(lA.length+2),lA.length&&y.writeBytes(lA);const aA=y.length;y.data[0]=aA>>>24&255,y.data[1]=aA>>>16&255,y.data[2]=aA>>>8&255,y.data[3]=255&aA,HC(t)&&(t=new TextEncoder().encode(t)),y.writeInt32(t.length+4),t.length&&y.writeBytes(t);let mA=new Uint8Array(y.data),IA=null;l.encryption===1?IA=new TextEncoder().encode(l.uin):l.encryption===2&&(IA=new Uint8Array(16)),IA&&(mA=GgA(mA,IA)),r.writeBytes(mA);const tA=new Uint8Array(r.data),MA=tA.length;return tA[0]=MA>>>24&255,tA[1]=MA>>>16&255,tA[2]=MA>>>8&255,tA[3]=255&MA,tA}function GgA(t,i){const r=t.length;let l=(r+1+DL+SL)%8;l&&(l=8-l);const u=new Uint8Array(r+1+DL+SL+l);let p=0;const y=new Uint8Array(8),w=new Uint8Array(8),_=new Uint8Array(8);let k=0;y[0]=248&Math.floor(256*Math.random())|l,k=1;for(let j=0;j>>=0,u+=(p<<4)+y[0]^p+w^(p>>>5)+y[1],u>>>=0,p+=(u<<4)+y[2]^u+w^(u>>>5)+y[3],p>>>=0;e8(r,u,l),e8(r,p,l+4)}var kgA=function(){return new URLSearchParams(location.search).get("trtc_env")||""},LgA=".rtc.qq.com",UgA=function(t){return t.includes(".")?t:`${t}${LgA}`},x1=t=>Number(t)<14e8,V3=function(t,i){let r;return r=x1(t)?BgA:hgA,`${r}/v5/AVQualityReportSvc/C2S?random=${Math.floor(Math.random()*2**31)}&sdkappid=${t}&cmdtype=${i}`},F9="unknown";function J3(){OgA();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 u=i&&i.effectiveType&&i.effectiveType.toLowerCase();return u==="slow-2"&&(u="2g"),l?O9(l,u):F9}function FgA(){jo.warn("netType changed",J3())}var o8=!1;function OgA(){var t;o8||(o8=!0,(t=navigator.connection)==null||t.addEventListener("typechange",FgA))}function O9(t,i){if(k9[t])return t;switch(t){case"cellular":case"wimax":return i||"unknown";case"ethernet":return"wired";default:return"unknown"}}function PgA(t){F9=O9(t)}function xgA(){return k9[J3()]}function YgA(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 VgA(t,i=48e3){return P9(t/4,i)}function P9(t,i=48e3){return 1e3*t/i}function JgA(t,i=48e3){return 4*x9(t,i)}function x9(t,i=48e3){return t*i/1e3}var HgA=typeof window<"u"&&typeof window.glog=="function"?window.glog:()=>{},Gy=()=>{let t=navigator.language;return t=t.substring(0,2),t==="zh"},N_=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 H3(t,i=1,r=1){return t<=1?r:H3(t-1,r,i+r)}function qgA(t){return t>8?3e4:1e3*H3(t)}function gv(t){return Reflect.apply(Object.prototype.toString,t,[]).replace(/^\[object\s(\w+)\]$/,"$1").toLowerCase()}var ev=t=>typeof t=="function",$n=t=>t===void 0,HC=t=>typeof t=="string",cv=t=>typeof t=="number",tv=t=>typeof t=="boolean",zM=t=>gv(t)==="object",VC=t=>gv(t)==="array",KgA=t=>gv(t)==="MediaStreamTrack".toLowerCase(),jgA=t=>t.isRemote,Y9=t=>gv(t)==="promise",V9=t=>ev(t)&&t.prototype.constructor===t,WgA=t=>V9(t)?t.prototype.constructor.name:"",zgA=typeof AudioWorkletNode<"u",ZgA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype;function XgA(t){return new Promise((i,r)=>{const l=[];t.forEach(u=>{u.then(i).catch(p=>{l.push(p),l.length===t.length&&r(l)})})})}function Pc(){return performance&&performance.now?Math.floor(performance.now()):Date.now()}var s8=t=>+t<10?`0${t}`:t,$gA=t=>{const i=t.match(/^\d+\.\d+\.\d+/)[0];if(!i)return t;const r=i.split("."),l=s8(r[1])+s8(r[2]);return r[1]-15>0&&(r[1]="15"),r[2]-15>0&&(r[2]="15"),`${r.join(".")}.${l}`},AcA=Object.prototype.hasOwnProperty;function ecA(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(N_(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(AcA.call(t,i))return!1;return!0}return!1}function J9(t,i){return{userId:i,hasAudio:!!(t&Zz),hasVideo:!!(t&zz),hasAuxiliary:!!(t&DgA),hasSmall:!!(t&ygA),audioMuted:!!(t&Xz),videoMuted:!!(t&$z),audioAvailable:!(!(t&Zz)||t&Xz),videoAvailable:!(!(t&zz)||t&$z),hasDatachannel:!!(t&SgA)}}function tcA(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 icA(t,i=!0){if(!HC(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 H9=function(t,i,r,l){if(!zM(t)||!zM(i))return 0;let u=0;const p=Object.keys(i);let y;for(let w=0,_=p.length;w<_;w++)if(y=p[w],!($n(i[y])||r&&r.includes(y)))if(zM(t[y])&&zM(i[y]))u+=H9(t[y],i[y],r,l);else{if(l&&l.includes(i[y]))continue;t[y]!==i[y]&&(t[y]=Y1(i[y]),u+=1)}return u};function Y1(t){if(VC(t)){const i=[];return t.forEach((r,l)=>{i[l]=Y1(r)}),i}if(zM(t)){const i={};return Object.keys(t).forEach(r=>{i[r]=Y1(t[r])}),i}return t}var ocA=t=>{let i=[];if(VC(t))i=[...t];else if(HC(t)){const r=document.getElementById(t);r&&i.push(r)}else t&&i.push(t);return i},scA=t=>HC(t)?document.getElementById(t):t,ncA=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())}`},rcA=()=>ncA(new Date);function by(t,{keysToInclude:i,keysToExclude:r}){try{if(VC(t))return`[${t.map(y=>by(y,{keysToInclude:i,keysToExclude:r})).join(",")}]`;if(!N_(t)||!VC(i)&&!VC(r))return JSON.stringify(t);const l={},u=new Set(i),p=new Set(r);return Object.keys(t).forEach(y=>{(p.size===0&&u.has(y)||u.size===0&&!p.has(y))&&(l[y]=N_(t[y])||VC(t[y])?JSON.parse(by(t[y],{keysToExclude:r,keysToInclude:i})):t[y])}),JSON.stringify(l)}catch{return"{}"}}function $j(t,i=!1){const r=[];return Object.keys(t).forEach(l=>{i===t[l]&&r.push(l)}),by(t,{keysToInclude:r})}function acA(t){return t.replace(/[\u4e00-\u9fa5]/g,"aa").length}var q9=()=>{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},gcA=async t=>new Promise((i,r)=>{let l;if(HC(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 Bl({code:Hg.INVALID_PARAMETER,message:`load image failed, url: ${t}`}))}}),K9=t=>{const i=t.split(".");return+i[0]<<24|+i[1]<<16|+i[2]<<8|+i[3]},j9=t=>(Object.keys(t).forEach(i=>{cv(t[i])&&(i.startsWith("uint")||i.startsWith("int"))?t[i]=Math.floor(t[i]):(N_(t[i])||VC(t[i]))&&j9(t[i])}),t);function G_(t,i){return new Promise(r=>{const l=setTimeout(r,t);i&&i(l)})}function W9(t,i){let r=null;return function(...l){return r||(r=t.apply(i||this,l),r.finally(()=>r=null),r)}}function ccA(t){return t.replace(/(^|[^:])\/{2,}/g,"$1/")}function lcA(t){var i;try{const{width:r,height:l,frameRate:u,sampleRate:p,sampleSize:y,channelCount:w}=(i=t.getSettings)==null?void 0:i.call(t),_=t.kind===zt.AUDIO?`${p}x${y}@${w}`:`${r}x${l}@${u}`,k=t.stats?` stats: ${JSON.stringify(t.stats).replaceAll('"',"")}`:"";return`${t.id} ${t.readyState} muted:${t.muted} ${t.kind} ${t.label} ${_}${k}`}catch{return""}}function z9(t,i){return t.width*t.height===i.width*i.height?1:q9()&&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 Z9(t){return t===90||t===270}async function IcA(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 A3(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,u)=>{r[u]=A3(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]=A3(t[l],i)}),r}return t}var X9=(t=>(t[t.END_REPORT=2001]="END_REPORT",t[t.LOG=2002]="LOG",t[t.KEY_METRIC_REPORT=2003]="KEY_METRIC_REPORT",t))(X9||{});function ucA(t,i,r,l){let u={data:t,random:Math.floor(Math.random()*2147483648),sdkAppId:r};return $n(l)||(u=zh(Rn({},u),{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(u)}}}function q3(t,i,r,l){try{const u=ucA(t,i,r,l);return NgA(zj(u),r)}catch{return JSON.stringify(t)}}function EcA(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 dcA(t){return(65535&t)>>>0}function CcA(t){return(4294901760&t)>>>0}function K3(t){return!!(t&&t instanceof CanvasCaptureMediaStreamTrack&&t.canvas.id.includes("trtc_mix"))}function hcA(t){const i=BcA(t);return i?.busiBuff}function BcA(t){try{const i={};let r=0;i.totalLength=ZE(t,r),r+=4,i.version=ZE(t,r),r+=4,i.encryption=t8(t,r),r+=1,i.uinType=t8(t,r),r+=1,i.uinLength=ZE(t,r),r+=4,i.uin=i.uinLength>4?Kk(t,r,i.uinLength-4):"",r+=i.uinLength-4;const l=t.slice(r);if(i.encryption===2){const u=new Uint8Array(16).fill(0);t=QcA(l,u),i.decrypted=!0,r=0}else t=l,r=0;return i.rspHeadLength=ZE(t,r),r+=4,i.seqNo=ZE(t,r),r+=4,i.retCode=ZE(t,r),r+=4,i.retStrLength=ZE(t,r),r+=4,i.retStr=i.retStrLength?Kk(t,r,i.retStrLength-4):"",r+=i.retStrLength-4,i.serviceCmdLength=ZE(t,r),r+=4,i.serviceCmd=i.serviceCmdLength?Kk(t,r,i.serviceCmdLength-4):"",r+=i.serviceCmdLength-4,i.cookieLength=ZE(t,r),r+=4,i.cookie=i.cookieLength?Kk(t,r,i.cookieLength-4):"",r+=i.cookieLength-4,i.flag=ZE(t,r),r+=4,i.busiBuffLength=ZE(t,r),r+=4,i.busiBuff=i.busiBuffLength?Kk(t,r,i.busiBuffLength-4):"",r+=i.busiBuffLength-4,i}catch{}}function $9(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 u=Zj*Xj>>>0;for(let p=0;p>>5)+i[3],l>>>=0,r-=(l<>>5)+i[1],r>>>=0,u-=Zj,u>>>=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 QcA(t,i){let r=0;const l=new Uint8Array(8).fill(0);let u=$9(new Uint8Array(t.slice(0,8)),i);const p=7&u[0],y=t.length-1-p-DL-SL,w=new Uint8Array(y);let _=0,k=l,F=t.slice(0,8);r=8;let j=1;j+=p;for(let aA=1;aA<=DL;)if(j<8)j++,aA++;else if(j===8){const mA=Aj(t,r,k,F,u,i);k=mA.ivPreCrypt,F=mA.ivCurCrypt,u=mA.debiBuf,r=mA.bufPos,j=0}let lA=y;for(;lA>0;)if(j<8)w[_++]=u[j]^k[j],j++,lA--;else if(j===8){const aA=Aj(t,r,k,F,u,i);k=aA.ivPreCrypt,F=aA.ivCurCrypt,u=aA.debiBuf,r=aA.bufPos,j=0}for(let aA=1;aA<=SL;)if(j<8)u[j],k[j],j++,aA++;else if(j===8){if(r>=t.length)break;const mA=Aj(t,r,k,F,u,i);if(!mA.success)break;k=mA.ivPreCrypt,F=mA.ivCurCrypt,u=mA.debiBuf,r=mA.bufPos,j=0}return w}function Aj(t,i,r,l,u,p){if(i+8>t.length)return{success:!1};const y=new Uint8Array(l),w=t.slice(i,i+8),_=new Uint8Array(8);for(let k=0;k<8;k++)_[k]=u[k]^w[k];return{success:!0,ivPreCrypt:y,ivCurCrypt:w,debiBuf:$9(_,p),bufPos:i+8}}var n8=typeof TextDecoder<"u"?new TextDecoder:void 0;function AX({url:t,body:i,method:r="POST",timeout:l,priority:u}){return new Promise((p,y)=>{if("fetch"in window)return fetch(t,{method:r,body:i,priority:u}).then(_=>_.clone().json().then(k=>({data:k}),()=>_.arrayBuffer().then(k=>({data:hcA(new Uint8Array(k))||(n8?n8.decode(k):k)})))).then(p,y);const w=new XMLHttpRequest;w.onreadystatechange=()=>{if(w.readyState===4)if(w.status>=200&&w.status<300)try{const _=JSON.parse(w.response);p({data:_})}catch{p({data:w.response})}else y({status:w.status,statusText:w.statusText||"request failed!"})},w.timeout=l||5e3,w.open(r,t,!0),w.send(i)})}var pcA=Object.prototype.hasOwnProperty,u_=t=>typeof t=="function",t_=t=>t===void 0,mcA=t=>typeof t=="boolean",ej=t=>t.isRemote,fcA=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 ycA(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(fcA(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(pcA.call(t,i))return!1;return!0}return!1}var DcA=0,ScA=1,r8=2;function McA({retryFunction:t,settings:i,onError:r,onRetrying:l,onRetryFailed:u,onRetrySuccess:p,context:y}){return function(...w){const{retries:_=5,timeout:k=1e3}=i;let F=0,j=-1,lA=DcA;const aA=async(mA,IA)=>{const tA=y||this;try{const MA=await t.apply(tA,w);F>0&&p&&p.call(this,F),F=0,mA(MA)}catch(MA){const PA=()=>{clearTimeout(j),F=0,lA=r8,IA(MA)},ge=()=>{lA!==r8&&F<(u_(_)?_():_)?(F++,lA=ScA,u_(l)&&l.call(this,F,PA),j=window.setTimeout(()=>{j=-1,aA(mA,IA)},u_(k)?k(F):k)):(PA(),u_(u)&&u.call(this,MA))};u_(r)?r.call(this,{error:MA,retry:ge,reject:IA,retryFuncArgs:w,retriedCount:F}):ge()}};return new Promise(aA)}}var j3=McA,tj=class eX{constructor(i){Ee(this,"_parentPath"),Ee(this,"userId"),Ee(this,"remoteUserId"),Ee(this,"id"),Ee(this,"sdkAppId"),Ee(this,"type"),Ee(this,"isLocal"),this.id=i.id,this.userId=i.userId,this.sdkAppId=i.sdkAppId,this.remoteUserId=i.remoteUserId,this.isLocal=!mcA(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 eX({id:i.id,userId:t_(i.userId)?this.userId:i.userId,sdkAppId:t_(i.sdkAppId)?this.sdkAppId:i.sdkAppId,type:t_(i.type)?this.type:i.type,isLocal:t_(i.isLocal)?this.isLocal:i.isLocal,remoteUserId:t_(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,u=this.getFullId();r.unshift(`[${this.isLocal?"↑":"↓"}${this.type&&this.type!=="main"?"*":""}${u}${l?`|${l}`:""}]`),jo.log(i,r,t_(this.userId)||ycA(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)}},hQ=typeof navigator>"u"?"":navigator.userAgent,xs=t=>new RegExp(t,"i").test(hQ),Bc=t=>{if(xs(t)){const i=new RegExp(`${t}\\/([\\d.]+)`),r=hQ.match(i);if(r&&r[1])return r[1]}return""},fY=t=>{if(xs(t)){const i=new RegExp(`${t}\\/(\\d+)`),r=hQ.match(i);if(r&&r[1])return parseFloat(r[1])}return NaN},a8=/AppleWebKit\/([\d.]+)/i.exec(hQ);a8&&parseFloat(a8[1]);var W3=xs("iPad"),tX=typeof navigator<"u"&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2&&xs("Macintosh"),yY=xs("iPhone")&&!W3,vcA=xs("iPod"),hu=yY||W3||vcA||tX,V1=()=>{try{return hu&&navigator.maxTouchPoints>1&&navigator.vendor.includes("Apple")}catch{return hu}},Zd=xs("Android"),iX=function(){if(Zd){const t=hQ.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}();Zd&&xs("webkit")&&iX<2.3;var Kd=xs("Firefox"),oX=Bc("Firefox"),sX=fY("Firefox"),sU=xs("Edge"),nX=Bc("Edge"),DY=xs("Edg"),rX=Bc("Edg"),RcA=fY("Edg"),z3=xs("SogouMobileBrowser"),aX=Bc("SogouMobileBrowser"),Z3=xs("MetaSr\\s"),gX=Bc("MetaSr\\s"),am=xs("TBS"),cX=Bc("TBS"),P_=xs("XWEB"),lX=Bc("XWEB");xs("MSIE\\s8\\.0");var wcA=xs("MSIE\\/\\d+");(function(){if(wcA){const t=/MSIE\s(\d+)\.\d/.exec(hQ);let i=t&&parseFloat(t[1]);return!i&&/Trident\/7.0/i.test(hQ)&&/rv:11.0/.test(hQ)&&(i=11),i}return NaN})();var nU=xs("(micromessenger|webbrowser)"),IX=Bc("MicroMessenger"),SY=!am&&xs("MQQBrowser")&&xs("COVC"),MY=!am&&xs("MQQBrowser")&&!xs("COVC"),J1=MY||SY?Bc("MQQBrowser"):"",X3=!am&&xs(" QQBrowser"),uX=Bc(" QQBrowser"),$3=!am&&xs("QQBrowserLite"),EX=Bc("QQBrowserLite"),AW=!am&&xs("MQBHD"),dX=Bc("MQBHD"),CX=xs("Windows"),vY=!hu&&xs("MAC OS X"),hX=!Zd&&xs("Linux"),BX=xs("CrOS");xs("MicroMessenger");var _cA=xs("UCBrowser");xs("Electron");var eW=xs("MiuiBrowser"),QX=Bc("MiuiBrowser"),tW=xs("HuaweiBrowser"),pX=xs("Huawei")||xs("HUAWEI"),TcA=xs("Honor")||xs("HONOR"),mX=Bc("HuaweiBrowser"),iW=xs("SamsungBrowser"),fX=Bc("SamsungBrowser"),RY=xs("HeyTapBrowser"),yX=Bc("HeyTapBrowser"),oW=xs("VivoBrowser"),DX=Bc("VivoBrowser"),sW=xs("OpenHarmony");Bc("OpenHarmony");var SX=()=>fY("Chrome"),H1=xs("CriOS"),Fy=xs("Chrome"),nW=!sU&&!Z3&&!z3&&!am&&!P_&&!DY&&!X3&&!eW&&!tW&&!iW&&!RY&&!oW&&Fy,NcA=xs("HeadlessChrome"),Oy=SX(),ij=Fy&&Oy>=128&&Oy<=143,MX=Bc("Chrome");fY("Electron");var Ad=!Fy&&!MY&&!SY&&!$3&&!AW&&xs("Safari"),vX=Ad||hu,rU=Bc("Version"),EQ=(()=>{if(tX)return rU;if(hu){const t=hQ.match(/OS (\d+)_(\d+)/i);if(t&&t[1]){let i=t[1];return t[2]&&(i+=`.${t[2]}`),i}}return""})();function GcA(t,i){const r=t.split(".").map(u=>Number(u)),l=i.split(".").map(u=>Number(u));for(let u=0;uy)return!1}return!1}function RX(t,i,r=!1){const l=t.split(".").map(p=>Number(p)),u=i.split(".").map(p=>Number(p));for(let p=0;pw)return!0;if(y{const t=Number(EQ.split(".")[0]);return t===14||t===13})(),LcA=H1&&rU==="11.1.1",q1=typeof location<"u"&&(location.protocol==="file:"||location.hostname==="localhost"||location.hostname==="127.0.0.1"),i_=(()=>{let t;return()=>{if(t===void 0)try{t=!!window.localStorage}catch{t=!1}return t}})(),iv=UcA();function UcA(){const t=new Map([[Kd,["Firefox",oX]],[DY,["Edg",rX]],[nW,["Chrome",MX]],[H1,["ChiOS",Bc("CriOS")]],[Ad&&!H1,["Safari",rU]],[am,["TBS",cX]],[P_,["XWEB",lX]],[nU&&yY,["WeChat",IX]],[X3,["QQ(Win)",uX]],[MY,["QQ(Mobile)",J1]],[SY,["QQ(Mobile X5)",J1]],[$3,["QQ(Mac)",EX]],[AW,["QQ(iPad)",dX]],[eW,["MI",QX]],[tW,["HW",mX]],[iW,["Samsung",fX]],[RY,["OPPO",yX]],[oW,["VIVO",DX]],[sU,["EDGE",nX]],[z3,["SogouMobile",aX]],[Z3,["Sogou",gX]]]);let i="unknown",r="unknown";return t.has(!0)&&([i,r]=t.get(!0)),{name:i,version:r}}function FcA(){return Zd||hu||yY||W3||sW}var OcA="";function wX(){return PcA()||""}function PcA(){const t=hQ.match(/;\s*([^;)]+)\s+Build\//);return t?.[1]?t[1].trim():null}var g8=new Map([[Zd,"Android"],[hu,"iOS"],[CX,"Windows"],[vY,"MacOS"],[hX,"Linux"],[BX,"ChromeOS"]]),_X=function(){return g8.get(!0)?g8.get(!0):"unknown"};function rW(){return CX?1:Zd?2:vY?3:hu?4:hX?5:BX?6:sW?7:0}function xcA(){return nU||P_?4:Fy?1:Ad?2:Kd?3:0}var TX=()=>{let t=_X();return hu?t+=`/${EQ}`:Zd&&(t+=`/${iX}`),t+=`/${iv.name}/${Ad&&!H1?iv.version:iv.version.split(".")[0]}`,t},YcA=O_(iU()),VcA=new YcA.default,Qs=VcA,NX=(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))(NX||{}),mn=NX,JcA=class{constructor(){Ee(this,"enable",!1),Ee(this,"ssoFailCount",0),Qs.on("22",({schedule:t})=>{var i;(i=t?.config)!=null&&i.sso&&Qs.emit("266",{enable:!0})}),Qs.on("266",({enable:t})=>{this.enable=t})}handleUploadFailed(){this.ssoFailCount++,this.ssoFailCount>3&&Qs.emit("266",{enable:!1})}},e3=new JcA,HcA="%cTRTC%c%s",qcA="padding: 1px 4px;border-radius: 3px;color: #fff;background: #1E88E5;",KcA="display: inline",GX=class bX{constructor(){Ee(this,"_isEnableUploadLog",!0),Ee(this,"_localJoinedUser",new Map),Ee(this,"_queue",[]),Ee(this,"_timeoutId",-1),Ee(this,"_logLevel",1),Ee(this,"_logLevelToUpload",2),N9||G9||(this.checkURLParam(),this.installEvents())}get isAbleToUpload(){return this._isEnableUploadLog&&this._timeoutId!==-1}installEvents(){Qs.on(mn.JOIN_SCHEDULE_SUCCESS,({schedule:i})=>{var r;(r=i?.config)!=null&&r.logLevelToUpload&&l_[i.config.logLevelToUpload]&&(this._logLevelToUpload=i.config.logLevelToUpload)}),Qs.on(mn.JOIN_START,({params:i})=>{this.addJoinedUser({userId:i.userId,sdkAppId:i.sdkAppId}),this.startUpload()}),Qs.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(u)?i.map.get(u).logs.push(l):i.map.set(u,{userId:u,sdkAppId:p,logs:[l]})});else if(HC(l.userId)&&cv(l.sdkAppId)){const{userId:u,sdkAppId:p}=l;i.map.has(u)?i.map.get(u).logs.push(l):i.map.set(u,{userId:u,sdkAppId:p,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 u=[...i.values()];for(let p=0;plA.log).join(` +`)},F=JSON.stringify(k),j=e3.enable?q3(k,2002,w):F;await this.uploadLogWithRetry(j,w,j instanceof Uint8Array,F),_.forEach(lA=>lA.uploaded=!0)}}catch{}const l=r.filter(u=>!u.uploaded);l.length>0&&(this._queue=l.concat(this._queue))}uploadLogWithRetry(i,r,l,u){return j3({retryFunction:()=>AX({url:V3(r,b9.LOG),body:i,timeout:5e3,priority:"low"}).then(p=>{l&&p.data!=="ok"&&(e3.handleUploadFailed(),this.uploadLogWithRetry(u,r,!1,u))}),settings:{retries:3,timeout:2e3},onError:({retry:p})=>{p()}})()}getPrefix(i){const r=new Date;return r.setTime(Y3()),`[${EgA(r)}] <${l_[i]}>`}getLogLevel(){return this._logLevel}setLogLevel(i){$n(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(HC(i))return i;try{return i instanceof Error?i.toString():JSON.stringify(i)}catch{return""}}addLogToQueue(i,r,l=!0,u,p){const y={log:r.reduce((w,_)=>`${w} ${this.logChunkToString(_)}`.trim(),""),level:i,userId:u,sdkAppId:p,forAllJoinedClients:l};Qs.emit(mn.LOG,{log:y}),this._isEnableUploadLog&&i>=this._logLevelToUpload&&this._queue.push(y)}log(i,r,l=!0,u,p){var y;if(r.unshift(this.getPrefix(i)),this.addLogToQueue(i,r,l,u,p),i{const i=16*Math.random()|0;return(t=="x"?i:3&i|8).toString(16)})},kX=WcA,zcA=class{constructor(){Ee(this,"_prefix","TRTC"),Ee(this,"_queue",new Map)}getRealKey(t){return`${this._prefix}_${t}`}checkStorage(){i_()&&(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(i_())try{for(const[t,i]of this._queue)localStorage.setItem(t,JSON.stringify(i))}catch(t){jo.warn(t)}}getItem(t){if(!i_())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){jo.warn(i)}}setItem(t,i){if(i_())try{const r={expiresIn:Date.now()+pgA,value:i};this._queue.set(this.getRealKey(t),r)}catch(r){jo.warn(r)}}deleteItem(t){if(!i_())return!1;try{return t=this.getRealKey(t),this._queue.delete(t),localStorage.removeItem(t),!0}catch(i){return jo.warn(i),!1}}clear(){if(i_())try{localStorage.clear()}catch(t){jo.warn(t)}}},LX=new zcA,ZcA={};P3(ZcA,{HTTPS_API:()=>clA,IS_GET_CAPABILITIES_FROM_INPUTDEVICE_SUPPORTED:()=>ZX,IS_GET_CAPABILITIES_SUPPORTED:()=>zX,IS_GET_SETTINGS_SUPPORTED:()=>W1,IS_GET_SYNCHRONIZATION_SOURCES_SUPPORTED:()=>QlA,IS_INSERTABLE_STREAM_SUPPORTED:()=>XX,IS_JITTER_BUFFER_TARGET_SUPPORTED:()=>SlA,IS_RTC_RTP_SENDER_SUPPORTED:()=>aU,IS_SCRIPT_TRANSFORM_SUPPORTED:()=>$X,IS_SEI_SUPPORTED:()=>plA,IS_SPC_SUPPORTED:()=>dlA,basis:()=>flA,capabilityCheck:()=>ylA,checkSystemRequirementsInternal:()=>PX,decodeSupportStatus:()=>OX,detectH264SupportedByFakeStreaming:()=>xX,detectVideoCodecCapabilities:()=>MlA,detectVideoDecoderCapabilities:()=>s7,detectVideoEncoderCapabilities:()=>o7,encodeSupportStatus:()=>lW,getBrowserInfo:()=>ilA,getDisplayResolution:()=>YX,getH264ProfileLevelIds:()=>n7,isAddTransceiverSupported:()=>_Y,isBrowserSupported:()=>aW,isCanvasCaptureStreamAPISupported:()=>HX,isCanvasSmallStreamSupported:()=>qX,isGetReceiversSupported:()=>ulA,isGetSendersSupported:()=>WX,isGetTransceiversSupported:()=>ElA,isGetUserMediaSupported:()=>VX,isMediaDevicesSupported:()=>cW,isMediaSessionSupported:()=>e7,isMediaStreamTrackGeneratorSupported:()=>slA,isMediaStreamTrackProcessorSupported:()=>olA,isReplaceTrackSupported:()=>hlA,isRequestVideoFrameCallbackSupported:()=>EW,isSIMDSupported:()=>mlA,isScaleResolutionDownBySupported:()=>KX,isScreenCaptureApiAvailable:()=>IW,isSelectedCandidatePair:()=>llA,isSetParametersSupported:()=>BlA,isSetSinkIdSupported:()=>alA,isSmallStreamSupported:()=>jX,isStopTransceiverSupported:()=>ClA,isTRTCSupported:()=>rlA,isUnifiedPlanDefault:()=>IlA,isUsedInHttpProtocol:()=>wY,isWebAudioSupported:()=>JX,isWebCodecSupported:()=>A7,isWebCodecsSupported:()=>gW,isWebRTCSupported:()=>uW,isWebTransportSupported:()=>t7});var K1={PLAY_FAILED:"PLAY_FAILED",NOT_SUPPORTED_HTTP:"NOT_SUPPORTED_HTTP",MICROPHONE_NOT_FOUND:"MICROPHONE_NOT_FOUND",CAMERA_NOT_FOUND:"CAMERA_NOT_FOUND"},B_={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 u=`${t||i.name}`;let p="";return p=Array.isArray(i.type)?i.type.join("|"):i.type,`'${u}' must be type of ${p} when calling ${r}(), received type: ${gv(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: ${gv(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}.`},c8=(t,i)=>i?`${qj}/${t}/${i}`:`${qj}/${t}/index.html`,XcA=()=>{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(QgA);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 j1(t){const{key:i,data:r,link:l,addDocLink:u=!0}=t;let p="",y="",w="";ev(B_[i])?p=B_[i](r):HC(B_[i])&&(p=B_[i]);const{TRTC_ERROR_INFO:_,TRTC_ERROR_LINK:k}=XcA();l?w=`${l.className}.html#${l.fnName}`:k&&k[i]&&(ev(k[i])?w=k[i](r):HC(k[i])&&(w=k[i]));let F=p;return Gy()&&(_&&_[i]&&(ev(_[i])?y=_[i](r):HC(_[i])&&(y=_[i])),y&&(F=u?`${y} +请查看文档: ${c8("zh-cn",w)} + +`:`${y} + +`,F+=p)),u&&(F+=` +Refer to: ${c8("en",w)} +`),F}var l8=O_(ngA()),$cA=1,AlA=0,UX=class{constructor(t=!0){Ee(this,"countMap",new Map),Ee(this,"distributionMap",new Map),Ee(this,"version"),Ee(this,"log",jo.createLogger({id:"kv"})),t&&(Qs.on("102",({track:i,cost:r})=>{this.addSuccessEvent({key:i.kind===zt.AUDIO?501700:511700,cost:r})}),Qs.on("103",({track:i,error:r})=>{this.addFailedEvent({key:i.kind===zt.AUDIO?501700:511700,error:r})}),Qs.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:K9(this.version||P1),uint32_terminal_type:15,bytes_device_name:"",bytes_os_version:"",uint32_framework:30,uint32_network_type:0},stats_count:[...this.countMap.entries()].map(([l,u])=>({uint32_key:l,uint32_count:u})),stats_distribution:[...this.distributionMap.entries()].map(([l,u])=>({uint32_key:l,distribution_items:[...u.entries()].map(([p,y])=>({uint32_item_key:p,uint32_item_value:y}))})),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 u=((l=this.distributionMap)==null?void 0:l.get(t))||new Map;u.set(i,(u.get(i)||0)+1),this.distributionMap.set(t,u)}addNumber({key:t,value:i,split:r=100,useUV:l=!1,max:u=5e3}){var p;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>u&&(i=u),this.countMap.set(t,(this.countMap.get(t)||0)+1);const y=((p=this.distributionMap)==null?void 0:p.get(t))||new Map;let w=0;if(cv(r))w=Math.floor(i/r);else for(let _=r.length-1;_>0;_--)if(i>r[_]){w=_;break}y.set(w,(y.get(w)||0)+1),this.distributionMap.set(t,y)}addSuccessEvent({key:t,cost:i,timeKey:r,split:l}){if(t&&(this.addEnum({key:t,value:$cA,useUV:!1}),i)){const u=+String(t).slice(-3);u<800&&u>=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=Hg.UNKNOWN;i&&(cv(i)?r=i:$n(i.extraCode)&&$n(i.code)||(r=i.extraCode||i.code)),this.addEnum({key:t,value:AlA,useUV:!1}),this.addEnum({key:t,value:Math.abs(r),useUV:!1})}},FX=(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))(FX||{}),elA=new UX(!0);new UX(!1);var lr=elA,Zs={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}},tlA=new Map([[Kd,["Firefox",oX]],[DY,["Edg",rX]],[nW,["Chrome",MX]],[Ad,["Safari",rU]],[am,["TBS",cX]],[P_,["XWEB",lX]],[nU&&yY,["WeChat",IX]],[X3,["QQ(Win)",uX]],[MY,["QQ(Mobile)",J1]],[SY,["QQ(Mobile X5)",J1]],[$3,["QQ(Mac)",EX]],[AW,["QQ(iPad)",dX]],[eW,["MI",QX]],[tW,["HW",mX]],[iW,["Samsung",fX]],[RY,["OPPO",yX]],[oW,["VIVO",DX]],[sU,["EDGE",nX]],[z3,["SogouMobile",aX]],[Z3,["Sogou",gX]]]);function ilA(){const t=tlA.get(!0);return{browserName:t?t[0]:"unknown",browserVersion:t?t[1]:"unknown"}}var aW=function(){return!_cA&&!sU&&!(DY&&RcA<80)&&!(Kd&&sX<56)},gW=function(){return["VideoDecoder","VideoEncoder","AudioEncoder","AudioDecoder"].every(t=>t in window)},cW=function(){if(!navigator.mediaDevices)return wY()||jo.error(B_.NOT_SUPPORTED_MEDIA),!1;const t=["getUserMedia","enumerateDevices"];return t.filter(i=>i in navigator.mediaDevices).length===t.length},I8=!1;function wY(){return location.protocol==="http:"&&!q1&&(I8||jo.error(j1({key:K1.NOT_SUPPORTED_HTTP})),I8=!0,!0)}var olA=function(){return window?.OffscreenCanvas&&window?.MediaStreamTrackProcessor&&window?.MediaStreamTrackGenerator},slA=function(){return!!window?.MediaStreamTrackGenerator},lW=async function(){var t,i,r;if(Zs.detail.isH264EncodeSupported&&Zs.detail.isVp8EncodeSupported)return{isH264EncodeSupported:Zs.detail.isH264EncodeSupported,isVp8EncodeSupported:Zs.detail.isVp8EncodeSupported,isH265EncodeSupported:Zs.detail.isH265EncodeSupported};let l,u=!1,p=!1,y=!1;try{const w=new RTCPeerConnection,_=document.createElement(zt.CANVAS);_.getContext("2d");const k=_.captureStream(0);return w.addTrack(k.getVideoTracks()[0],k),l=await w.createOffer(),u=((t=l.sdp)==null?void 0:t.toLowerCase().indexOf("h264"))!==-1,p=((i=l.sdp)==null?void 0:i.toLowerCase().indexOf("vp8"))!==-1,y=((r=l.sdp)==null?void 0:r.toLowerCase().indexOf("h265"))!==-1,w.close(),{isH264EncodeSupported:u,isVp8EncodeSupported:p,isH265EncodeSupported:y}}catch{return{isH264EncodeSupported:!1,isVp8EncodeSupported:!1,isH265EncodeSupported:!1}}},OX=async function(){var t;if(Zs.detail.isH264DecodeSupported&&Zs.detail.isVp8DecodeSupported)return{isH264DecodeSupported:Zs.detail.isH264DecodeSupported,isVp8DecodeSupported:Zs.detail.isVp8DecodeSupported,isH265DecodeSupported:Zs.detail.isH265DecodeSupported};let i,r=!1,l=!1;try{const u=new RTCPeerConnection;_Y()?(u.addTransceiver(zt.VIDEO,{direction:"recvonly"}),i=await u.createOffer()):i=await u.createOffer({offerToReceiveVideo:!0}),i.sdp.toLowerCase().indexOf("h264")!==-1&&(r=!0),i.sdp.toLowerCase().indexOf("vp8")!==-1&&(l=!0);const p=((t=i.sdp)==null?void 0:t.toLowerCase().indexOf("h265"))!==-1;return u.close(),{isH264DecodeSupported:r,isVp8DecodeSupported:l,isH265DecodeSupported:p}}catch{return{isH264DecodeSupported:!1,isVp8DecodeSupported:!1,isH265DecodeSupported:!1}}};async function nlA(){const[t,i]=await Promise.all([lW(),OX()]);return{encode:{h264:t.isH264EncodeSupported,vp8:t.isVp8EncodeSupported,h265:t.isH265EncodeSupported},decode:{h264:i.isH264DecodeSupported,vp8:i.isVp8DecodeSupported,h265:i.isH265DecodeSupported}}}var PX=W9(async t=>{const i=Date.now(),r=uW(),l=cW(),u=gW();if(Zs.detail.isWebRTCSupported=r,Zs.detail.isMediaDevicesSupported=l,Zs.detail.isWebCodecsSupported=u,Zs.detail.isScreenShareSupported=IW(),Zs.detail.isSmallStreamSupported=jX(),t===37)return Object.assign(Zs.detail,await glA()),Zs.detail.isBrowserSupported=u,Zs.result=l&&u,Zs.result||jo.error(`${navigator.userAgent} ${$j(Zs.detail,!1)}`),d8(t),lr.addNumber({key:523800,value:Date.now()-i}),Zs;if(Zs.result&&Zs.detail.isH264EncodeSupported&&Zs.detail.isVp8EncodeSupported&&Zs.detail.isH265EncodeSupported&&Zs.detail.isH264DecodeSupported&&Zs.detail.isVp8DecodeSupported&&Zs.detail.isH265DecodeSupported)return Zs;const p=aW(),{encode:y,decode:w}=await nlA();let{h264:_,vp8:k}=y,{h264:F}=w;const{h265:j}=y,{vp8:lA,h265:aA}=w;if(!_||!k){const mA=await lW();jo.warn(`detect encode again h264:${_} vp8:${k} result: ${JSON.stringify(mA)}`),_=mA.isH264EncodeSupported,k=mA.isVp8EncodeSupported}if(_&&F&&Zd&&Fy&&!P_&&!am&&(!RY||Oy!==115)){const{encode:mA,decode:IA}=await xX();_=mA,F=IA}return Zs.result=p&&r&&l&&(_||k)&&(F||lA),Zs.detail.isBrowserSupported=p,Zs.detail.isWebRTCSupported=r,Zs.detail.isH264EncodeSupported=_,Zs.detail.isVp8EncodeSupported=k,Zs.detail.isH265EncodeSupported=j,Zs.detail.isH264DecodeSupported=F,Zs.detail.isVp8DecodeSupported=lA,Zs.detail.isH265DecodeSupported=aA,Zs.result||jo.error(`${navigator.userAgent} ${$j(Zs.detail,!1)}`),d8(),lr.addNumber({key:523800,value:Date.now()-i}),Zs}),rlA=function(){return Zs.result},IW=function(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia)},alA=typeof HTMLMediaElement<"u"&&"setSinkId"in HTMLMediaElement.prototype,u8=null;async function xX(t=2e3){return u8||(u8=new Promise(async i=>{const r={encode:!1,decode:!1};let l=()=>{};try{const u=document.createElement("canvas"),p=u.getContext("2d");u.width=640,u.height=480;const y=setInterval(()=>{p.fillText("test",Math.floor(640*Math.random()),Math.floor(480*Math.random()))},66);let w=-1,_=-1;l=()=>{clearInterval(w),clearInterval(y),clearTimeout(_),F.close(),j.close(),k.getTracks().forEach(tA=>tA.stop())},_=setTimeout(()=>{l(),i(r)},t);const k=u.captureStream(),F=new RTCPeerConnection({}),j=new RTCPeerConnection({offerToReceiveAudio:!0,offerToReceiveVideo:!0});F.addEventListener("icecandidate",tA=>j.addIceCandidate(tA.candidate)),j.addEventListener("icecandidate",tA=>F.addIceCandidate(tA.candidate)),F.addTrack(k.getVideoTracks()[0],k);const lA=await F.createOffer();await F.setLocalDescription(lA),await j.setRemoteDescription(lA);const aA=await j.createAnswer(),mA=l8.default.parse(aA.sdp),IA=mA.media[0].rtp.findIndex(tA=>tA.codec==="H264");mA.media[0].rtp=[mA.media[0].rtp[IA]],mA.media[0].fmtp=mA.media[0].fmtp.filter(tA=>tA.payload===mA.media[0].rtp[0].payload),mA.media[0].rtcpFb&&(mA.media[0].rtcpFb=mA.media[0].rtcpFb.filter(tA=>tA.payload===mA.media[0].rtp[0].payload)),aA.sdp=l8.default.write(mA),await j.setLocalDescription(aA),await F.setRemoteDescription(aA),w=setInterval(async()=>{r.encode&&r.decode&&(l(),i(r));const[tA,MA]=await Promise.all([F.getSenders()[0].getStats(),j.getReceivers()[0].getStats()]);r.encode||tA.forEach(PA=>{PA.type==="outbound-rtp"&&(PA.mediaType===zt.VIDEO||PA.kind===zt.VIDEO)&&PA.bytesSent>0&&(r.encode=!0)}),r.decode||MA.forEach(PA=>{PA.type==="inbound-rtp"&&(PA.mediaType===zt.VIDEO||PA.kind===zt.VIDEO)&&PA.bytesReceived>0&&(r.decode=!0)})},100)}catch(u){l(),jo.warn("detectH264Supported failed",u),i({encode:!0,decode:!0})}}).then(i=>(i.encode||(i.decode=!0),i.encode&&i.decode||jo.warn(`detectH264Supported encode: ${i.encode} decode: ${i.decode} ${OcA}`),i)))}var E8=null;async function glA(){return E8||(E8=new Promise(async t=>{const i={isH264EncodeSupported:!1,isH264DecodeSupported:!1,isVp8EncodeSupported:!1,isVp8DecodeSupported:!1};if(!gW())return void t(i);let r=null,l=null,u=null;const p=()=>{u&&clearTimeout(u),r=null,l=null};try{r=document.createElement("canvas"),l=r.getContext("2d"),r.width=320,r.height=240;let y=0;const w=()=>{l&&r&&(l.fillStyle=`hsl(${y%360}, 50%, 50%)`,l.fillRect(0,0,r.width,r.height),l.fillStyle="white",l.font="20px Arial",l.fillText(`Frame ${y}`,10,30),y++)};u=setTimeout(()=>{p(),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 k=>{const F={type:k.type,encodeSupported:!1,decodeSupported:!1};let j;try{j=await new Promise(async(lA,aA)=>{try{const mA=new VideoEncoder({output:tA=>{lA(tA),F.encodeSupported=!0},error:aA});mA.configure(k.encodeConfig),w();const IA=new VideoFrame(r,{timestamp:0});mA.encode(IA,{keyFrame:!0}),IA.close(),await mA.flush(),mA.close()}catch(mA){aA(mA)}})}catch(lA){return jo.warn(`${k.type} encoder error:`,lA),F}try{await new Promise(async(lA,aA)=>{try{const mA=new VideoDecoder({output:IA=>{F.decodeSupported=!0,lA(0),IA.close()},error:aA});mA.configure(k.decodeConfig),mA.decode(j),await mA.flush(),mA.close()}catch(mA){aA(mA)}})}catch(lA){jo.warn(`${k.type} decoder error:`,lA)}return F}))).forEach(k=>{k.type==="h264"?(i.isH264EncodeSupported=k.encodeSupported,i.isH264DecodeSupported=k.decodeSupported):k.type==="vp8"&&(i.isVp8EncodeSupported=k.encodeSupported,i.isVp8DecodeSupported=k.decodeSupported)}),p(),t(i)}catch(y){p(),jo.warn("detectWebCodecsSupported failed:",y),t(i)}}))}var clA=(t,i,r)=>{location.protocol!=="http:"||q1||(t[i]=()=>{throw new Bl({code:Hg.INVALID_OPERATION,message:B_.NOT_SUPPORTED_HTTP})})},llA=function(t){return!(t.type!=="candidate-pair"||!t.nominated||t.state!=="in-progress"&&t.state!=="succeeded")&&!(tv(t.selected)&&!t.selected)};function YX(){let t="";return screen.width&&(t+=`${screen.width?screen.width*window.devicePixelRatio:""} * ${screen.height?screen.height*window.devicePixelRatio:""}`),t}function VX(){return navigator.getUserMedia||navigator.mediaDevices&&navigator.mediaDevices.getUserMedia}function JX(){const t={isSupported:!1},i=["AudioContext","webkitAudioContext","mozAudioContext","msAudioContext"];for(let r=0;r=86,$X="RTCRtpScriptTransform"in window,plA=aU&&(XX||$X),uW=function(){return["RTCPeerConnection","webkitRTCPeerConnection","RTCIceGatherer"].filter(t=>t in window).length>0};function A7(){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 e7(){return"mediaSession"in navigator&&!$n(navigator.mediaSession.setActionHandler)}function t7(){return!$n(window.WebTransport)}function mlA(){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 flA(){const t={browser:`${iv.name}/${iv.version}`,os:_X(),displayResolution:YX(),isScreenShareSupported:IW(),isWebRTCSupported:uW(),isGetUserMediaSupported:VX(),isWebAudioSupported:JX(),isWebSocketsSupported:"WebSocket"in window&&window.WebSocket.CLOSING===2,isWebCodecSupported:A7(),isMediaSessionSupported:e7(),isWebTransportSupported:t7()};return navigator.userAgent.includes("miniProgram")&&(t.browser=`mini/${t.browser}`),t}var i7="checkResult";function d8(t=30){LX.setItem(i7+t,{ua:navigator.userAgent,checkResult:Zs})}function ylA(t){wY();const i=LX.getItem(i7+t);i&&i.ua===navigator.userAgent&&i.checkResult&&DlA(i.checkResult.detail,Zs.detail)&&(Zs=i.checkResult),PX(t)}function DlA(t,i){return!!zM(t)&&Object.keys(i).every(r=>r in t)}function EW(){return"requestVideoFrameCallback"in HTMLVideoElement.prototype}var SlA="RTCRtpReceiver"in window&&"jitterBufferTarget"in window.RTCRtpReceiver.prototype;function C8(t){return{h264:1,h265:2,vp8:3,vp9:4,av1:5}[t]}var h8=!1;async function MlA(){var t;try{if(h8||!((t=navigator?.mediaCapabilities)!=null&&t.encodingInfo))return;const i=rW(),r=xcA();if(i===0||r===0)return;h8=!0;const l=["H264","VP8","VP9","AV1","H265"],[u,p]=await Promise.all([o7(l),s7(l)]);u&&Object.keys(u).forEach(_=>{const k=C8(_.toLowerCase());lr.addEnum({key:513707,value:+`${k}${+u[_].supported}${+u[_].powerEfficient}${i}${r}`,useUV:!1})}),p&&Object.keys(p).forEach(_=>{const k=C8(_.toLowerCase());lr.addEnum({key:514713,value:+`${k}${+p[_].supported}${+p[_].powerEfficient}${i}${r}`,useUV:!1})});const{sender:y,receiver:w}=n7();lr.addEnum({key:513708,value:+`${i}${r}${+y.high}`,useUV:!1}),lr.addEnum({key:513709,value:+`${i}${r}${+y.main}`,useUV:!1}),lr.addEnum({key:514714,value:+`${i}${r}${+w.high}`,useUV:!1}),lr.addEnum({key:514715,value:+`${i}${r}${+w.main}`,useUV:!1})}catch(i){jo.info("detectVideoCodecCapabilities failed",i)}}async function o7(t,i=1920,r=1080,l=30,u=3e3){const p={};try{for(const y of t){const w=await navigator.mediaCapabilities.encodingInfo({type:"webrtc",video:{contentType:`video/${y}`,width:i,height:r,bitrate:u,framerate:l}});p[y]=w}}catch{}return p}async function s7(t,i=1920,r=1080,l=30,u=3e3){const p={};try{for(const y of t){const w=await navigator.mediaCapabilities.decodingInfo({type:"webrtc",video:{contentType:`video/${y}`,width:i,height:r,bitrate:u,framerate:l}});p[y]=w}}catch{}return p}function n7(){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){jo.warn("get H264 profile levelId failed",i)}return t}var vlA=O_(iU()),B8=Symbol("instance"),e1=Symbol("cacheResult"),oj=class{constructor(t,i,r){this.oldState=t,this.newState=i,this.action=r,this.aborted=!1}abort(t){this.aborted=!0,vL.call(t,this.oldState,new Error(`action '${this.action}' aborted`))}toString(){return`${this.action}ing`}},sj=class extends Error{constructor(t,i,r){super(i),this.state=t,this.message=i,this.cause=r}};function RlA(t){return typeof t=="object"&&t&&"then"in t}var ML=new Map;function du(t,i,r={}){return(l,u,p)=>{const y=r.action||u;if(!r.context){const _=ML.get(l)||[];ML.has(l)||ML.set(l,_),_.push({from:t,to:i,action:y})}const w=p.value;p.value=function(..._){let k=this;if(r.context&&(k=Xn.get(typeof r.context=="function"?r.context.call(this,..._):r.context)),k.state===i)return r.sync?k[e1]:Promise.resolve(k[e1]);k.state instanceof oj&&k.state.action==r.abortAction&&k.state.abort(k);let F=null;Array.isArray(t)?t.length==0?k.state instanceof oj&&k.state.abort(k):typeof k.state=="string"&&t.includes(k.state)||(F=new sj(k._state,`${k.name} ${y} to ${i} failed: current state ${k._state} not from ${t.join("|")}`)):t!==k.state&&(F=new sj(k._state,`${k.name} ${y} to ${i} failed: current state ${k._state} not from ${t}`));const j=tA=>{if(r.fail&&r.fail.call(this,tA),r.sync){if(r.ignoreError)return tA;throw tA}return r.ignoreError?Promise.resolve(tA):Promise.reject(tA)};if(F)return j(F);const lA=k.state,aA=new oj(lA,i,y);vL.call(k,aA);const mA=tA=>{var MA;return k[e1]=tA,aA.aborted||(vL.call(k,i),(MA=r.success)===null||MA===void 0||MA.call(this,k[e1])),tA},IA=tA=>(vL.call(k,lA,tA),j(tA));try{const tA=w.apply(this,_);return RlA(tA)?tA.then(mA).catch(IA):r.sync?mA(tA):Promise.resolve(mA(tA))}catch(tA){return IA(new sj(k._state,`${k.name} ${y} from ${t} to ${i} failed: ${tA}`,tA instanceof Error?tA:new Error(String(tA))))}}}}var wlA=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 vL(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 FC extends vlA.default{constructor(i,r,l){super(),this.name=i,this.groupName=r,this._state=FC.INIT,i||(i=Date.now().toString(36)),l?Object.setPrototypeOf(this,l):l=Object.getPrototypeOf(this),r||(this.groupName=this.constructor.name);const u=l[B8];u?this.name=u.name+"-"+u.count++:l[B8]={name:this.name,count:0},this.updateDevTools({diagram:this.stateDiagram})}get stateDiagram(){const i=Object.getPrototypeOf(this),r=ML.get(i)||[];let l=new Set,u=[],p=[];const y=new Set,w=Object.getPrototypeOf(i);ML.has(w)&&(w.stateDiagram.forEach(k=>l.add(k)),w.allStates.forEach(k=>y.add(k))),r.forEach(({from:k,to:F,action:j})=>{typeof k=="string"?u.push({from:k,to:F,action:j}):k.length?k.forEach(lA=>{u.push({from:lA,to:F,action:j})}):p.push({to:F,action:j})}),u.forEach(({from:k,to:F,action:j})=>{y.add(k),y.add(F),y.add(j+"ing"),l.add(`${k} --> ${j}ing : ${j}`),l.add(`${j}ing --> ${F} : ${j} 🟢`),l.add(`${j}ing --> ${k} : ${j} 🔴`)}),p.forEach(({to:k,action:F})=>{l.add(`${F}ing --> ${k} : ${F} 🟢`),y.forEach(j=>{j!==k&&l.add(`${j} --> ${F}ing : ${F}`)})});const _=[...l];return Object.defineProperties(i,{stateDiagram:{value:_},allStates:{value:y}}),_}static get(i){let r;return typeof i=="string"?(r=FC.instances.get(i),r||FC.instances.set(i,r=new FC(i,void 0,Object.create(FC.prototype)))):(r=FC.instances2.get(i),r||FC.instances2.set(i,r=new FC(i.constructor.name,void 0,Object.create(FC.prototype)))),r}static getState(i){var r;return(r=FC.get(i))===null||r===void 0?void 0:r.state}updateDevTools(i={}){wlA(FC.UPDATEAFSM,Object.assign({name:this.name,group:this.groupName},i))}get state(){return this._state}set state(i){vL.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 dW=typeof window<"u",Q8=dW&&window.requestIdleCallback||function(t){const i=Date.now();return setTimeout(()=>{t({didTimeout:!1,timeRemaining:()=>Math.max(0,50-(Date.now()-i))})},1e3)},_lA=dW&&window.cancelIdleCallback||function(t){clearTimeout(t)},p8=dW&&(window.cancelAnimationFrame||window.mozCancelAnimationFrame),nL=class rE{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 u=zh(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(u.taskID,u),this[i](u),u.taskID}static interval(i){return i.intervalID=setInterval(()=>{i.callback(),i.loopCount+=1,rE.isBreakLoop(i)},i.delay)}static intervalInWorker(i){rE.sharedWorker||(rE.sharedWorker=new Worker(URL.createObjectURL(new Blob([` + const timers = new Map(); + self.onmessage = function(e) { + const { taskId, delay, type } = e.data; + if (type === 'start') { + timers.set(taskId, setInterval(() => { + self.postMessage({ type: 'tick', taskId }); + }, delay)); + } else if (type === 'stop') { + clearInterval(timers.get(taskId)); + timers.delete(taskId); + } + }; + `],{type:"application/javascript"}))),rE.sharedWorker.onmessage=r=>{var l;if(r.data.type==="tick"){const u=rE.workerTasks.get(r.data.taskId);u&&(rE.isBreakLoop(u)?((l=rE.sharedWorker)==null||l.postMessage({type:"stop",taskId:u.taskID}),rE.workerTasks.delete(u.taskID)):(u.callback(),u.loopCount+=1))}}),rE.workerTasks.set(i.taskID,i),rE.sharedWorker.postMessage({taskId:i.taskID,delay:i.delay,type:"start"})}static timeout(i){const r=()=>{if(i.callback(),i.loopCount+=1,!rE.isBreakLoop(i))return i.timeoutID=setTimeout(r,i.delay)};return i.timeoutID=setTimeout(r,i.delay)}static ric(i){let r,l=Pc();const u=()=>{if(r=Pc()-l,r>=i.delay&&(l=Pc()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!rE.isBreakLoop(i))return i.ricID=Q8(u,{timeout:i.delay})};return i.ricID=Q8(u,{timeout:i.delay})}static raf(i){let r,l=Pc();const u=()=>{if(document.hidden&&i.backgroundTask)return r=Pc()-l,l=Pc(),i.callback(),i.loopCount+=1,rE.isBreakLoop(i)?void 0:i.timeoutID=setTimeout(u,i.delay-Math.floor(r%i.delay));if(r=Pc()-l,r>=i.delay&&(l=Pc()-Math.floor(r%i.delay),i.callback(),i.loopCount+=1),!rE.isBreakLoop(i))return i.rafID=requestAnimationFrame(u)};if(i.rafID=requestAnimationFrame(u),i.backgroundTask){const p=()=>{if(document.hidden){const y=Pc()-l;y>=i.delay?u():i.timeoutID=setTimeout(u,i.delay-y)}};document.addEventListener("visibilitychange",p),i.onVisibilitychange=p,document.hidden&&p()}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:u,ricID:p,onVisibilitychange:y}=this.taskMap.get(i);return r&&clearInterval(r),l&&clearTimeout(l),u&&p8&&p8(u),p&&_lA(p),y&&document.removeEventListener("visibilitychange",y),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)}};Ee(nL,"taskMap",new Map),Ee(nL,"currentTaskID",1),Ee(nL,"sharedWorker",null),Ee(nL,"workerTasks",new Map);var TlA=nL,uQ=TlA,Vn={LOAD_START:zt.LOADSTART,LOADED_DATA:zt.LOADEDDATA,LOADED_META_DATA:zt.LOADEDMETADATA,MEDIA_TRACK_CHANGED:"media-track-changed",PLAYER_STATE_CHANGED:"player-state-changed",ERROR:"error",AUTOPLAY_FAILED:"autoplay-failed",RESIZE:zt.RESIZE,TIME_UPDATE:"time-update",LEAVE_PICTURE_IN_PICTURE:zt.LEAVE_PICTURE_IN_PICTURE,ENTER_PICTURE_IN_PICTURE:zt.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"},t3={};P3(t3,{create:()=>CW,remove:()=>VL});var RL=new WeakMap;function CW(t,i){RL.has(t)||RL.set(t,[]);const r=RL.get(t),l={add:(u,p)=>("addEventListener"in i?(r.push(i.removeEventListener.bind(i,u,p)),i.addEventListener(u,p)):(r.push(i.off.bind(i,u,p)),i.on(u,p)),l)};return l}function VL(t){const i=RL.get(t);i&&(i.forEach(r=>r()),RL.delete(t))}var NlA=class{constructor(){Ee(this,"_roomIdMap",new Map),Ee(this,"_configs"),typeof registerProcessor>"u"&&(this._configs={sdkAppId:"",userId:"",version:P1,env:zK.QCLOUD,browserVersion:iv.name+iv.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){!q1&&jo.isAbleToUpload&&this._configs.env===zK.QCLOUD&&this.uploadEventToKibana(zh(Rn({},t),{result:"success"}))}logFailedEvent(t){if(q1||!jo.isAbleToUpload)return;const{eventType:i,code:r,error:l,userId:u}=t,p={roomId:this._roomIdMap.get(u||this._configs.userId),userId:u,eventType:i,result:"failed",code:r||l?.extraCode||l?.code||Hg.UNKNOWN};this._configs.env===zK.QCLOUD&&this.uploadEventToKibana(zh(Rn({},p),{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:T9(),sdkAppId:this._configs.sdkAppId,userId:i||this._configs.userId,version:P1,log:t};r&&(l.errorInfo=r.message,r.stack&&(l.errorInfo+=` +${r.stack}`));const u=e3.enable?q3(l,2002,Number(this._configs.sdkAppId)):JSON.stringify(l);this.sendRequest(V3(this._configs.sdkAppId,b9.LOG),u)}sendRequest(t,i){setTimeout(()=>AX({url:t,body:i,priority:"low"}).catch(()=>{}),2e3)}},qC=new NlA,PM=new WeakMap;function GlA({settings:t={retries:5,timeout:2e3},onError:i,onRetrying:r,onRetryFailed:l}){return function(u,p,y){const w=j3({retryFunction:y.value,settings:t,onError({error:_,retry:k,reject:F,retryFuncArgs:j}){var lA;i?i.call(this,_,()=>{var aA;(aA=PM.get(u))!=null&&aA.has(p)?k():F(_)},F,j):(lA=PM.get(u))!=null&&lA.has(p)?k():F(_)},onRetrying(_,k){var F;u_(r)&&r.call(this,_,k),(F=PM.get(u))!=null&&F.has(p)&&(PM.get(u).get(p).stopRetry=k)},onRetryFailed:l});return y.value=function(..._){const k=PM.get(u);return k?k.set(p,{args:_}):PM.set(u,new Map([[p,{args:_}]])),w.apply(this,_).finally(()=>{var F;return(F=PM.get(u))==null?void 0:F.delete(p)})},y}}var HM=class extends Xn{constructor(t,i){super(t.id,`${i}-player`),this.options=t,this.kind=i,Ee(this,"id"),Ee(this,"element",null),Ee(this,"track"),Ee(this,"url"),Ee(this,"attr"),Ee(this,"mode"),Ee(this,"muted"),Ee(this,"_log"),Ee(this,"isPausedByUserCall",!1),Ee(this,"_pausedRetryCount"),Ee(this,"_isElementPlayingFired",!1),Ee(this,"_interval"),Ee(this,"_delayDestroyTimeoutId",0),Ee(this,"_playSuccessResolve"),Ee(this,"_isReplayByRecreateMediaStreamCalled",!1),Ee(this,"isPlayCalled",!1),Ee(this,"isInAutoPlayFailedState",!1),Ee(this,"isBindAutoPlayEvent",!1),this.id=t.id,this._log=t.log,this.track=t.track,this.muted=t.muted,this._pausedRetryCount=I_,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=j1({key:K1.PLAY_FAILED,data:{media:this.kind,error:t}});if(this._log.warn(t),i.includes("NotAllowedError"))throw this.isInAutoPlayFailedState=!0,new Bl({code:Hg.PLAY_NOT_ALLOWED,message:i})}}stop(t=0){var i;this.isPlayCalled=!1,this.isPausedByUserCall=!1,this._isElementPlayingFired=!1,this.unbindEvents(),t>0&&!vX?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(zt.ENDED),this._interval>0&&uQ.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():bcA?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 CW(this.element,this.element).add(zt.PLAYING,t).add(zt.ENDED,t).add(zt.PAUSE,t).add(zt.ERROR,t).add(zt.LOADSTART,t).add(zt.LOADEDDATA,t).add(zt.LOADEDMETADATA,t)}}bindTrackEvents(t=this.track){if(t){const i=this.handleTrackEvent.bind(this);t3?.create(t,t).add(zt.ENDED,i).add(zt.MUTE,i).add(zt.UNMUTE,i),t.readyState===zt.ENDED&&this.handleTrackEvent({type:zt.ENDED}),t.muted&&this.handleTrackEvent({type:zt.MUTE})}}bindAutoPlayEvent(){this.isBindAutoPlayEvent||(this._log.warn("bindAutoPlayEvent"),Qs.on(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!0)}unbindTrackEvents(t=this.track){t&&VL(t)}unbindEvents(){this.element&&VL(this.element),this.unbindTrackEvents(),Qs.off(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM,this.resume,this),this.isBindAutoPlayEvent=!1}handleElementEvent(t){switch(t.type){case zt.PLAYING:JL()||(this.isInAutoPlayFailedState=!1),this._isElementPlayingFired=!0,this._log.info(`${this.kind} player is playing`),this.handlePlaying(zt.PLAYING),this._interval&&(uQ.clearTask(this._interval),this._interval=-1);break;case zt.ENDED:this._log.info(`${this.kind} player is ended`),this.handleStopped(zt.ENDED);break;case zt.PAUSE:this._log.info(`${this.kind} player is paused`),this.handlePaused(zt.PAUSE);break;case zt.ERROR:if(this.element&&this.element.error){this.handlePaused(zt.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}`),qC.uploadEvent({log:`stat-${this.kind}-${yL.PLAYER_ERROR}-${i}-${navigator.userAgent}`,error:this.element.error}),TcA||pX?this.emit(Vn.ERROR,this.element.error):this.replayByRecreateMediaStream(this.element.error)}break;case zt.LOADEDDATA:this.kind===zt.VIDEO&&this.emit(Vn.LOADED_DATA);break;case zt.LOADEDMETADATA:this.kind===zt.VIDEO&&this.emit(Vn.LOADED_META_DATA);break;case zt.LOADSTART:this.emit(Vn.LOAD_START)}}replayByRecreateMediaStream(t){if(!this._isReplayByRecreateMediaStreamCalled)return this._isReplayByRecreateMediaStreamCalled=!0,this.doReplayByRecreateMediaStream(1e3).then(()=>{this._log.warn("replayByRecreateMediaStream success"),qC.uploadEvent({log:"stat-replayByRecreateMediaStream-success"}),lr.addSuccessEvent({key:this.kind===zt.AUDIO?506700:516700})}).catch(()=>{var i;this._log.error("replayByRecreateMediaStream failed"),qC.uploadEvent({log:"stat-replayByRecreateMediaStream-failed"}),lr.addFailedEvent({key:this.kind===zt.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)=>{G_(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,u,p;this._log.warn(`element onerror ${(u=(l=this.element)==null?void 0:l.error)==null?void 0:u.code} fired after recreated mediaStream`),r((p=this.element)==null?void 0:p.error)}),G_(5e3).then(()=>{var l,u;this.isPlaying&&!((l=this.element)!=null&&l.error)||r((u=this.element)==null?void 0:u.error),i()})})}).finally(()=>{this.element&&(this.element.onerror=null)})}async handleTrackEvent(t){const i=t.type;switch(this.options.enableLogTrackState&&this._log[i===zt.UNMUTE?"info":"warn"](`track ${i}`),i){case zt.ENDED:this.handleStopped(zt.ENDED);break;case zt.MUTE:this.handlePaused(zt.MUTE);break;case zt.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(zt.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}};Ee(HM,"PlayerEvent",Vn),dc([GlA({settings:{retries:2,timeout:0},onError(t,i,r,l){l[0]=(l[0]||1e3)+1e3,i()}})],HM.prototype,"doReplayByRecreateMediaStream"),dc([du([],"PLAYING",{sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PLAYING",reason:t})}})],HM.prototype,"handlePlaying"),dc([du("PLAYING","PAUSED",{ignoreError:!0,sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"PAUSED",reason:t})}})],HM.prototype,"handlePaused"),dc([du([],"STOPPED",{sync:!0,success(t){this.emit(Vn.PLAYER_STATE_CHANGED,{type:this.kind,state:"STOPPED",reason:t})}})],HM.prototype,"handleStopped");var gm="trtc_autoplay",nj=`${gm}_mask`,jk=`${gm}_wrapper`,m8=`${gm}_header`,rj=`${gm}_content`,t1=`${gm}_action_wrapper`,aj=`${gm}_question`,gj=`${gm}_collapse`,i1=`${gm}_action_confirm`,f8=`${gm}_detail`,y8="#2473E8",hW="dialog",blA=`${hW}-show`,klA=`${hW}-1`,LlA=`${hW}-2`,D8=!1,i3=!1,JL=()=>i3,r7=`${qj}/${Gy()?"zh-cn":"en"}/tutorial-21-advanced-auto-play-policy.html`,S8=`
${Gy()?"其他方案?":"Any other solution?"}`,UlA=Gy()?`浏览器自动播放策略:在用户与页面产生交互(点击、触摸)之前,浏览器禁止播放有声媒体。该弹窗用于帮助用户恢复音视频播放。${S8}`:`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. ${S8}`,FlA=class{constructor(){if(Ee(this,"content","音视频播放被浏览器拦截,请点击“恢复播放”。"),Ee(this,"_dialogNode",null),Ee(this,"_bodyPosition",""),Ee(this,"_showDetail",!1),Ee(this,"_isCollapseClicked",!1),Ee(this,"_isQuestionClicked",!1),Gy()||(this.content='Media playback failed. Click the "Resume" to resume playback.'),!D8){const t=document.createElement("style");t.innerHTML=`.${nj}{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;}.${nj} div:not(.${t1}){display:block !important;}.${jk}{padding:14px;background:#fff;border-radius:3px;box-shadow:0px 3px 15px #434343;border:1px solid #d1cfcf;max-width:500px;}.${jk} a{color:${y8};}.${m8}{overflow:hidden;text-overflow:ellipsis;font-size:16px;font-weight:600;}.${rj}{margin:8px 0;}.${t1}{width:100%;display:flex !important;align-items:center;justify-content:right;float:right;}.${gj}{margin-right:auto;cursor:pointer}.${aj}{height:100%;line-height:16px;cursor:pointer;}.${i1}{margin-left:8px;color:#fff;background:${y8};padding:4px 12px;outline:none;border:1px solid;border-radius:3px;font-weight:bold;}.${i1}:hover{opacity:0.9;}.${gj},.${i1},.${rj},.${aj}{font-size:14px;}@media screen and (max-width:750px){.${jk}{width:80vw;}}`,document.head.appendChild(t),D8=!0}this.addDiaLog()}createDiaLog(){const t=document.createElement("template");t.innerHTML=`
${location.host}
${this.content}
`.trim();const i=document.createElement("button");i.className=i1,i.innerText=Gy()?"恢复播放":"Resume",i.onclick=this.onConfirm.bind(this);const r=document.createElement("div");r.className=aj,r.innerHTML=` + + + + + + `,r.onclick=this.onQuestionClick.bind(this);const l=document.createElement("div");l.className=gj,l.innerText=Gy()?"详情 >":"Detail >",l.onclick=this.onCollapseClick.bind(this);const u=t.content.firstChild,p=u.querySelector(`.${t1}`);return p.appendChild(l),p.appendChild(r),p.appendChild(i),u}addDiaLog(){JL()||(i3=!0,this._dialogNode=this.createDiaLog(),document.body.appendChild(this._dialogNode),this._dialogNode.onclick=this.onConfirm.bind(this),this._dialogNode.querySelector(`.${jk}`).onclick=t=>t.stopPropagation(),this._bodyPosition=document.body.style.position,document.body.style.position="fixed",jo.info("show autoplay dialog"),qC.uploadEvent({log:blA}))}deleteDialog(){this._dialogNode&&(document.body.removeChild(this._dialogNode),document.body.style.position=this._bodyPosition,this._dialogNode=null,i3=!1),HL=null}onConfirm(){jo.warn("confirm clicked, try resume stream"),Qs.emit(mn.AUTOPLAY_DIALOG_CLICK_CONFIRM),this.deleteDialog()}onCollapseClick(){const t=this._dialogNode.querySelector(`.${f8}`);t.style.visibility=this._showDetail?"hidden":"visible",t.style.height=`${this._showDetail?0:"fit-content"}`,this._showDetail=!this._showDetail,this._isCollapseClicked||qC.uploadEvent({log:klA}),this._isCollapseClicked=!0}onQuestionClick(){window.open(r7,"_blank"),this._isQuestionClicked||qC.uploadEvent({log:LlA}),this._isQuestionClicked=!0}},HL=null;function OlA(){HL||(HL=new FlA)}function PlA(){HL&&HL.deleteDialog()}var wL,Ry=class extends HM{constructor(t){super(t,zt.VIDEO),Ee(this,"stat",{}),Ee(this,"_calculateTimeout",-1),Ee(this,"viewMirror",!1),Ee(this,"objectFit","cover"),Ee(this,"container"),Ee(this,"canvas"),Ee(this,"shouldRenderAlpha",!1),Ee(this,"_preSize",{width:0,height:0}),Ee(this,"posterImg"),Ee(this,"pipWindow"),Ee(this,"enterPIPPromise"),Ee(this,"_originContainerPosition"),Ee(this,"_isResettingSrcObject",!1),Ee(this,"_wrapper",null),Ee(this,"_useWrapper",!1),Ee(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(zt.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,Zd&&(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=I_,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(zt.ENTER_PICTURE_IN_PICTURE,this.handleElementEvent).add(zt.LEAVE_PICTURE_IN_PICTURE,this.handleElementEvent).add(zt.RESIZE,this.handleElementEvent),this.element&&(this.element.addEventListener(zt.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===zt.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,u,p,y;if(this.mode===2)return;super.handleElementEvent(t);const w=t.type,_=this.isPictureInPicture(),k=this.isFullscreen(),F=t.isTrusted&&(_&&Ad||k);if(w===zt.PLAYING&&F&&!this._isResettingSrcObject&&(this._log.warn("user resume in "+(k?"fullscreen":"pip")),this.emit(Vn.USER_RESUME_IN_PIP_OR_FULL_SCREEN)),w===zt.PAUSE&&(F&&(this._log.warn("user pause in "+(k?"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}`),G_(500).then(()=>{var j;(j=this.container)!=null&&j.isConnected&&(this._pausedRetryCount=I_,this._log.info(`view container ${this.container.id} is in dom, reset pausedRetryCount`))})),this._pausedRetryCount>0&&!JL()&&!this.isPausedByUserCall&&!F&&(this._log.info(`[${I_-this._pausedRetryCount+1}/${I_}] ${this.kind} player auto resume when paused`),this.doResume(),this._pausedRetryCount--),hu&&!F&&(this._interval=uQ.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===zt.ENTER_PICTURE_IN_PICTURE?this.element.style.transform=j.replace("scaleX(-1)",""):w!==zt.LEAVE_PICTURE_IN_PICTURE||j.includes("scaleX")||(this.element.style.transform=`${j} scaleX(-1)`)}w===zt.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${(u=this.element)==null?void 0:u.videoHeight}`),this._preSize.height=((p=this.element)==null?void 0:p.videoHeight)||0,this._preSize.width=((y=this.element)==null?void 0:y.videoWidth)||0,this.emit(Vn.RESIZE,{newWidth:this._preSize.width,newHeight:this._preSize.height}))),w===zt.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===zt.ENTER_PICTURE_IN_PICTURE&&this.emit(Vn.ENTER_PICTURE_IN_PICTURE)}resetSrcObjectToReplay(){Zd&&ij&&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&&(Ad||Kd))))return r();if(t==="")return this.removePosterImg(),r();if(this.posterImg)return r();const l=document.createElement("img");l.src=t;const u=window.getComputedStyle(this.element),p=u.objectFit||this.objectFit;let y=1;if(this._useWrapper){const w=parseInt(u.zIndex,10);isNaN(w)||(y=w+1)}l.style.cssText=this._useWrapper?`grid-area:1/1;z-index:${y};width:100%;height:100%;object-fit:${p};`:`position:absolute;top:0;left:0;width:100%;height:100%;object-fit:${p};`,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),V1()&&lv<=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&&(V1()&&lv<=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||!(ij||t&&(Kd||Ad))||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&&ij&&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(zt.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(EW()&&this.element&&this._calculateTimeout<0){let t=0,i=null;const r=(l,u)=>{this.stat.width=u.width,this.stat.height=u.height,i&&(this.stat.fps=Math.round((u.presentedFrames-i.presentedFrames)/(l-t)*1e3)),t=l,i=u,this._calculateTimeout=-1,this.element&&(this._calculateTimeout=setTimeout(()=>{var p;return(p=this.element)==null?void 0:p.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(hu&&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=I_,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 xlA(t,i){if(!t.audioWorklet)return Promise.reject("audioWorklet is not supported");try{await t.audioWorklet.addModule(i),jo.info("worklet addModule success")}catch(r){throw jo.info(`worklet addModule catch error. ${r.message}`),r}}typeof AudioContext<"u"?wL=AudioContext:typeof webkitAudioContext<"u"?wL=webkitAudioContext:typeof mozAudioContext<"u"&&(wL=mozAudioContext);var Eu,YlA=1500,M8=-1,o1=0,_L=-1,o3=!1,v8=0,R8=-1,w8=-1;function a7(){try{if(Eu)return;(Eu=new wL({sampleRate:48e3})).onstatechange=()=>{jo.info(`context state: ${Eu.state}${Eu.state!=="running"?` visibilityState: ${document.visibilityState}`:""}`),w_()},clearTimeout(M8)}catch(t){jo.error(`initAudioContext failed: ${t} typeof AudioContextClass: ${typeof wL}`),M8=setTimeout(a7,1e3)}}a7();var w_=()=>{Eu.state==="suspended"?(o1=Pc(),VlA(),z1(),document.addEventListener("click",w_)):Eu.state==="interrupted"?z1():(o1&&(lr.addNumber({key:507800,value:Pc()-o1,split:[0,500,1e3,1500,2e3,3e3,4e3,5e3,1e4,3e4],max:6e4}),o1=0),JlA(),document.removeEventListener("visibilitychange",w_),document.removeEventListener("click",w_))},cj=0,lj=-1;function z1(){return new Promise((t,i)=>{if(Eu.state==="running")return t();Date.now()-cj<1e3?(clearTimeout(lj),lj=setTimeout(()=>{cj=Date.now(),Eu.resume().then(t,i)},1e3)):(clearTimeout(lj),cj=Date.now(),Eu.resume().then(t,i))}).catch(t=>{jo.warn(`context resume failed: ${t}`),document.addEventListener("visibilitychange",w_)})}function VlA(){_L===-1&&(_L=setTimeout(()=>{Eu.state==="suspended"&&(o3=!0,Qs.emit("155",{isSuspended:!0}))},YlA))}function JlA(){_L!==-1&&(clearTimeout(_L),_L=-1,o3&&(o3=!1,Qs.emit("155",{isSuspended:!1})))}function HlA(){if(!hu||w8!==-1)return;const t=()=>{Pc()-v8<500||(Eu&&Eu.state==="running"&&Eu.currentTime===R8&&(jo.warn("context is fake running, auto resume"),Eu.suspend().catch(i=>{jo.warn(`context suspend failed: ${i}`)})),R8=Eu.currentTime,v8=Pc())};w8=setInterval(()=>{t()},2e3),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&t()})}document.addEventListener("click",w_);var Py=t=>Eu,ov=class{constructor(t){this.name=t,Ee(this,"node"),Ee(this,"node2"),Ee(this,"pre",new Set),Ee(this,"next",new Set),Ee(this,"context"),Ee(this,"connectedNodes",new Set),Ee(this,"nextInputChannelMap",new Map),Ee(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){jo.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(),lr.addSuccessEvent({key:502701})}catch(l){jo.error(l),lr.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(),lr.addSuccessEvent({key:502702})}catch(i){jo.error(i),lr.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}},qlA=class extends ov{constructor(t=256){super(),this.fftSize=t,Ee(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 u=0;uthis.initAudioWorklet()).catch(i=>(this._log.error(`volumeMeter preload error: ${i}`),this.initScriptProcessor()))}initAudioWorklet(){if(!this._audioWorkletNode)try{this._audioWorkletNode=new AudioWorkletNode(Zp.audioContext,"volume-meter");let i=!1;this._audioWorkletNode.port.onmessage=r=>{Zp.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}`),qC.logFailedEvent({userId:this._log.userId,eventType:yL.LOAD_WORKLET,error:i}),this.initScriptProcessor()}}initScriptProcessor(){if(!this._scriptProcessorNode)try{this._scriptProcessorNode=Py("volume-meter").createScriptProcessor(2048,1,1),this._scriptProcessorNode.onaudioprocess=i=>{Zp.lastMessageTime=Date.now();const r=i.inputBuffer.getChannelData(0);let l=0;for(let u=0;u>2);t.copyTo(r,{planeIndex:0}),this.node.port.postMessage({name:"chunk",data:r},[r.buffer]),t.close()}}},zlA=O_(iU()),N8=t=>i=>i.deviceId===t,Ij=class{constructor(t,i){Ee(this,"kind"),Ee(this,"type"),Ee(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&&g7(this.devices[0])||i&&(r.forEach(l=>{if(l.deviceId&&!this.devices.find(N8(l.deviceId))){const u=`${this.kind}${this.type}Added`;jo.warn(`${u}: ${JSON.stringify(l)}`),i.emit(u,l)}}),this.devices.forEach(l=>{if(l.deviceId&&!r.find(N8(l.deviceId))){const u=`${this.kind}${this.type}Removed`;jo.warn(`${u}: ${JSON.stringify(l)}`),i.emit(u,l)}})),this.devices=r}hasDevice(t){return!!this.devices.find(i=>i.deviceId===t)}},ZlA=class extends zlA.EventEmitter{constructor(){super(),Ee(this,"audioInputs",new Ij(zt.AUDIO,"Input")),Ee(this,"videoInputs",new Ij(zt.VIDEO,"Input")),Ee(this,"audioOutputs",new Ij(zt.AUDIO,"Output")),this.init(),navigator.mediaDevices&&(navigator.mediaDevices.addEventListener&&navigator.mediaDevices.addEventListener("devicechange",()=>this.update()),"ondevicechange"in navigator.mediaDevices||uQ.run("interval",()=>{this.update()},{delay:1e4}))}init(){s3().then(t=>{this.audioInputs.update(t),this.videoInputs.update(t),this.audioOutputs.update(t)})}async update(t=0){const i=await s3(t);return this.audioInputs.update(i,this),this.videoInputs.update(i,this),this.audioOutputs.update(i,this),this}hasBlueTooth(){var t;if(1e3*((t=Py())==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)))}},lQ=G9||N9?null:new ZlA;function g7(t){return t.deviceId===t.groupId&&t.groupId===""}async function s3(t=0){if(wY()||!cW())return[];let i=await navigator.mediaDevices.enumerateDevices();if(t!==0){const r={audio:!1,video:!1};if(i.forEach(l=>{g7(l)&&(l.kind===zt.AUDIO_INPUT?r.audio=!0:l.kind===zt.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&&z1()}catch(u){jo.debug("capture before getDevices failed: ",u)}i=await navigator.mediaDevices.enumerateDevices(),l?.getTracks().forEach(u=>u.stop())}}return i.map((r,l)=>{const u={kind:r.kind,deviceId:r.deviceId,groupId:r.groupId,label:r.label||`${r.kind}_${l}`};return r.deviceId.length>0&&BW.add(`${r.deviceId}_${r.kind}`),r.getCapabilities&&(u.getCapabilities=()=>r.getCapabilities()),u})}function qL(t=!1){return lQ.update(t?1:0).then(i=>i.audioInputs.devices)}function sv(t=!1){return lQ.update(t?2:0).then(i=>i.videoInputs.devices)}var G8=!1;async function XlA(){try{G8||(G8=!0,jo.info(`speakers:${(await $lA()).map(t=>` ${t.deviceId.slice(0,8)}: ${t.label}`)}`))}catch{}}async function $lA(t=!1){return(hu||Ad)&&(t=!1),lQ.update(t?1:0).then(i=>i.audioOutputs.devices)}var y1,BW=new Set;function AIA(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}_${zt.VIDEO_INPUT}`;return!!BW.has(r)}function eIA(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}_${zt.AUDIO_INPUT}`;return!!BW.has(r)}async function tIA(t,i){const r=(await qL()).find(l=>l.deviceId===L9);return!i&&r?.groupId===t||r?.groupId===t&&r.label===i}async function iIA({newDeviceId:t,oldDeviceId:i,oldGroupId:r,oldLabel:l,kind:u}){return t===i&&(u!==zt.AUDIO||t!==L9||await tIA(r,l))}var oIA=class extends KlA{constructor(t){super(),this.log=t,Ee(this,"volumeMeter"),Ee(this,"volumeMeterAfter3A"),Ee(this,"volumeDestination"),Ee(this,"analyser",new qlA),this.volumeMeter=new T8({log:this.log}),this.volumeMeterAfter3A=new T8({log:this.log}),this.volumeDestination=new ov,this.volumeMeter.pipeTo(this.volumeDestination)}destroy(){this.gain.deleteNode(),this.volumeMeter.deleteNode(),this.analyser.deleteNode(),this.source.deleteNode(),this.destination.deleteNode(),this.volumeDestination.deleteNode()}},sIA=class extends HM{constructor(t){super(t,zt.AUDIO),Ee(this,"_outputDeviceId"),Ee(this,"_floatVolume",1),Ee(this,"_destination"),Ee(this,"pipeline"),Ee(this,"volumeMeterMode","worklet"),Ee(this,"enableVolumeControlInIOS"),this.enableVolumeControlInIOS=t.enableVolumeControlInIOS,this.mode=0,t.url&&(this.url=t.url),this.pipeline=new oIA(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((EQ==="15.2"||EQ==="15.3"||EQ==="15.4")&&this.muted)return void this._log.info("audioElement is muted.");this._log.info("audio player initializeElement");const i=y1||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(cv(t)?t/100:this._floatVolume),i===y1&&(y1=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(Py("player").createAnalyser()),XlA()}catch(i){throw this._log.warn(`audio play error: ${i}`),RX(EQ,"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()}},nIA=class extends sIA{constructor(t){super(t),Ee(this,"_sourceElement"),Ee(this,"_output",new ov),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(Py().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&&!V1();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(V1()){if(!this.enableVolumeControlInIOS)return;HlA()}if(Kd&&!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=Py().createMediaStreamDestination()),this.pipeline.destination.setNode(this._destination),VL(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&&vX&&(y1=i),this._sourceElement&&(this._sourceElement.srcObject=null,delete this._sourceElement),super.stop(t)}},QW=class extends Xn{constructor({userId:t,sdkAppId:i,mediaType:r,room:l,PlayerClass:u=r===1?nIA:Ry}){var p;super(),Ee(this,"id",kX()),Ee(this,"userId",""),Ee(this,"isRemote"),Ee(this,"mediaType"),Ee(this,"room"),Ee(this,"user"),Ee(this,"_log"),Ee(this,"_inputTrack"),Ee(this,"_outputTrack"),Ee(this,"isPlayCalled"),Ee(this,"container",null),Ee(this,"player"),Ee(this,"subVideoPlayerMap"),Ee(this,"muted",!1),Ee(this,"abortCtrl"),Ee(this,"objectFit","cover"),Ee(this,"mirror"),Ee(this,"rotation"),Ee(this,"isScreen",!1),Ee(this,"manager"),Ee(this,"trackSettings"),Ee(this,"isFirstVideoFrameEmitted",!1),this.userId=t||"",this.mediaType=r,this._log=jo.createLogger({parent:l?.getLogger(),id:`${this.kind[0]}t`,userId:(p=l||this.room)==null?void 0:p.userId,remoteUserId:this instanceof ZM?void 0:this.userId,sdkAppId:i,type:this.mediaType===2?"auxiliary":"main",isLocal:this instanceof ZM}),this.player=new u({id:this.userId||this.id,track:null,muted:!1,container:null,log:this._log,enableVolumeControlInIOS:l?.enableVolumeControlInIOS}),this.player.on(Vn.PLAYER_STATE_CHANGED,y=>{if(Qs.emit(mn.PLAYER_STATE_CHANGED,Rn({track:this},y)),this.emit("player-state-changed",y),y.state==="PLAYING"&&this.room){let w=!0;for(const{remoteAudioTrack:_,remoteVideoTrack:k,remoteAuxiliaryTrack:F}of[...this.room.remotePublishedUserMap.values()])if(_.isAvailable&&!_.player.isPlaying||k.isAvailable&&!k.player.isPlaying||F.isAvailable&&!F.player.isPlaying){w=!1;break}w&&JL()&&PlA()}}),this.kind===zt.VIDEO&&(this.player.on(Vn.LOADED_DATA,()=>{this.emitFirstVideoFrameEvent(Vn.LOADED_DATA),Qs.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,y=>{var w;(w=this.subVideoPlayerMap)==null||w.forEach(_=>_.setTrack(y))}),this.player.on(Vn.RESIZE,y=>{this.emitFirstVideoFrameEvent(Vn.RESIZE),this.emit("video-size-changed",Rn({userId:this.userId,streamType:this.mediaType===2?"auxiliary":"main"},y))}),this.player.on(Vn.FIRST_FRAME_RENDER,y=>{this.emit("first-frame-render",zh(Rn({},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(Vn.ERROR,this.onPlayerError.bind(this)),this.player.on(Vn.AUTOPLAY_FAILED,this.handleAutoPlayFailed,this)}get log(){return this._log||jo}get kind(){return this.mediaType===1?zt.AUDIO:zt.VIDEO}get isAudio(){return this.kind===zt.AUDIO}get strMediaType(){return this.mediaType===4?zt.VIDEO:this.mediaType===2?zt.SCREEN:zt.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=VC(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 Ry&&(this.player.setObjectFit(this.objectFit),this.container!==r&&r&&(VC(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))),VC(t)&&t.length>=1&&await this.playSubContainer(t.slice(1),i)));if(i&&!$n(i.muted)?this.setPlayerMute(i.muted):this.isRemote&&this.kind!==zt.VIDEO||this.setPlayerMute(!0),i&&!$n(i.objectFit)&&(this.objectFit=i.objectFit),this.player instanceof Ry&&($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 Ry&&this.player.setContainer(r)),Qs.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),VC(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!==zt.VIDEO||$n(t)||t===this.mirror)return;this.mirror=t;let r=this.player;i&&(r=i);const l=this.manager;if(tv(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===zt.AUDIO)return;this.subVideoPlayerMap||(this.subVideoPlayerMap=new Map),this.subVideoPlayerMap.forEach((l,u)=>{var p;t.find(y=>u===y)||(l.stop(),(p=this.subVideoPlayerMap)==null||p.delete(u))});for(const[l,u]of t.entries()){const p=this.subVideoPlayerMap.get(u);p?i&&($n(i.objectFit)||p.setObjectFit(i.objectFit)):this.subVideoPlayerMap.set(u,new Ry({id:this.userId||this.id,track:this.playerMediaTrack,container:u,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(ej(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),Qs.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){CW(t,t).add(zt.MUTE,this.onTrackMuted).add(zt.UNMUTE,this.onTrackUnmuted).add(zt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===zt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){VL(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 NY&&K3(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 ej(this)&&this.isAudio&&((i=this.user)!=null&&i.muteState.hasAudio)&&((r=this.user)!=null&&r.muteState.audioMuted)?void 0:(this.player.stop(ej(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((P_||nU)&&(await G_(100),(i=this.player)==null?void 0:i.isPlaying))return;OlA()}else document.addEventListener("click",r,!0);Qs.once(mn.LOCAL_TRACK_CAPTURE_SUCCESS,({track:l})=>{l.kind==="audio"&&JL()&&!this.player.isPlaying&&this.isRemote&&this.isAvailable&&r()}),this.emit("error",t)}getVideoFrame(){return this.player instanceof Ry?this.player.getVideoFrame():""}emitFirstVideoFrameEvent(t){var i,r,l;if(this.isFirstVideoFrameEmitted)return;const u=(i=this.mediaTrack)==null?void 0:i.getSettings();let p=u?.width||((r=this.player.element)==null?void 0:r.videoWidth)||0,y=u?.height||((l=this.player.element)==null?void 0:l.videoHeight)||0;(t!==Vn.RESIZE||p||y)&&(t!==Vn.LOADED_META_DATA||p||y)&&(t!==Vn.LOADED_DATA||p||y||this._log.warn("the dimension of video is 0x0 in first-video-frame event"),this.isFirstVideoFrameEmitted=!0,Z9(this.rotation)&&([p,y]=[y,p]),this.emit("first-video-frame",{width:p,height:y,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`)}};dc([du([],Xn.INIT,{sync:!0})],QW.prototype,"_toInitState");var rIA=Object.prototype.hasOwnProperty;function aIA(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(N_(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(rIA.call(t,i))return!1;return!0}return!1}var Z1=aIA,gIA=async function(t){const i=lIA(t);jo.info(`getUserMedia with constraints: ${JSON.stringify(i)}`);let r=[],l=[];const u=["label","deviceId","groupId"];if(i.audio&&(r=await qL(),jo.info(`microphones: ${by(r.map(p=>zh(Rn({},p),{groupId:p.groupId.substring(0,8)})),{keysToInclude:u})}`)),i.video&&(l=await sv(),jo.info(`cameras: ${by(l,{keysToInclude:u})}`),!tv(i.video)&&i.video.facingMode==="user"&&!i.video.deviceId)){const p=l.filter(y=>!y.label.includes("infrared")).find(y=>y.label.includes("facing front"));p&&(i.video.deviceId=p.deviceId,jo.info(`exclude infrared camera: ${JSON.stringify(i)}`))}try{const p=await navigator.mediaDevices.getUserMedia(i);return zX&&p.getTracks().forEach(y=>{var w;const _=y.getCapabilities();jo.info(`${y.kind} capabilities: ${by(_,{keysToInclude:U9})}`),$n(t.echoCancellation)||((w=_.echoCancellation)==null?void 0:w.indexOf(t.echoCancellation))!==-1||jo.warn(`Invalid argument for 'echoCancellation'. Expected one of [${JSON.stringify(_.echoCancellation)}], but received '${t.echoCancellation}'`)}),i.audio&&z1(),p}catch(p){let{message:y}=p;throw p.name==="NotFoundError"&&(t.video&&l&&l.length===0&&(y=j1({key:K1.CAMERA_NOT_FOUND})),t.audio&&r&&r.length===0&&(y=j1({key:K1.MICROPHONE_NOT_FOUND}))),new Bl({code:Hg.INITIALIZE_FAILED,name:p.name,message:y,constraint:p.constraint})}},cIA=j3({retryFunction:gIA,settings:{retries:3,timeout:500},onError:({error:t,retry:i,reject:r,retryFuncArgs:l,retriedCount:u})=>{const p=u+1;t.name==="NotReadableError"||t.name==="OverconstrainedError"||t.name==="AbortError"?(p===1?(l[0].video&&(l[0].maxResolution=!1,(!Ad||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)):p===2?l[0].useDeviceIdOnly=!0:p!==3||l[0].useExactDeviceId||(l[0].useTrueAsConstraint=!0),i()):r(t),l[0].microphoneId&&b8(l[0].microphoneId,!1),l[0].cameraId&&b8(l[0].cameraId,!0)},onRetrying:t=>{jo.warn(`getUserMedia NotReadableError observed, retrying [${t}/3]`)},onRetryFailed:t=>{qC.logFailedEvent({eventType:yL.GET_USER_MEDIA_RETRY,error:t})},onRetrySuccess:t=>{qC.logSuccessEvent({eventType:yL.GET_USER_MEDIA_RETRY}),qC.uploadEvent({log:`stat-${yL.GET_USER_MEDIA_RETRY}-success-${t}`})}});async function b8(t,i){const r=(i?await sv():await qL()).find(l=>l.deviceId===t);r&&ev(r.getCapabilities)&&jo.warn(by(r.getCapabilities(),{keysToInclude:U9}))}function lIA(t){return{audio:IIA(t),video:uIA(t)}}function IIA(t){if(!t.audio)return!1;if(t.useTrueAsConstraint)return!0;const i={echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,sampleRate:t.sampleRate};return!Z1(t.microphoneId)&&(i.deviceId=t.useExactDeviceId?{exact:t.microphoneId}:t.microphoneId,t.useDeviceIdOnly)?i:(cv(t.channelCount)&&(i.channelCount=t.channelCount),(tv(t.echoCancellation)||t.echoCancellation==="remote-only"||t.echoCancellation==="all")&&(i.echoCancellation=t.echoCancellation),tv(t.noiseSuppression)&&!t.noiseSuppression&&(i.noiseSuppression=!1),tv(t.autoGainControl)&&!t.autoGainControl&&(i.autoGainControl=!1),!!Z1(i)||i)}function uIA(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&&!Z1(r)?r:(t.width&&(r.width={ideal:t.width},i&&!Kd&&(r.width.max=t.width)),t.height&&(r.height={ideal:t.height},i&&!Kd&&(r.height.max=t.height)),Kd&&vY&&t.width&&t.height&&t.width*t.height<101376&&(r.width=t.width,r.height=t.height),t.frameRate&&(r.frameRate=t.frameRate),!!Z1(r)||r)}var EIA=cIA;function c7(t){return TY((i,r)=>async function(...l){const u=await i.apply(this,l);return await t.call(this,...l),u})}function TY(t){return function(i,r,l){return l.value=t(l.value,r),l}}var dIA=(()=>{let t=!1,i=document.visibilityState;return()=>{document.visibilityState!==i&&jo.info(`visibility change: ${document.visibilityState}`),t||(document.addEventListener("visibilitychange",()=>{jo.info(`visibility change: ${document.visibilityState}`),i=document.visibilityState}),t=!0)}})(),CIA=0,hIA=class{constructor(t){Ee(this,"log"),Ee(this,"isRunning",!1),Ee(this,"queue",[]);let i="fq"+ ++CIA;t&&(i+=`|${t}`),this.log=jo.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 u=Rn({},t),p=new Promise((y,w)=>{u.resolve=y,u.reject=w});return u.promise=p,i?this.length<=1?this.queue.push(u):(l=(r=this.lastQueueItem)==null?void 0:r.promise)==null||l.then(u.resolve,u.reject):this.queue.push(u),this.log.debug(`push ${this.length}`,t.funcName,t.args),this.isRunning||this.callNext(),p}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:u,funcName:p}=this.queue[0];this.log.debug("callNext",this.length,p,i),this.isRunning=!0,t.apply(r,i).then(l,u).finally(()=>{this.isRunning=!1,this.shift(),this.callNext()})}},k8=new WeakMap;function BIA(t=!1){return function(i,r,l){const u=l.value;return l.value=function(...p){const y=k8.get(this)||new hIA;return k8.set(this,y),y.push({fn:u,args:p,context:this,funcName:r},t)},l}}function l7(t,i){return TY((r,l)=>function(...u){const p=t;try{const y=r.apply(this,u),w=Pc();return Y9(y)?y.then(_=>(i?lr.addSuccessEvent({key:p,cost:Pc()-w}):lr.addSuccessEvent({key:p}),_)).catch(_=>{throw lr.addFailedEvent({key:p,error:_}),_}):(lr.addSuccessEvent({key:p}),y)}catch(y){throw lr.addFailedEvent({key:p,error:y}),y}})}function zl(...t){}var QIA=t=>t();function pIA(){this.dispose()}var mIA=()=>typeof __FASTRX_DEVTOOLS__<"u",fIA=1,b_=class extends Function{toString(){return`${this.name}(${this.args.length?[...this.args].join(", "):""})`}subscribe(t){const i=new DIA(t,this,this.streamId++);return hl.subscribe({id:this.id,end:!1},{nodeId:i.sourceId,streamId:i.id}),this(i),i}},pW=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=zl,this.error=zl,this.next=zl,this.dispose=zl,this.subscribe=zl,this.doDefer()}subscribe(t){return t instanceof b_?t.subscribe(this):t(this),this}get bindSubscribe(){return t=>this.subscribe(t)}doDefer(){this.defers.forEach(QIA),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}},Xh=class extends pW{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)}},yIA=class extends pW{constructor(t,i=zl,r=zl,l=zl){if(super(),this._next=i,this._error=r,this._complete=l,this.then=zl,t instanceof b_){const u={toString:()=>"subscribe",id:0,source:t};this.defer(()=>{hl.defer(u,0)}),hl.create(u),hl.pipe(u),this.sourceId=u.id,this.subscribe(t),hl.subscribe({id:u.id,end:!0}),i==zl?this._next=p=>hl.next(u,0,p):this.next=p=>{hl.next(u,0,p),i(p)},l==zl?this._complete=()=>hl.complete(u,0):this.complete=()=>{this.dispose(),hl.complete(u,0),l()},r==zl?this._error=p=>hl.complete(u,0,p):this.error=p=>{this.dispose(),hl.complete(u,0,p),r(p)}}else this.subscribe(t)}next(t){this._next(t)}complete(){this.dispose(),this._complete()}error(t){this.dispose(),this._error(t)}};function YC(t,...i){return i.reduce((r,l)=>l(r),t)}function Wd(t,i,r){if(mIA()){const l=Object.defineProperties(Object.setPrototypeOf(t,b_.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}});hl.create(l);for(let u=0;u{if(l instanceof b_){const u=Wd(p=>{const y=new t(p,...r);y.sourceId=u.id,y.subscribe(l)},i,arguments);return u.source=l,hl.pipe(u),u}return u=>l(new t(u,...r))}}}function py(t,i){window.postMessage({source:"fastrx-devtools-backend",payload:{event:t,payload:i}})}var DIA=class extends Xh{constructor(t,i,r){super(t),this.source=i,this.id=r,this.sourceId=t.sourceId,this.defer(()=>{hl.defer(this.source,this.id)})}next(t){hl.next(this.source,this.id,t),this.sink.next(t)}complete(){hl.complete(this.source,this.id),this.sink.complete()}error(t){hl.complete(this.source,this.id,t),this.sink.error(t)}},hl={addSource(t,i){py("addSource",{id:t.id,name:t.toString(),source:{id:i.id,name:i.toString()}})},next(t,i,r){py("next",{id:t.id,streamId:i,data:r&&r.toString()})},subscribe({id:t,end:i},r){py("subscribe",{id:t,end:i,sink:{nodeId:r&&r.nodeId,streamId:r&&r.streamId}})},complete(t,i,r){py("complete",{id:t.id,streamId:i,err:r?r.toString():null})},defer(t,i){py("defer",{id:t.id,streamId:i})},pipe(t){py("pipe",{name:t.toString(),id:t.id,source:{id:t.source.id,name:t.source.toString()}})},update(t){py("update",{id:t.id,name:t.toString()})},create(t){t.id||(t.id=fIA++),py("create",{name:t.toString(),id:t.id})}},SIA=class extends pW{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 I7(){return t=>{const i=new SIA(t);if(t instanceof b_){const r=Wd(l=>{i.add(l)},"share",arguments);return i.sourceId=r.id,r.source=t,hl.pipe(r),r}return Wd(i.add.bind(i),"share",arguments)}}function u7(...t){return Wd(i=>{const r=new Xh(i);let l=t.length;r.complete=()=>{--l===0&&i.complete()},t.forEach(r.bindSubscribe)},"merge",arguments)}function MIA(...t){return Wd(i=>{const r=new Map;t.forEach(l=>{const u=new Xh(i);r.set(l,u),u.complete=()=>{r.delete(l),r.size===0?i.complete():u.dispose()},u.next=p=>{r.delete(l),r.forEach(y=>y.dispose()),u.resetNext(),u.resetComplete(),u.next(p)}}),t.forEach(l=>r.get(l).subscribe(l))},"race",arguments)}function vIA(...t){return i=>Wd((r,l=0,u=t.length)=>{for(;l{r.next=u=>l.next(u),r.complete=()=>l.complete(),r.error=u=>l.error(u),t&&l.subscribe(t)},"subject",i));return r.next=zl,r.complete=zl,r.error=zl,r}function RIA(t){return Wd(i=>{let r=0;const l=setInterval(()=>i.next(r++),t);return i.defer(()=>{clearInterval(l)}),"interval"},"interval",arguments)}function wIA(t,i){return Wd(r=>{let l=0;const u=setTimeout(()=>{r.removeDefer(p),r.next(l++),i||r.complete()},t),p=()=>clearTimeout(u);r.defer(p)},"timer",arguments)}function uj(t,i){return r=>{const l=u=>r.next(u);r.defer(()=>i(l)),t(l)}}function IE(t,i){if("on"in t&&"off"in t)return Wd(uj(r=>t.on(i,r),r=>t.off(i,r)),"fromEvent",arguments);if("addListener"in t&&"removeListener"in t)return Wd(uj(r=>t.addListener(i,r),r=>t.removeListener(i,r)),"fromEvent",arguments);if("addEventListener"in t)return Wd(uj(r=>t.addEventListener(i,r),r=>t.removeEventListener(i,r)),"fromEvent",arguments);throw"target is not a EventDispachter"}function _IA(){return Wd(t=>t.complete(),"empty",arguments)}var TIA=class extends Xh{constructor(t,i,r){super(t),this.filter=i,this.thisArg=r}next(t){this.filter.call(this.thisArg,t)&&this.sink.next(t)}},__=Ev(TIA,"filter"),NIA=class extends Xh{constructor(t,i){super(t),this.count=i}next(t){this.sink.next(t),--this.count===0&&(this.doDefer(),this.complete())}},GIA=Ev(NIA,"take"),bIA=class extends Xh{constructor(t,i){super(t);const r=new Xh(t);r.next=()=>{r.doDefer(),t.complete()},r.complete=pIA,r.subscribe(i)}},k_=Ev(bIA,"takeUntil"),kIA=class extends Xh{constructor(t,i){super(t),this.f=i}next(t){this.f(t)||(this.next=super.next,this.next(t))}},LIA=Ev(kIA,"skipWhile"),UIA=class extends Xh{constructor(t,i,r){super(t),this.mapper=i,this.thisArg=r}next(t){super.next(this.mapper.call(this.thisArg,t))}},d7=Ev(UIA,"map"),FIA=class extends Xh{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()}},OIA=class C7 extends Xh{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===C7.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()}},L8=class extends FIA{},h7=class extends OIA{next(t){this.subInner(t,L8),this.next=i=>{this.currentSink.dispose(),this.subInner(i,L8)}}},PIA=Ev(h7,"switchMap");function xIA(t){return(i,r)=>t(()=>i,r)}var B7=xIA(Ev(h7,"switchMapTo")),Iv=(t=zl,i=zl,r=zl)=>l=>new yIA(l,t,i,r),Q7=(t=>(t[t.AUTO_SWITCH_NEW_DEVICE=0]="AUTO_SWITCH_NEW_DEVICE",t[t.WAIT_CURRENT_DEVICE=1]="WAIT_CURRENT_DEVICE",t))(Q7||{}),ZM=class extends QW{constructor(t,i){super({mediaType:t,PlayerClass:i}),Ee(this,"isRemote",!1),Ee(this,"deviceId"),Ee(this,"groupId",""),Ee(this,"label",""),Ee(this,"sourceTrack"),Ee(this,"enableAutoSwitchWhenRecapturing",!0),Ee(this,"_isRecapturing",!1),Ee(this,"_lastRecaptureTime",0),Ee(this,"_onMuteTimeoutId",-1),Ee(this,"_encodeCheckTimeoutId",-1),Ee(this,"recaptureMode",0),Ee(this,"profile"),Ee(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(zt.MUTE,this.onTrackMuted),t.addEventListener(zt.UNMUTE,this.onTrackUnmuted),t.addEventListener(zt.ENDED,this.onTrackEnded),t.muted&&this.onTrackMuted(),t.readyState===zt.ENDED&&this.onTrackEnded()}uninstallTrackEvent(t){t.removeEventListener(zt.MUTE,this.onTrackMuted),t.removeEventListener(zt.UNMUTE,this.onTrackUnmuted),t.removeEventListener(zt.ENDED,this.onTrackEnded)}setStateToReady(){}async capture(t,i=!1){var r,l;const u=this.sourceTrack;try{const p=Pc();let y;Qs.emit(mn.LOCAL_TRACK_CAPTURE_START,{track:this}),t.customSource?(y=new MediaStream,y.addTrack(t.customSource)):(i||(r=this.sourceTrack)==null||r.stop(),y=await EIA(t));const w=y.getTracks()[0];return await this.setInputMediaStreamTrack(w),t.customSource||(this.sourceTrack=w,this.updateDeviceIdInUse(),this.listenDeviceChange()),Qs.emit(mn.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Pc()-p,profile:this.profile,room:(l=this.manager)==null?void 0:l.room}),y}catch(p){throw Qs.emit(mn.LOCAL_TRACK_CAPTURE_FAILED,{track:this,error:p}),this.log.error(`getUserMedia error observed ${p}`),p}finally{i&&u?.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=J9(((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,u,p,y,w;const _=()=>r(new Bl({code:Hg.API_CALL_ABORTED,message:"publish aborted"}));if(this.hasFlag||this.muted?i():(this.state!==Xn.INIT&&this.state!=="ready"||_(),YC(IE(t,"local-publish-flag-changed"),__(()=>this.hasFlag),k_(u7(IE(this,Xn.INIT),IE(this,"ready"))),Iv(i,r,_))),(p=(u=(l=this.room)==null?void 0:l.networkQuality)==null?void 0:u.hadRecentBadUplink)==null?void 0:p.call(u,2))return i();const k=t.heartbeatCount,F=((w=(y=this.mediaTrack)==null?void 0:y.stats)==null?void 0:w.totalFrames)||0;this._encodeCheckTimeoutId=setTimeout(async()=>{var j,lA,aA,mA,IA,tA,MA,PA;if((aA=(lA=(j=this.room)==null?void 0:j.networkQuality)==null?void 0:lA.hadRecentBadUplink)!=null&&aA.call(lA,2)||t.heartbeatCount-k<3)return i();if((this.isPublished||this.isPublishing)&&this.isMediaTrackActive){if((mA=this.mediaTrack)!=null&&mA.stats){const Ve=this.mediaTrack.stats.totalFrames||0;Ve-F===0&&this.log.warn("capture totalFrames is 0 during encode check, totalFrames",Ve)}const ge=this.kind===zt.AUDIO,de=this.stat.bytesSent>0;if(lr[de?"addSuccessEvent":"addFailedEvent"]({key:ge?503700:513702}),!ge){const Ve={H264:513704,H265:513705,VP8:513706}[((tA=(IA=this.room)==null?void 0:IA.videoCodec)==null?void 0:tA.toUpperCase())||"H264"];Ve&&lr[de?"addSuccessEvent":"addFailedEvent"]({key:Ve})}if(!de){if(lr.addEnum({key:ge?503701:513703,value:rW()}),qC.uploadEvent({log:`stat-encode-failed-${this.kind}-${wX()||TX()}`,userId:this.userId}),this.log.warn(ge?"encode failed":`${(PA=(MA=this.room)==null?void 0:MA.videoCodec)==null?void 0:PA.toUpperCase()} encode failed`),this.retryEncodeFailed&&(this.log.warn("retry encode"),await this.retryEncodeFailed(this),this.stat.bytesSent>0||this.hasFlag||(await G_(5e3),this.stat.bytesSent>0||this.hasFlag)))return i();this.emit("6",this),r(new Bl({message:`${this.strMediaType} encode failed`,code:ge?Hg.AUDIO_ENCODE_FAILED:Hg.VIDEO_ENCODE_FAILED}))}}},1e4)})}unpublish(){this.room&&this.room.localTracks.delete(this),this.log.info("unpublish"),Qs.emit(mn.LOCAL_TRACK_UNPUBLISHED,{track:this})}async updateDeviceIdInUse(){if(this.sourceTrack&&W1){const{deviceId:t,groupId:i}=this.sourceTrack.getSettings(),{label:r}=this.sourceTrack;await iIA({newDeviceId:t,oldDeviceId:this.deviceId,oldGroupId:this.groupId,oldLabel:this.label,kind:this.kind})||(this.deviceId=t,this.label=r,i&&(this.groupId=i),s3().then(l=>{const u=l.find(p=>{let y=p.deviceId===t;return i&&(y=y&&p.groupId===i),y});u&&this.emit("2",u)}))}}setProfile(t){this.log.info("setProfile",t),Object.assign(this.profile,t)}isNeedToRecapture(t=!1){return!(!this.deviceId||!this.sourceTrack||this.kind===zt.AUDIO&&!eIA(this.sourceTrack)||this.kind===zt.VIDEO&&!AIA(this.sourceTrack)||this._isRecapturing||t&&vY&&Ad)}onTrackMuted(){super.onTrackMuted(),dIA(),this.isNeedToRecapture(!0)&&(Date.now()-this._lastRecaptureTimethis.onTrackMuted(),A1):this._onMuteTimeoutId=setTimeout(async()=>{var t;if((t=this.sourceTrack)!=null&&t.muted){if((hu||Zd)&&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(),A1);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 u={useExactDeviceId:!0};if(t==="user"||t==="environment")u.facingMode=t;else{let p;(this.kind==="audio"?await qL():await sv()).find(y=>y.deviceId===t)&&(p=t),u.deviceId=p}return this.capture(u,i).then(()=>{this._isRecapturing=!1,this.log.warn("recapture success"),this.emit("1",{deviceId:this.deviceId}),Qs.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this})}).catch(p=>{this._isRecapturing=!1,this.log.warn(`recapture failed ${p.message}`),this.emit("5",p),Qs.emit(mn.LOCAL_TRACK_RECAPTURE,{track:this,error:p})}).finally(()=>{i&&l?.stop()})}async getRecoverCaptureDeviceId(){const t=this instanceof NY;if(t&&this.facingMode)return this.facingMode;let{deviceId:i}=this;if(i){const r=(rL.get(i)||0)+1;if(rL.set(i,r),r>=3&&this.enableAutoSwitchWhenRecapturing){const l=t?(await sv()).find(u=>!rL.has(u.deviceId)):(await qL()).find(u=>!rL.has(u.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(),Qs.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()}};dc([du(Xn.INIT,"ready",{ignoreError:!0,sync:!0})],ZM.prototype,"setStateToReady"),dc([BIA()],ZM.prototype,"capture"),dc([du("ready","publish",{ignoreError:!0,success(){Qs.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 Bl?t:t.cause instanceof Bl?t.cause:t;let u=!1;l instanceof Bl&&(l.message.includes("timeout")?r="timeout":l.code===Hg.API_CALL_ABORTED&&(u=!0,r="api-call")),this.emit("4",{mediaType:this.strMediaType,state:"stopped",prevState:"starting",reason:r,error:l}),this.log[u?"info":"error"]("publish failed",l)}}),l7(521714,!1)],ZM.prototype,"publish"),dc([TY(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})],ZM.prototype,"unpublish");var rL=new Map;Qs.on(mn.SWITCH_DEVICE_SUCCESS,t=>{t.track.deviceId&&rL.delete(t.track.deviceId)});var YIA=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 p=t;p<=i;p++){const y=this.dataView.getInt8(p);switch(y){case 0:case 1:case 2:case 3:l===2&&(r.push(3),l=0),y===0?l+=1:l=0,r.push(y);break;default:l=0,r.push(y)}}r.push(this.dataView.getInt8(this.dataView.byteLength-1));const u=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=u}removePreventionByte(){const{seiPayloadStartIndex:t}=this,i=this.dataView.byteLength-1,r=[];let l=0;for(let p=t;p<=i;p++)switch(this.dataView.getInt8(p)){case 0:l++,r.push(this.dataView.getInt8(p));break;case 3:l!==2&&r.push(this.dataView.getInt8(p)),l=0;break;default:r.push(this.dataView.getInt8(p)),l=0}const u=new DataView(new Uint8Array([...new Uint8Array(this.dataView.buffer).slice(0,t),...r]).buffer);this.dataView=u}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}},VIA=class{constructor(){Ee(this,"_seiMessageList",[]),Ee(this,"_smallSeiMessageList",[]),Ee(this,"_seiPayloadType",243)}encodeSEINalu(t){const i=t.byteLength,r=parseInt(String(i/255),10),l=i%255,u=[];u.push(0,0,0,1,6,this._seiPayloadType);for(let y=0;y0&&t.data.byteLength>0){const l=9-this.getNaluCount(t.data);if(l<=0)return 0;const u=r.splice(0,l).reverse().map(this.encodeSEINalu.bind(this)),p=u.reduce((F,j)=>F+j.dataView.byteLength,0),y=new ArrayBuffer(p+t.data.byteLength),w=new DataView(y),_=new DataView(t.data);let k=0;for(let F=0;F{var l;if(this.isAllowed2k4k(this.profile))this.room&&this.settings.height>=1440&&this.state==="publish"&&this.room.sendAbilityStatus({"2k4k":1});else{const u=x1(((l=this.room)==null?void 0:l.sdkAppId)||0)?Wz:jz;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${u}`),this.setProfile(zh(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(W1&&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(HC(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:u=!0}){const p={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:u,customSource:l};if(p.facingMode==="environment"){const y=await this.getDeviceIdWhenUsingBackCamera();y&&(p.cameraId=y)}return super.capture(p)}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=x1(((i=this.room)==null?void 0:i.sdkAppId)||0)?Wz:jz;this.log.warn(`Resolution is reset to 1080p, need to upgrade ability here ${l}`),super.setProfile(zh(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(),u=r*l,p=this.settings,y=p.height!==this.profile.height||p.width!==this.profile.width||p.frameRate!==this.profile.frameRate;if(y&&(lv===16&&this.deviceId?await this.recapture(this.deviceId):(K3(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(),k=w*_;return y&&k&&u&&k===u?void this.log.warn("set bandwidth failed: resolution is not changed"):this.room.setBandWidth({bandwidth:this.profile.bitrate,type:zt.VIDEO,videoType:zt.BIG})}}get settings(){const t={width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate},i=this.sourceTrack||this.mediaTrack;return W1&&i&&Object.assign(t,i.getSettings()),t}get scaleResolutionDownBy(){return this._scaleResolutionDownBy?this._scaleResolutionDownBy:z9(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),Qs.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(pX&&!sW&&ZX){const i=(await sv(!0)).map(l=>{var u;return zh(Rn({},l),{capabilities:(u=l.getCapabilities)==null?void 0:u.call(l)})}).filter(l=>{var u,p;return(p=(u=l.capabilities)==null?void 0:u.facingMode)==null?void 0:p.includes("environment")});let r=i[0];i.forEach(l=>{var u,p,y,w;const{capabilities:_}=l;((u=_.width)!=null&&u.max&&((p=_.height)!=null&&p.max)?_.width.max*_.height.max:0)>((y=r.capabilities.width)!=null&&y.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&&Zd&&Fy&&(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&&kcA&&(l.width=r?1280:720,l.height=r?720:1280,this.log.warn("reset to 1280 * 720 on iOS 13~14")),GcA(EQ,"14.3")&&RX(EQ,"14.0",!0)&&this.on("7",()=>{const u=this.profile.width>this.profile.height;this.profile.width*this.profile.height>307200?(this.profile.width=u?640:480,this.profile.height=u?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=u?640:360,this.profile.height=u?360:640,this.log.warn("reduce the resolution to 360p on iOS 14.0 ~ 14.2"))}),!i&&this.avoidCropping&&(Fy||Kd)&&!FcA()&&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(){lQ&&!lQ.listeners("videoInputRemoved").includes(this.handleCameraRemoved)&&lQ.on("videoInputRemoved",this.handleCameraRemoved,this)}async handleCameraRemoved(t){if(t.deviceId===this.deviceId){let i=this.recaptureMode===1;if(this.log.warn(`RecaptureMode: ${Q7[this.recaptureMode]}. Current camera is lost: ${JSON.stringify(t)}`),this.recaptureMode===0){uc(this.userId,{eventId:2003,param1:7,streamType:2});const r=await sv();r[0]?this.recapture(r[0].deviceId):i=!0}i&&lQ.on("videoInputAdded",this.handleCameraAdded,this)}}async handleCameraAdded(t){this.recaptureMode===1&&t.deviceId!==this.deviceId||(lQ.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,u)=>u?u({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(){lQ.off("videoInputAdded",this.handleCameraAdded,this),lQ.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))}};dc([c7(function(t){this.setContentHint(t.contentHint||"motion")})],NY.prototype,"capture");var JIA=[-1,-1,1,-1,-1,1,1,1],HIA=[0,0,1,0,0,1,1,1],aL=class n3 extends Xn{constructor(i,r){if(super(),this.context=i,Ee(this,"name"),Ee(this,"input"),Ee(this,"output"),Ee(this,"texture"),Ee(this,"ctx2d",null),Ee(this,"fbo"),Ee(this,"width",0),Ee(this,"height",0),Ee(this,"x",0),Ee(this,"y",0),Ee(this,"program"),Ee(this,"vertexShader"),Ee(this,"fragmentShader"),Ee(this,"totalFrames",0),Ee(this,"dropFrames",0),Ee(this,"matchInputSize",!0),Ee(this,"texCoordBuffer"),Ee(this,"positionBuffer"),Ee(this,"lastInfo",{name:"",timestamp:0,totalFrames:0,x:0,y:0,width:0,height:0,fps:0}),Ee(this,"cost",0),Ee(this,"_canvas",null),Ee(this,"_image"),Ee(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 jL)i.ctx&&r.create2d&&(typeof OffscreenCanvas=="function"&&lv!==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(HIA),this.positionBuffer=this.createBuffer(JIA),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 Bl({code:Hg.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 r3&&this.render(i)||this.context instanceof jL&&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 r3){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,u)=>{l&&(r.activeTexture(r.TEXTURE0+u),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,u)=>{r.enableVertexAttribArray(u),r.bindBuffer(r.ARRAY_BUFFER,l),r.vertexAttribPointer(u,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,u,p,y,w,_,k){const F=!($n(y)||$n(w)||$n(_)||$n(k));return!(!this.ctx2d||!i)&&(i instanceof ImageData?(F?this.ctx2d.putImageData(i,r,l,y,w,_,k):this.ctx2d.putImageData(i,r,l),this.emit(n3.RENDER,this.ctx2d.canvas)):(F?this.ctx2d.drawImage(i,y,w,_,k,r,l,u,p):this.ctx2d.drawImage(i,r,l,u,p),this.emit(n3.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:u,width:p,height:y,name:w,cost:_}=this,k=Date.now(),F=(r-this.lastInfo.totalFrames)/((k-this.lastInfo.timestamp)/1e3)|0;return this.lastInfo={totalFrames:r,x:l,y:u,width:p,height:y,timestamp:k,fps:F,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}};Ee(aL,"RENDER","render"),dc([du(Xn.INIT,"connected",{sync:!0})],aL.prototype,"connect"),dc([du("connected",Xn.INIT,{ignoreError:!0,sync:!0})],aL.prototype,"disconnect"),dc([du([],"closed",{sync:!0})],aL.prototype,"close");var X1=aL,qIA=YC(RIA(250),d7(()=>performance.now()),I7()),KIA=t=>i=>{const r=performance.now();YC(qIA,LIA(l=>l-r{if(t!==this.context.frameRate&&(uQ.clearTask(this._intervalId),this.start(this.context.frameRate)),this.requestFrame(this._sequence++),this.checkGLError&&this.context instanceof r3){const i=this.context.ctx.getError();i&&this.context.destroy(new Bl({code:Hg.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(X1.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&&(uQ.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),uQ.clearTask(this._intervalId)}resize(t,i){super.resize(t,i),this.context.setSize(t,i)}close(){super.close(),uQ.clearTask(this._intervalId),document.removeEventListener("visibilitychange",this.checkVisibilityChange)}},zIA=class extends WIA{constructor(t,i){super(t,i),Ee(this,"_videoTrack"),Ee(this,"_muteOb"),Ee(this,"_closedOb",IE(this,"closed")),Ee(this,"_subscription"),Ee(this,"_canvasContainer"),Number(rU)<17&&(this._canvasContainer=document.createElement("div"),this._canvasContainer.style.display="none"),[this._videoTrack]=t.canvas.captureStream().getVideoTracks(),this._muteOb=IE(this._videoTrack,"mute"),YC(IE(this._videoTrack,"ended"),k_(this._closedOb),Iv(()=>{this.context.destroy(new Bl({code:Hg.VIDEO_MANAGER_ERROR,extraCode:8,message:"video track ended"}))}))}enableCheckMute(){this._subscription=YC(this._muteOb,k_(this._closedOb),B7(KIA(5e3)),__(()=>{var t;return!!((t=this._videoTrack)!=null&&t.muted)&&!document.hidden}),Iv(()=>{this.context.destroy(new Bl({code:Hg.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()}},p7=class extends X1{constructor(t,i){super(t,Rn({name:"imageSource"},i)),Ee(this,"_lastImage"),Ee(this,"_totalFrames",0),Ee(this,"_autoResize",!1),Ee(this,"_canvasRendered"),Ee(this,"videoCallbackId",0),Ee(this,"waitingFirstFrame",!0),Ee(this,"shouldUpdate",!0),this._autoResize=i?.autoResize!==!1,lv===16&&(this._canvasRendered=E7(),YC(this._canvasRendered,vIA(this._image),PIA(r=>r instanceof HTMLCanvasElement?IE(r,"rendered"):_IA()),k_(IE(this,"closed")),Iv(()=>{this.update()})))}onFirstFrame(){this.waitingFirstFrame=!1}tryVideoFrameCallback(){if(!this.shouldUpdate)return;const t=this.image;this.videoCallbackId&&t.cancelVideoFrameCallback(this.videoCallbackId),EW()&&!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:u}=this;const{image:p}=this;if(p instanceof HTMLVideoElement){if(this.tryVideoFrameCallback(),{videoWidth:l,videoHeight:u}=p,!l||!u)return!1;p.width=l,p.height=u}else if(p instanceof HTMLImageElement||p instanceof ImageData||p instanceof ImageBitmap){if({width:l,height:u}=p,p!==this._lastImage)this._lastImage=p;else if(l===this.width&&u===this.height)return!0}else p instanceof HTMLCanvasElement||p instanceof OffscreenCanvas?({width:l,height:u}=p,this._lastImage=p):typeof VideoFrame<"u"&&p instanceof VideoFrame&&({displayWidth:l,displayHeight:u}=p,(r=this._lastImage)==null||r.close(),this._lastImage=p);if(!this._autoResize)return!0;if(this.width===l&&this.height===u&&this.totalFrames){if(i){this.useTexture();const y=this.context.ctx;y.texSubImage2D(y.TEXTURE_2D,0,0,0,y.RGBA,y.UNSIGNED_BYTE,p)}}else{if(i){this.useTexture();const y=this.context.ctx;y.texImage2D(y.TEXTURE_2D,0,y.RGBA,y.RGBA,y.UNSIGNED_BYTE,p)}this.resize(l,u)}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)}},m7=class extends p7{constructor(t,i,r){super(t,r),this._player=i,this.name="videoPlayerSource",YC(IE(this._player,Vn.PLAYER_STATE_CHANGED),k_(IE(this,"closed")),__(({state:l})=>l==="PLAYING"),Iv(()=>{this.tryVideoFrameCallback()}))}get image(){return this._player.element}},ZIA=class extends m7{get available(){return this._player.isPlaying&&!this.waitingFirstFrame}constructor(t,i,r){super(t,new Ry({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()}},XIA=class extends X1{constructor(t,i,r){super(t,zh(Rn({name:"textSource"},r),{create2d:!0})),Ee(this,"hasChange",!0),Ee(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 u=this.font.match(/(\d+)px/),p=(u?parseInt(u[1],10):16)*r,y=this.content.split(` +`);for(let w=0;w{this.destroy(new Bl({code:Hg.VIDEO_MANAGER_ERROR,extraCode:4,message:"webgl context lost"}))})}destroy(t){let i="";return t&&(i=t.message,this.error=t,lr.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}};Ee(gL,"UNAVAILABLE","unavailable"),dc([du(Xn.INIT,"created",{sync:!0,fail(t){this.log.error("video gl context create failed",t.cause),lr.addFailedEvent({key:512700,error:t.cause||t})},success(){this.log.info("video context created use webgl"),lr.addSuccessEvent({key:512700})}})],gL.prototype,"create"),dc([du("created",Xn.INIT,{ignoreError:!0,sync:!0,success(t){t&&this.emit(gL.UNAVAILABLE,t),this.removeAllListeners()}})],gL.prototype,"destroy");var r3=gL,jL=class extends KL{constructor(){super(...arguments),Ee(this,"ctx")}create(t){if(this.hasAlpha=t.alpha,this._canvas=document.createElement("canvas"),this._canvas.id=`trtc_${this.name}_${KL._ids++}`,this.ctx=this._canvas.getContext("2d",{alpha:t.alpha,willReadFrequently:t.willReadFrequently}),!this.ctx)throw new Bl({code:Hg.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,lr.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(),lr.addSuccessEvent({key:512703})}};dc([du(Xn.INIT,"created",{sync:!0,fail(t){this.log.error("video 2d context create failed",t.cause),lr.addFailedEvent({key:512701,error:t.cause||t})},success(){this.log.info("video context created use 2d"),lr.addSuccessEvent({key:512701})}})],jL.prototype,"create"),dc([du("created",Xn.INIT,{ignoreError:!0,sync:!0})],jL.prototype,"destroy");var mW=kX();if(typeof navigator<"u"&&navigator.mediaDevices&&"setCaptureHandleConfig"in navigator.mediaDevices)try{navigator.mediaDevices.setCaptureHandleConfig({handle:mW,exposeOrigin:!0,permittedOrigins:["*"]})}catch{}var euA=async function(t){let i=null;const r=ouA(t);jo.info(`getDisplayMedia with constraints: ${JSON.stringify(r)}`);const l=await navigator.mediaDevices.getDisplayMedia(r);t.systemAudio&&l.getAudioTracks().length===0&&(nW&&Oy<74||Ad||Kd)&&jo.warn("Your browser not support capture system audio");const u=l.getVideoTracks()[0];if(u){if(t.frameRate)try{await u.applyConstraints({frameRate:{min:t.frameRate,ideal:t.frameRate},width:t.width,height:t.height})}catch(p){jo.warn(`screen applyConstraints failed: ${p}`)}t.captureElement&&await tuA(u,t.captureElement)}if(t.audio){const p=iuA(t);jo.info(`getUserMedia with constraints: ${JSON.stringify(p)}`),i=await navigator.mediaDevices.getUserMedia(p),l.addTrack(i.getAudioTracks()[0])}return l};async function tuA(t,i){var r;if("CropTarget"in window&&"fromElement"in CropTarget&&ev(t.cropTo))try{if(((r=t.getCaptureHandle())==null?void 0:r.handle)!==mW)return;const l=await CropTarget.fromElement(i);await t.cropTo(l)}catch(l){jo.warn(`cropTo target failed ${l}`)}}function iuA(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 ouA(t){const i={preferCurrentTab:t.preferDisplaySurface==="current-tab"||!!t.captureElement,systemAudio:"include",selfBrowserSurface:"include",surfaceSwitching:"include"},r={width:Ad?{max:t.width}:{ideal:t.width,max:t.width},height:Ad?{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:u=!1,autoGainControl:p=!1}=t;i.audio={echoCancellation:l,noiseSuppression:u,autoGainControl:p,sampleRate:48e3}}return i}var suA=euA,nuA=class extends NY{constructor(t){super(t,2),Ee(this,"profile",{width:1920,height:1080,frameRate:5,bitrate:1600}),Ee(this,"objectFit","contain"),Ee(this,"isScreen",!0),this._log.id=`s-${this._log.id}`}get isShareCurrentTab(){var t,i;try{return mW===((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:u,videoTrack:p,captureElement:y,preferDisplaySurface:w}){var _;try{const k=Pc();let F;return p||u?(F=new MediaStream,p&&F.addTrack(p),u&&F.addTrack(u)):(F=await suA({audio:!1,systemAudio:t,width:this.profile.width,height:this.profile.height,frameRate:this.profile.frameRate,autoGainControl:i,echoCancellation:r,noiseSuppression:l,captureElement:y,preferDisplaySurface:w}),this.sourceTrack=F.getVideoTracks()[0]),await this.setInputMediaStreamTrack(F.getVideoTracks()[0]),Qs.emit(mn.LOCAL_TRACK_CAPTURE_SUCCESS,{track:this,cost:Pc()-k,profile:this.profile,room:(_=this.manager)==null?void 0:_.room}),F}catch(k){throw this.log.error(`getDisplayMedia error observed ${k}`),k instanceof Bl?k:new Bl({code:Hg.INITIALIZE_FAILED,name:k.name,message:k.message})}}async switchDevice(t){throw new Error("Method not implemented.")}};function ruA(t=30,i=2){return TY((r,l)=>function(...u){return new Promise((p,y)=>{const w=setTimeout(()=>{const _=new Bl({code:Hg.API_CALL_TIMEOUT,message:`checkPendingPromise ${l}() timeout ${t}s`});(this.log||this._log||jo).warn(_),i===2?y(_):i===1&&p()},1e3*t);this._checkPendingPromiseSet||(this._checkPendingPromiseSet=new Set),this._checkPendingPromiseSet.add(w),r.apply(this,u).then(p,y).finally(()=>{clearTimeout(w),this._checkPendingPromiseSet&&w&&this._checkPendingPromiseSet.delete(w)})})})}dc([c7(function(t){this.setContentHint(t.contentHint||"detail")})],nuA.prototype,"capture");var o_=class a3 extends QW{constructor(i,r,l){super({userId:r.userId,sdkAppId:i.sdkAppId,mediaType:l,room:i}),this.room=i,this.user=r,Ee(this,"tinyId"),Ee(this,"isRemote",!0),Ee(this,"jitterBufferDelay",0),Ee(this,"availableState"),Ee(this,"remotePublishState"),Ee(this,"_triggerCheckDecodeSubject",E7(IE(this,a3.STATE_SUBSCRIBE))),Ee(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"),YC(u7(IE(this,Xn.STATECHANGED),IE(this.remotePublishState,Xn.STATECHANGED)),d7(()=>this.isRemotePublished&&(this.isSubscribed||this.isSubscribing)),Iv(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 u=YC(IE(this.player,Vn.ERROR),__(w=>w.code===MediaError.MEDIA_ERR_DECODE)),p=YC(wIA(5e3),__(()=>this.ignoreDecodeError||!this.isSubscribed||!this.isPlayCalled||!this.stat.bytesReceived||!this.isRemotePublished?!1:!(this.player.isPlaying||(this.kind===zt.AUDIO?this.getAudioLevel()>0:this.stat.framesDecoded>0))||(this.reportDecodeResult(!0),!1))),y=YC(MIA(u,p),k_(IE(this,Xn.INIT)));YC(this._triggerCheckDecodeSubject,__(()=>!this.ignoreDecodeError),B7(y),Iv(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,u;return(u=(l=(r=(i=this.room)==null?void 0:i.networkQuality)==null?void 0:r.hadRecentBadDownlink)==null?void 0:l.call(r,2))!=null&&u||this.player.isInAutoPlayFailedState}get isSubscribing(){return this.state.toString()==="subscribeing"}get isSubscribed(){return this.state===a3.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,u;const p=this.kind===zt.AUDIO;if(lr[i?"addSuccessEvent":"addFailedEvent"]({key:p?504700:514702}),!p){const y=((l=this.room)==null?void 0:l.downlinkVideoCodec.toUpperCase())||"H264";lr[i?"addSuccessEvent":"addFailedEvent"]({key:FX[`DECODE_${y}_RESULT`]}),i||this.log.warn(`${(u=this.room)==null?void 0:u.downlinkVideoCodec} decode failed`)}i||(lr.addEnum({key:p?504701:514703,value:rW()}),qC.uploadEvent({log:`stat-decode-failed-${this.kind}-${wX()||TX()}`,userId:this.room.userId}),this._log.warn(`decode failed: isPlaying: ${this.player.isPlaying} ${this.kind===zt.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()}};Ee(o_,"STATE_SUBSCRIBE","subscribe"),dc([ruA(5,1)],o_.prototype,"waitHasMediaTrack"),dc([du(Xn.INIT,o_.STATE_SUBSCRIBE,{success(){this.log.info("subscribed"),Qs.emit(mn.REMOTE_TRACK_SUBSCRIBED,{track:this})},ignoreError:!0}),l7(521716,!1)],o_.prototype,"subscribe"),dc([du(o_.STATE_SUBSCRIBE,Xn.INIT,{sync:!0,success(){this.log.info("unsubscribed"),Qs.emit(mn.REMOTE_TRACK_UNSUBSCRIBED,{track:this})}})],o_.prototype,"unsubscribe");var Ej=new Map;function uc(t,i){const r=zh(Rn({},i),{timestamp:Y3()});Ej.has(t)?Ej.get(t).push(r):Ej.set(t,[r])}Qs.on(mn.JOIN_SUCCESS,({room:t})=>{uc(t.userId,{eventId:32788})}),Qs.on(mn.LEAVE_START,({room:t})=>{uc(t.userId,{eventId:32789})}),Qs.on(mn.LOCAL_TRACK_PUBLISHED,({track:t})=>{if(t.room){let i=32769;t.mediaType===4?i=32768:t.mediaType===2&&(i=32805),uc(t.room.userId,{eventId:i})}}),Qs.on(mn.LOCAL_TRACK_UNPUBLISHED,({track:t})=>{if(t.room){let i=32771;t.mediaType===4?i=32770:t.mediaType===2&&(i=32806),uc(t.room.userId,{eventId:i})}}),Qs.on(mn.TRACK_MUTED,({track:t})=>{t.room&&(t.kind===zt.AUDIO?uc(t.room.userId,{eventId:t.isRemote?32785:32772,remoteUserId:t.isRemote?t.userId:void 0}):uc(t.room.userId,{eventId:t.isRemote?32784:32773,remoteUserId:t.isRemote?t.userId:void 0}))}),Qs.on(mn.TRACK_UNMUTED,({track:t})=>{t.room&&(t.kind===zt.AUDIO?uc(t.room.userId,{eventId:t.isRemote?32787:32774,remoteUserId:t.isRemote?t.userId:void 0}):uc(t.room.userId,{eventId:t.isRemote?32786:32775,remoteUserId:t.isRemote?t.userId:void 0}))}),Qs.on(mn.REMOTE_TRACK_SUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&uc(t.room.userId,{eventId:32777,remoteUserId:t.userId}),t.mediaType===4&&uc(t.room.userId,{eventId:32776,remoteUserId:t.userId}),t.mediaType===8&&uc(t.room.userId,{eventId:32803,remoteUserId:t.userId}))}),Qs.on(mn.REMOTE_TRACK_UNSUBSCRIBED,({track:t})=>{t.room&&(t.mediaType===1&&uc(t.room.userId,{eventId:32779,remoteUserId:t.userId}),t.mediaType===4&&uc(t.room.userId,{eventId:32778,remoteUserId:t.userId}),t.mediaType===8&&uc(t.room.userId,{eventId:32804,remoteUserId:t.userId}))}),Qs.on(mn.SWITCH_DEVICE_SUCCESS,({track:t})=>{t.room&&uc(t.room.userId,{eventId:t.kind===zt.VIDEO?32780:32781})}),Qs.on(mn.LOCAL_TRACK_REPLACED,({track:t})=>{t.room&&uc(t.room.userId,{eventId:t.kind===zt.VIDEO?32782:32783})}),Qs.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&&uc(t.userId,{eventId:l})}),Qs.on(mn.PEER_CONNECTION_STATE_CHANGED,({room:t,prevState:i,state:r,remoteUserId:l})=>{const u=!!l;let p;switch(r){case"CONNECTED":p=i==="RECONNECTING"?u?32801:32798:u?32793:32792;break;case"DISCONNECTED":i==="RECONNECTING"&&(p=u?32802:32799);break;case"RECONNECTING":p=u?32800:32797}p&&uc(t.userId,{eventId:p,remoteUserId:l})}),Qs.on(mn.VIDEO_CODEC_IMPLEMENTATION_CHANGED,({implementation:t,userId:i,remoteUserId:r,codec:l,isHWCodec:u,prevImplementation:p,streamType:y})=>{let w=u?1:0;p||(w=u?3:2);const _={H264:0,H265:1,VP8:2}[l.toUpperCase()],k={eventId:4004,param1:w,param2:_,streamType:y||2};r&&(k.remoteUserId=r,k.eventId=4005),uc(i,k),lr.addEnum({key:r?514701:513701,value:w}),lr.addEnum({key:r?514700:513700,value:_})}),Qs.on(mn.LOCAL_TRACK_RECAPTURE,({track:t,error:i})=>{if(t.userId){const r={eventId:2003,param1:0};t.kind===zt.AUDIO?(r.streamType=1,i&&(r.param1=2)):(r.streamType=t.streamType==="auxiliary"?7:2,i&&(r.param1=8)),uc(t.userId,r)}});O_(iU());O_(iU());var dj=0,f7=class y7{constructor(i){this.core=i,Ee(this,"seq"),Ee(this,"log"),Ee(this,"localMixVideoTrack",null),Ee(this,"systemAudioTrackList",{}),Ee(this,"_mixVideoConfig"),Ee(this,"onScreenShareStop"),Ee(this,"eventListeners",new Map),dj+=1,this.seq=dj,this.log=i.log.createChild({id:`${this.getAlias()}${dj}`}),this.log.info("created")}getName(){return y7.Name}getAlias(){return"vmix"}getValidateRule(i){switch(i){case"start":return agA(this.core);case"update":return ggA(this.core);case"stop":return cgA(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,u=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:u}}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:u}=i,p=await this.parseMixOptions(i);return await this._updatePreview({view:u,track:this.localMixVideoTrack,prevConfig:this._mixVideoConfig}),this.core.utils.isUndefined(u)||(this._mixVideoConfig.view=u),{track:this.localMixVideoTrack.outMediaTrack,systemAudioTrackList:this.systemAudioTrackList,result:p}}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 u=[],p=Rn({},i),{canvasInfo:y,camera:w,screen:_,text:k,image:F,video:j}=i;y&&this.parseCanvasOptions(y);let lA=0,aA=0;const mA=[{key:"camera",options:w,parser:this.parseCameraOptions.bind(this)},{key:"screen",options:_,parser:this.parseScreenOptions.bind(this)},{key:"text",options:k,parser:this.parseTextOptions.bind(this)},{key:"image",options:F,parser:this.parseImageOptions.bind(this)},{key:"video",options:j,parser:this.parseVideoOptions.bind(this)}];for(const{key:IA,options:tA,parser:MA}of mA)if(tA){lA++;const PA=await MA(this.localMixVideoTrack,tA,this._mixVideoConfig[IA]||[]);this._mixVideoConfig[IA]=PA.finalOptions,p[IA]=PA.finalOptions,PA.errors.length>0&&(u.push(...PA.errors),PA.errors.length===tA.length&&aA++)}if(aA>0&&aA===lA)throw new r({code:l.INVALID_PARAMETER,message:"all sources mix failed",data:{failedDetails:u}});return{successOptions:p,failedDetails:u}}parseCanvasOptions(i){if(!this.localMixVideoTrack||!this._mixVideoConfig)return;const{canvasColor:r,width:l,height:u,frameRate:p}=i;r&&this.localMixVideoTrack.setMixBackground(r),p&&this.localMixVideoTrack.setFps(p),this.localMixVideoTrack.resizeMixCanvas(l,u),this._mixVideoConfig.canvasInfo=i}prepareSourceOptions(i,r){const l=new Set(i.map(u=>u.id));return{removeIdList:r.filter(u=>!l.has(u.id)).map(u=>u.id),preOptionsMap:new Map(r.map(u=>[u.id,u]))}}recordSourceError(i,r,l,u,p){p.push({id:i,error:r}),l.has(i)&&u.push(l.get(i))}async parseCameraOptions(i,r,l=[]){const{removeIdList:u,preOptionsMap:p}=this.prepareSourceOptions(r,l);this.log.debug("videomixer removeIdList",r,u,p);for(const _ of u)i.removeCameraSource(_),this.removeEventListeners(_);const y=[],w=[];for(const _ of r)try{await this.processSingleCameraSource(i,_),y.push(_)}catch(k){this.recordSourceError(_.id,k,p,y,w)}return{finalOptions:y,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,u;const{id:p,layout:y,profile:w}=r,_=(l=i.inputLocalVideoTracks.get(p))==null?void 0:l.mediaTrack;await this.updateCameraProfile(r);const k=(u=i.inputLocalVideoTracks.get(p))==null?void 0:u.mediaTrack,F=this.resolveVideoProfile(w);k!==_?i.updateCameraSource(p,y,k,F):i.updateCameraSource(p,y,null,F)}resolveCameraInternalTrack(i,r){var l;const{id:u,layout:p,profile:y,useInternalTrack:w}=r;if(w){if(i.inputLocalVideoTracks.get(u))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(u);const _=F=>{var j,lA;const aA=i.inputLocalVideoTracks.get(u);this.log.debug(`camera internal track preprocessed event from ${(j=F.room)==null?void 0:j.userId} to ${this.core.room.userId}, is same instance:${F.room===this.core.room} ,new track:`,F.mediaTrack,aA?.mediaTrack,i.outMediaTrack),((lA=F.mediaTrack)==null?void 0:lA.kind)!==zt.AUDIO&&aA?.mediaTrack!==F.mediaTrack&&i.outMediaTrack!==F.mediaTrack&&F.room===this.core.room?aA&&F.mediaTrack&&i.updateCameraSource(u,p,F.mediaTrack):this.log.debug("camera internal track preprocessed event return")},k=F=>{var j,lA,aA,mA,IA,tA,MA,PA;const ge=i.inputLocalVideoTracks.get(u);this.log.debug(`camera internal track stopped ${((j=F.track)==null?void 0:j.mediaTrack)===ge?.mediaTrack||((lA=F.track)==null?void 0:lA.outMediaTrack)===ge?.mediaTrack||((aA=F.track)==null?void 0:aA.outMediaTrack)===i.outMediaTrack}`,(mA=F.track)==null?void 0:mA.mediaTrack,(IA=F.track)==null?void 0:IA.outMediaTrack,ge?.mediaTrack,i.outMediaTrack),!ge||((tA=F.track)==null?void 0:tA.mediaTrack)!==ge?.mediaTrack&&((MA=F.track)==null?void 0:MA.outMediaTrack)!==ge?.mediaTrack&&((PA=F.track)==null?void 0:PA.outMediaTrack)!==i.outMediaTrack||i.updateCameraSource(u,p,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("118",_),this.core.innerEmitter.on("117",k),this.eventListeners.has(u)||this.eventListeners.set(u,{}),this.eventListeners.get(u).captureSuccess=()=>{this.core.innerEmitter.off("118",_)},this.eventListeners.get(u).trackStop=()=>{this.core.innerEmitter.off("117",k)}}return r}async addNewCameraSource(i,r){const{id:l,layout:u,useInternalTrack:p}=r,y=await this.captureCamera(r);try{i.addCameraSource(l,y,u)}catch(w){throw y.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:u,preOptionsMap:p}=this.prepareSourceOptions(r,l);for(const _ of u)i.removeScreenSource(_),this.removeSystemAudioTrack(_),this.removeEventListeners(_);const y=[],w=[];for(const _ of r)try{await this.processSingleScreenSource(i,_,p),y.push(_)}catch(k){this.recordSourceError(_.id,k,p,y,w)}return{finalOptions:y,errors:w}}async processSingleScreenSource(i,r,l){const{id:u,layout:p,useInternalTrack:y}=r;this.resolveScreenInternalTrack(i,r);const w=l.get(u),_=i.inputLocalScreenTracks.has(u),k=!w?.systemAudio&&r.systemAudio;_&&!k?this.updateExistingScreenSource(i,u,p,w,r):await this.addNewScreenSource(i,r,w)}updateExistingScreenSource(i,r,l,u,p){i.updateScreenSource(r,l),u?.systemAudio&&!p.systemAudio&&this.removeSystemAudioTrack(r)}resolveScreenInternalTrack(i,r){var l,u;const{id:p,layout:y,useInternalTrack:w}=r;if(w){if(i.inputLocalScreenTracks.get(p))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,(u=this.core.trtc.localScreenAudioTrack)!=null&&u.mediaTrack&&(r.audioTrack=this.core.trtc.localScreenAudioTrack.mediaTrack),delete r.captureElement,delete r.preferDisplaySurface,delete r.systemAudio):r.videoTrack=this.createPlaceholderVideoTrack(),this.removeEventListeners(p);const _=F=>{var j,lA,aA,mA,IA,tA,MA;const PA=i.inputLocalScreenTracks.get(p);this.log.debug(`screen internal track capture success event from ${(j=F.room)==null?void 0:j.userId} to ${this.core.room.userId}, is same instance:${F.room===this.core.room}, isScreen:${(lA=F.track)==null?void 0:lA.isScreen} kind:${(aA=F.track)==null?void 0:aA.kind}`,PA,F.track.sourceTrack),(mA=F.track)!=null&&mA.isScreen&&((IA=F.track)==null?void 0:IA.kind)!==zt.AUDIO&&PA&&(this.log.debug("screen internal track capture success event ",(tA=F.track)==null?void 0:tA.sourceTrack),(MA=F.track)!=null&&MA.sourceTrack&&i.updateScreenSource(p,y,F.track.sourceTrack))},k=F=>{var j,lA;const aA=i.inputLocalScreenTracks.get(p);this.log.debug(`screen internal track stopped, is same track:${((j=F.track)==null?void 0:j.sourceTrack)===aA?.mediaTrack}, isScreen:${F.track.isScreen}`),F.track.isScreen&&((lA=F.track)==null?void 0:lA.sourceTrack)===aA?.mediaTrack&&i.updateScreenSource(p,y,this.createPlaceholderVideoTrack())};this.core.innerEmitter.on("102",_),this.core.innerEmitter.on("117",k),this.eventListeners.has(p)||this.eventListeners.set(p,{}),this.eventListeners.get(p).captureSuccess=()=>{this.core.innerEmitter.off("102",_)},this.eventListeners.get(p).trackStop=()=>{this.core.innerEmitter.off("117",k)}}return r}async addNewScreenSource(i,r,l){const{id:u,layout:p}=r,y=await this.captureScreen(r);!l?.systemAudio&&r.systemAudio&&i.inputLocalScreenTracks.has(u)&&i.removeScreenSource(u);try{i.addScreenSource(u,y,p)}catch(w){throw y.close(),w}}async parseTextOptions(i,r,l=[]){const{removeIdList:u,preOptionsMap:p}=this.prepareSourceOptions(r,l);for(const _ of u)i.removeTextSource(_);const y=[],w=[];for(const _ of r)try{p.has(_.id)?i.updateTextSource(_):i.addTextSource(_),y.push(_)}catch(k){this.recordSourceError(_.id,k,p,y,w)}return{finalOptions:y,errors:w}}async parseImageOptions(i,r,l=[]){const{removeIdList:u,preOptionsMap:p}=this.prepareSourceOptions(r,l);for(const _ of u)i.removeImageSource(_);const y=[],w=[];for(const _ of r)try{await this.processSingleImageSource(i,_,p),y.push(_)}catch(k){this.recordSourceError(_.id,k,p,y,w)}return{finalOptions:y,errors:w}}async processSingleImageSource(i,r,l){const{id:u,url:p,layout:y}=r,w=l.get(u);if(w){let _;w.url!==p&&(_=await this.core.utils.loadImage(p)),i.updateImageSource(u,y,_)}else{const _=await this.core.utils.loadImage(p);i.addImageSource(u,_,y)}}async parseVideoOptions(i,r,l=[]){const{removeIdList:u,preOptionsMap:p}=this.prepareSourceOptions(r,l);for(const _ of u)i.removeVideoSource(_);const y=[],w=[];for(const _ of r)try{await this.processSingleVideoSource(i,_,p),y.push(_)}catch(k){this.recordSourceError(_.id,k,p,y,w)}return{finalOptions:y,errors:w}}async processSingleVideoSource(i,r,l){const{id:u,url:p,layout:y}=r,w=l.get(u);if(w){let _;w.url!==p&&(_=await this.core.utils.loadVideo(p)),i.updateVideoSource(u,y,_)}else{const _=await this.core.utils.loadVideo(p);i.addVideoSource(u,_,y)}}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 u=1e3/30,p=i.captureStream(30).getVideoTracks()[0],y=()=>{r.fillStyle="rgba(255, 255, 255, 0)",r.fillRect(0,0,i.width,i.height),p.readyState==="live"&&(l=setTimeout(y,u))};y();const w=p.stop.bind(p);return p.stop=()=>{l&&(clearTimeout(l),l=null),w()},p}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:u,profile:p}=i,y=new this.core.LocalVideoTrack;y.log.id+=`-${r}`;const w={};if(l?w.deviceId=l:this.core.utils.isUndefined(u)||(w.customSource=u),!this.core.utils.isUndefined(p)){const _=this.resolveVideoProfile(p);_&&y.setProfile(_)}return await y.capture(w),y}async updateCameraProfile(i){var r;const{id:l,cameraId:u,videoTrack:p,profile:y}=i,w=(r=this.localMixVideoTrack)==null?void 0:r.inputLocalVideoTracks.get(l);if(w&&(u?await w.switchDevice(u):this.core.utils.isUndefined(p)||await w.setInputMediaStreamTrack(p),!this.core.utils.isUndefined(y))){const _=this.resolveVideoProfile(y);_&&w.setProfile(_),u&&w.isNeedToSwitchDevice(u)||await w.applyProfile()}}async captureScreen(i){const{id:r,profile:l,captureElement:u,preferDisplaySurface:p,systemAudio:y,videoTrack:w,audioTrack:_}=i,k=new this.core.LocalScreenTrack;k.log.id+=`-${r}`;const F={captureElement:u,preferDisplaySurface:p,systemAudio:y,videoTrack:w,audioTrack:_};if(!this.core.utils.isUndefined(l))if(this.core.utils.isString(l)){const lA=this.core.constants.screenProfileMap[l];lA&&k.setProfile(lA)}else k.setProfile(l);const j=await k.capture(F);return y&&j.getAudioTracks().length>0?(this.systemAudioTrackList[r]=j.getAudioTracks()[0],this.log.info(`${r} system audio track captured`)):this.removeSystemAudioTrack(r),k.mediaTrack.addEventListener(this.core.constants.NAME.ENDED,()=>{this.handleScreenShareEnded(r)}),k}handleScreenShareEnded(i){var r,l,u;(r=this.localMixVideoTrack)==null||r.removeScreenSource(i),(l=this._mixVideoConfig)!=null&&l.screen&&(this._mixVideoConfig.screen=this._mixVideoConfig.screen.filter(p=>p.id!==i)),(u=this.onScreenShareStop)==null||u.call(this,i)}async _updatePreview({view:i,track:r,prevConfig:l}){if(this.core.utils.isUndefined(i)&&l?.view){const u=this.core.utils.getViewListFromView(l.view);return void(u.length>0&&await r.play(u))}if(!this.core.utils.isUndefined(i)){const u=this.core.utils.getViewListFromView(i);u.length>0?await r.play(u):r.stop()}}removeSystemAudioTrack(i){const r=this.systemAudioTrackList[i];r&&(r.stop(),this.log.info(`${i} system audio track stop`),delete this.systemAudioTrackList[i])}};Ee(f7,"Name","VideoMixer");var D7=f7,auA=D7;const guA=Object.freeze(Object.defineProperty({__proto__:null,VideoMixer:D7,default:auA},Symbol.toStringTag,{value:"Module"})),cuA=ZL(guA);var luA=$k.exports,U8;function IuA(){return U8||(U8=1,function(t,i){(function(r,l){l(i,BnA(),JnA,baA,VaA,ZaA,cuA)})(luA,function(r,l,u,p,y,w,_){function k(q){return q&&typeof q=="object"&&"default"in q?q:{default:q}}var F=k(l),j=k(_),lA=function(q,L){return lA=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(sA,G){sA.__proto__=G}||function(sA,G){for(var x in G)Object.prototype.hasOwnProperty.call(G,x)&&(sA[x]=G[x])},lA(q,L)},aA=function(){return aA=Object.assign||function(q){for(var L,sA=1,G=arguments.length;sA=0;_A--)(x=q[_A])&&(uA=(iA<3?x(uA):iA>3?x(L,sA,uA):x(L,sA))||uA);return iA>3&&uA&&Object.defineProperty(L,sA,uA),uA}function IA(q,L,sA,G){return new(sA||(sA=Promise))(function(x,iA){function uA(Qe){try{XA(G.next(Qe))}catch(Q){iA(Q)}}function _A(Qe){try{XA(G.throw(Qe))}catch(Q){iA(Q)}}function XA(Qe){var Q;Qe.done?x(Qe.value):(Q=Qe.value,Q instanceof sA?Q:new sA(function(h){h(Q)})).then(uA,_A)}XA((G=G.apply(q,[])).next())})}function tA(q,L){var sA,G,x,iA,uA={label:0,sent:function(){if(1&x[0])throw x[1];return x[1]},trys:[],ops:[]};return iA={next:_A(0),throw:_A(1),return:_A(2)},typeof Symbol=="function"&&(iA[Symbol.iterator]=function(){return this}),iA;function _A(XA){return function(Qe){return function(Q){if(sA)throw new TypeError("Generator is already executing.");for(;iA&&(iA=0,Q[0]&&(uA=0)),uA;)try{if(sA=1,G&&(x=2&Q[0]?G.return:Q[0]?G.throw||((x=G.return)&&x.call(G),0):G.next)&&!(x=x.call(G,Q[1])).done)return x;switch(G=0,x&&(Q=[2&Q[0],x.value]),Q[0]){case 0:case 1:x=Q;break;case 4:return uA.label++,{value:Q[1],done:!1};case 5:uA.label++,G=Q[1],Q=[0];continue;case 7:Q=uA.ops.pop(),uA.trys.pop();continue;default:if(x=uA.trys,!((x=x.length>0&&x[x.length-1])||Q[0]!==6&&Q[0]!==2)){uA=0;continue}if(Q[0]===3&&(!x||Q[1]>x[0]&&Q[1]=q.length&&(q=void 0),{value:q&&q[G++],done:!q}}};throw new TypeError(L?"Object is not iterable.":"Symbol.iterator is not defined.")}function PA(q,L,sA){if(sA||arguments.length===2)for(var G,x=0,iA=L.length;x0&&Jt[0]<4?1:+(Jt[0]+Jt[1])),!fg&&pc&&(!(Jt=pc.match(/Edge\/(\d+)/))||Jt[1]>=74)&&(Jt=pc.match(/Chrome\/(\d+)/))&&(fg=+Jt[1]);var Ia=fg,yn=Gn.String,Ga=!!Object.getOwnPropertySymbols&&!Vs(function(){var q=Symbol("symbol detection");return!yn(q)||!(Object(q)instanceof Symbol)||!Symbol.sham&&Ia&&Ia<41}),ya=Ga&&!Symbol.sham&&typeof Symbol.iterator=="symbol",$=Object,K=ya?function(q){return typeof q=="symbol"}:function(q){var L=Js("Symbol");return wo(L)&&Dg(L.prototype,$(q))},RA=String,KA=TypeError,Ae=function(q){if(wo(q))return q;throw KA(function(L){try{return RA(L)}catch{return"Object"}}(q)+" is not a function")},pe=function(q,L){var sA=q[L];return Zi(sA)?void 0:Ae(sA)},Fe=TypeError,Ue=Object.defineProperty,ot=function(q,L){try{Ue(Gn,q,{value:L,configurable:!0,writable:!0})}catch{Gn[q]=L}return L},ut="__core-js_shared__",St=Gn[ut]||ot(ut,{}),Ot=Ve(function(q){(q.exports=function(L,sA){return St[L]||(St[L]=sA!==void 0?sA:{})})("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"})}),li=Object,nt=function(q){return li(sg(q))},Ft=rs({}.hasOwnProperty),Ji=Object.hasOwn||function(q,L){return Ft(nt(q),L)},qi=0,Hs=Math.random(),Mi=rs(1 .toString),Wo=function(q){return"Symbol("+(q===void 0?"":q)+")_"+Mi(++qi+Hs,36)},Sg=Gn.Symbol,or=Ot("wks"),fr=ya?Sg.for||Sg:Sg&&Sg.withoutSetter||Wo,xn=function(q){return Ji(or,q)||(or[q]=Ga&&Ji(Sg,q)?Sg[q]:fr("Symbol."+q)),or[q]},yl=TypeError,qs=xn("toPrimitive"),tI=function(q,L){if(!Hn(q)||K(q))return q;var sA,G=pe(q,qs);if(G){if(sA=po(G,q,L),!Hn(sA)||K(sA))return sA;throw yl("Can't convert object to primitive value")}return function(x,iA){var uA,_A;if(wo(uA=x.toString)&&!Hn(_A=po(uA,x))||wo(uA=x.valueOf)&&!Hn(_A=po(uA,x)))return _A;throw Fe("Can't convert object to primitive value")}(q)},jg=function(q){var L=tI(q,"string");return K(L)?L:L+""},mc=Gn.document,Qu=Hn(mc)&&Hn(mc.createElement),Da=function(q){return Qu?mc.createElement(q):{}},Dl=!Qr&&!Vs(function(){return Object.defineProperty(Da("div"),"a",{get:function(){return 7}}).a!==7}),fe=Object.getOwnPropertyDescriptor,me={f:Qr?fe:function(q,L){if(q=yg(q),L=jg(L),Dl)try{return fe(q,L)}catch{}if(Ji(q,L))return mr(!po(cn.f,q,L),q[L])}},Mg=Qr&&Vs(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!==42}),ng=String,vg=TypeError,Dn=function(q){if(Hn(q))return q;throw vg(ng(q)+" is not an object")},yr=TypeError,Ii=Object.defineProperty,so=Object.getOwnPropertyDescriptor,Jc="enumerable",Wg="configurable",Rg="writable",Or={f:Qr?Mg?function(q,L,sA){if(Dn(q),L=jg(L),Dn(sA),typeof q=="function"&&L==="prototype"&&"value"in sA&&Rg in sA&&!sA[Rg]){var G=so(q,L);G&&G[Rg]&&(q[L]=sA.value,sA={configurable:Wg in sA?sA[Wg]:G[Wg],enumerable:Jc in sA?sA[Jc]:G[Jc],writable:!1})}return Ii(q,L,sA)}:Ii:function(q,L,sA){if(Dn(q),L=jg(L),Dn(sA),Dl)try{return Ii(q,L,sA)}catch{}if("get"in sA||"set"in sA)throw yr("Accessors not supported");return"value"in sA&&(q[L]=sA.value),q}},fc=Qr?function(q,L,sA){return Or.f(q,L,mr(1,sA))}:function(q,L,sA){return q[L]=sA,q},Hc=Function.prototype,rg=Qr&&Object.getOwnPropertyDescriptor,pu=Ji(Hc,"name"),uE={CONFIGURABLE:pu&&(!Qr||Qr&&rg(Hc,"name").configurable)},wg=rs(Function.toString);wo(St.inspectSource)||(St.inspectSource=function(q){return wg(q)});var ba,yc,EE,ka=St.inspectSource,oa=Gn.WeakMap,_g=wo(oa)&&/native code/.test(String(oa)),iI=Ot("keys"),Cs=function(q){return iI[q]||(iI[q]=Wo(q))},ko={},ua="Object already initialized",sr=Gn.TypeError,Pt=Gn.WeakMap;if(_g||St.state){var Ht=St.state||(St.state=new Pt);Ht.get=Ht.get,Ht.has=Ht.has,Ht.set=Ht.set,ba=function(q,L){if(Ht.has(q))throw sr(ua);return L.facade=q,Ht.set(q,L),L},yc=function(q){return Ht.get(q)||{}},EE=function(q){return Ht.has(q)}}else{var Tg=Cs("state");ko[Tg]=!0,ba=function(q,L){if(Ji(q,Tg))throw sr(ua);return L.facade=q,fc(q,Tg,L),L},yc=function(q){return Ji(q,Tg)?q[Tg]:{}},EE=function(q){return Ji(q,Tg)}}var oI={get:yc,enforce:function(q){return EE(q)?yc(q):ba(q,{})}},nr=Ve(function(q){var L=uE.CONFIGURABLE,sA=oI.enforce,G=oI.get,x=String,iA=Object.defineProperty,uA=rs("".slice),_A=rs("".replace),XA=rs([].join),Qe=Qr&&!Vs(function(){return iA(function(){},"length",{value:8}).length!==8}),Q=String(String).split("String"),h=q.exports=function(v,N,O){uA(x(N),0,7)==="Symbol("&&(N="["+_A(x(N),/^Symbol\(([^)]*)\)/,"$1")+"]"),O&&O.getter&&(N="get "+N),O&&O.setter&&(N="set "+N),(!Ji(v,"name")||L&&v.name!==N)&&(Qr?iA(v,"name",{value:N,configurable:!0}):v.name=N),Qe&&O&&Ji(O,"arity")&&v.length!==O.arity&&iA(v,"length",{value:O.arity});try{O&&Ji(O,"constructor")&&O.constructor?Qr&&iA(v,"prototype",{writable:!1}):v.prototype&&(v.prototype=void 0)}catch{}var z=sA(v);return Ji(z,"source")||(z.source=XA(Q,typeof N=="string"?N:"")),v};Function.prototype.toString=h(function(){return wo(this)&&G(this).source||ka(this)},"toString")}),UI=function(q,L,sA,G){G||(G={});var x=G.enumerable,iA=G.name!==void 0?G.name:L;if(wo(sA)&&nr(sA,iA,G),G.global)x?q[L]=sA:ot(L,sA);else{try{G.unsafe?q[L]&&(x=!0):delete q[L]}catch{}x?q[L]=sA:Or.f(q,L,{value:sA,enumerable:!1,configurable:!G.nonConfigurable,writable:!G.nonWritable})}return q},Wa=Math.ceil,sa=Math.floor,un=Math.trunc||function(q){var L=+q;return(L>0?sa:Wa)(L)},Sn=function(q){var L=+q;return L!=L||L===0?0:un(L)},mu=Math.max,Ng=Math.min,La=Math.min,qc=function(q){return q>0?La(Sn(q),9007199254740991):0},FI=function(q){return qc(q.length)},dE=function(q){return function(L,sA,G){var x,iA=yg(L),uA=FI(iA),_A=function(XA,Qe){var Q=Sn(XA);return Q<0?mu(Q+Qe,0):Ng(Q,Qe)}(G,uA);if(q&&sA!=sA){for(;uA>_A;)if((x=iA[_A++])!=x)return!0}else for(;uA>_A;_A++)if((q||_A in iA)&&iA[_A]===sA)return q||_A||0;return!q&&-1}},sI={indexOf:dE(!1)}.indexOf,fu=rs([].push),Sl=function(q,L){var sA,G=yg(q),x=0,iA=[];for(sA in G)!Ji(ko,sA)&&Ji(G,sA)&&fu(iA,sA);for(;L.length>x;)Ji(G,sA=L[x++])&&(~sI(iA,sA)||fu(iA,sA));return iA},Dc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],yu=Dc.concat("length","prototype"),Du={f:Object.getOwnPropertyNames||function(q){return Sl(q,yu)}},Ml={f:Object.getOwnPropertySymbols},ss=rs([].concat),as=Js("Reflect","ownKeys")||function(q){var L=Du.f(Dn(q)),sA=Ml.f;return sA?ss(L,sA(q)):L},td=function(q,L,sA){for(var G=as(L),x=Or.f,iA=me.f,uA=0;uAuA;)Or.f(q,sA=x[uA++],G[sA]);return q},OI={f:Su},Wc=Js("document","documentElement"),zc="prototype",PI="script",aI=Cs("IE_PROTO"),Zc=function(){},Xc=function(q){return"<"+PI+">"+q+""},Sa=function(q){q.write(Xc("")),q.close();var L=q.parentWindow.Object;return q=null,L},Gg=function(){try{Ea=new ActiveXObject("htmlfile")}catch{}var q,L,sA;Gg=typeof document<"u"?document.domain&&Ea?Sa(Ea):(L=Da("iframe"),sA="java"+PI+":",L.style.display="none",Wc.appendChild(L),L.src=String(sA),(q=L.contentWindow.document).open(),q.write(Xc("document.F=Object")),q.close(),q.F):Sa(Ea);for(var G=Dc.length;G--;)delete Gg[zc][Dc[G]];return Gg()};ko[aI]=!0;var fs,Kn,Mc=Object.create||function(q,L){var sA;return q!==null?(Zc[zc]=Dn(q),sA=new Zc,Zc[zc]=null,sA[aI]=q):sA=Gg(),L===void 0?sA:OI.f(sA,L)},xI=Gn.RegExp,YI=Vs(function(){var q=xI(".","s");return!(q.dotAll&&q.exec(` +`)&&q.flags==="s")}),BE=Gn.RegExp,zC=Vs(function(){var q=BE("(?b)","g");return q.exec("b").groups.a!=="b"||"b".replace(q,"$c")!=="bc"}),eC=oI.get,ZC=Ot("native-string-replace",String.prototype.replace),$c=RegExp.prototype.exec,bg=$c,no=rs("".charAt),tC=rs("".indexOf),QE=rs("".replace),pE=rs("".slice),nd=(Kn=/b*/g,po($c,fs=/a/,"a"),po($c,Kn,"a"),fs.lastIndex!==0||Kn.lastIndex!==0),mE=sd.BROKEN_CARET,Al=/()??/.exec("")[1]!==void 0;(nd||Al||mE||YI||zC)&&(bg=function(q){var L,sA,G,x,iA,uA,_A,XA=this,Qe=eC(XA),Q=Zg(q),h=Qe.raw;if(h)return h.lastIndex=XA.lastIndex,L=po(bg,h,Q),XA.lastIndex=h.lastIndex,L;var v=Qe.groups,N=mE&&XA.sticky,O=po(qn,XA),z=XA.source,X=0,rA=Q;if(N&&(O=QE(O,"y",""),tC(O,"g")===-1&&(O+="g"),rA=pE(Q,XA.lastIndex),XA.lastIndex>0&&(!XA.multiline||XA.multiline&&no(Q,XA.lastIndex-1)!==` +`)&&(z="(?: "+z+")",rA=" "+rA,X++),sA=new RegExp("^(?:"+z+")",O)),Al&&(sA=new RegExp("^"+z+"$(?!\\s)",O)),nd&&(G=XA.lastIndex),x=po($c,N?sA:XA,rA),N?x?(x.input=pE(x.input,X),x[0]=pE(x[0],X),x.index=XA.lastIndex,XA.lastIndex+=x[0].length):XA.lastIndex=0:nd&&x&&(XA.lastIndex=XA.global?x.index+x[0].length:G),Al&&x&&x.length>1&&po(ZC,x[0],sA,function(){for(iA=1;iA=_A?q?"":void 0:(G=lI(iA,uA))<55296||G>56319||uA+1===_A||(x=lI(iA,uA+1))<56320||x>57343?q?ad(iA,uA):G:q?Fa(iA,uA,uA+2):x-56320+(G-55296<<10)+65536}},Oa={charAt:sC(!0)}.charAt,Ir=function(q,L,sA){return L+(sA?Oa(q,L).length:1)},gd=TypeError,wu=function(q,L){var sA=q.exec;if(wo(sA)){var G=po(sA,q,L);return G!==null&&Dn(G),G}if(ds(q)==="RegExp")return po(gI,q,L);throw gd("RegExp#exec called on incompatible receiver")};(function(q,L,sA,G){var x=xn(q),iA=!Vs(function(){var Qe={};return Qe[x]=function(){return 7},""[q](Qe)!==7}),uA=iA&&!Vs(function(){var Qe=!1,Q=/a/;return q==="split"&&((Q={}).constructor={},Q.constructor[oC]=function(){return Q},Q.flags="",Q[x]=/./[x]),Q.exec=function(){return Qe=!0,null},Q[x](""),!Qe});if(!iA||!uA||sA){var _A=_n(/./[x]),XA=L(x,""[q],function(Qe,Q,h,v,N){var O=_n(Qe),z=Q.exec;return z===gI||z===el.exec?iA&&!N?{done:!0,value:_A(Q,h,v)}:{done:!0,value:O(h,Q,v)}:{done:!1}});UI(String.prototype,q,XA[0]),UI(el,x,XA[1])}})("match",function(q,L,sA){return[function(G){var x=sg(this),iA=Zi(G)?void 0:pe(G,q);return iA?po(iA,G,x):new RegExp(G)[q](Zg(x))},function(G){var x=Dn(this),iA=Zg(G),uA=sA(L,x,iA);if(uA.done)return uA.value;if(!x.global)return wu(x,iA);var _A=x.unicode;x.lastIndex=0;for(var XA,Qe=[],Q=0;(XA=wu(x,iA))!==null;){var h=Zg(XA[0]);Qe[Q]=h,h===""&&(x.lastIndex=Ir(iA,qc(x.lastIndex),_A)),Q++}return Q===0?null:Qe}]});var ur=Array.isArray||function(q){return ds(q)==="Array"},Rc=TypeError,tl=function(q){if(q>9007199254740991)throw Rc("Maximum allowed index exceeded");return q},kg=function(q,L,sA){var G=jg(L);G in q?Or.f(q,G,mr(0,sA)):q[G]=sA},Fo=function(){},Xg=[],za=Js("Reflect","construct"),wl=/^\s*(?:class|function)\b/,Xr=rs(wl.exec),XC=!wl.exec(Fo),Ks=function(q){if(!wo(q))return!1;try{return za(Fo,Xg,q),!0}catch{return!1}},VI=function(q){if(!wo(q))return!1;switch(ag(q)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return XC||!!Xr(wl,ka(q))}catch{return!0}};VI.sham=!0;var Ls,wc=!za||Vs(function(){var q;return Ks(Ks.call)||!Ks(Object)||!Ks(function(){q=!0})||q})?VI:Ks,$g=xn("species"),Er=Array,Pr=function(q,L){return new(function(sA){var G;return ur(sA)&&(G=sA.constructor,(wc(G)&&(G===Er||ur(G.prototype))||Hn(G)&&(G=G[$g])===null)&&(G=void 0)),G===void 0?Er:G}(q))(0)},Za=xn("species"),fE=xn("isConcatSpreadable"),nC=Ia>=51||!Vs(function(){var q=[];return q[fE]=!1,q.concat()[0]!==q}),$C=function(q){if(!Hn(q))return!1;var L=q[fE];return L!==void 0?!!L:ur(q)};en({target:"Array",proto:!0,arity:1,forced:!(nC&&(Ls="concat",Ia>=51||!Vs(function(){var q=[];return(q.constructor={})[Za]=function(){return{foo:1}},q[Ls](Boolean).foo!==1})))},{concat:function(q){var L,sA,G,x,iA,uA=nt(this),_A=Pr(uA),XA=0;for(L=-1,G=arguments.length;L=5||Math.abs(G)>=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)):cg.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 sA=L.screenX-this.moveStartOfLeft,G=L.screenY-this.moveStartOfTop,x=this.originLeft+sA,iA=this.originTop+G,uA=this.movable.offsetWidth,_A=this.movable.offsetHeight,XA=this.container.offsetWidth,Qe=this.container.offsetHeight;this.options.canExceedContainer||(x<0?x=0:x>XA-uA&&(x=XA-uA),iA<0?iA=0:iA>Qe-_A&&(iA=Qe-_A)),!this.options.calcPositionOnly&&this.movable&&(this.movable.style.left="".concat(x,"px"),this.movable.style.top="".concat(iA,"px")),this.emit("move",x,iA)}else cg.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,sA){var G=this.callbacksMap.get(L);G?G.push(sA):this.callbacksMap.set(L,[sA])},q.prototype.off=function(L,sA){var G=this.callbacksMap.get(L);G&&(G=G.filter(function(x){return x!=sA}),this.callbacksMap.set(L,G))},q.prototype.emit=function(L){for(var sA=[],G=1;G ").concat(L)),this.enabled=L,this.movable&&(this.movable.style.cursor=L?"move":"default",cg.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"})(ra||(ra={}));var RE="trtc-resizable-top-left-anchor",Gu="trtc-resizable-top-anchor",bu="trtc-resizable-top-right-anchor",hI="trtc-resizable-left-anchor",rl="trtc-resizable-right-anchor",Gr="trtc-resizable-bottom-left-anchor",br="trtc-resizable-bottom-anchor",lg="trtc-resizable-bottom-right-anchor",rr={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 vr(q,L){for(var sA in L)q.style[sA]=L[sA]}var tc=function(){function q(L,sA,G){G===void 0&&(G={keepRatio:!1,stopPropagation:!1,anchorMode:ra.Both,canExceedContainer:!1}),this.logPrefix="[Resizable]",this.container=null,this.options={keepRatio:!1,stopPropagation:!1,anchorMode:ra.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=sA||document.body,this.options={keepRatio:!!G.keepRatio||!1,stopPropagation:!!G.stopPropagation||!1,anchorMode:G.anchorMode||ra.Both,canExceedContainer:!!G.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,sA,G,x,iA,uA,_A,XA,Qe=document.createElement("div");Qe.className="trtc-resizable-resize-anchor ".concat(RE),vr(Qe,Object.assign({},rr.resizeAnchor,rr.topLeftAnchor)),this.topLeftAnchor=Qe;var Q=document.createElement("div");Q.className="trtc-resizable-resize-anchor ".concat(Gu),vr(Q,Object.assign({},rr.resizeAnchor,rr.topAnchor)),this.topAnchor=Q;var h=document.createElement("div");h.className="trtc-resizable-resize-anchor ".concat(bu),vr(h,Object.assign({},rr.resizeAnchor,rr.topRightAnchor)),this.topRightAnchor=h;var v=document.createElement("div");v.className="trtc-resizable-resize-anchor ".concat(hI),vr(v,Object.assign({},rr.resizeAnchor,rr.leftAnchor)),this.leftAnchor=v;var N=document.createElement("div");N.className="trtc-resizable-resize-anchor ".concat(rl),vr(N,Object.assign({},rr.resizeAnchor,rr.rightAnchor)),this.rightAnchor=N;var O=document.createElement("div");O.className="trtc-resizable-resize-anchor ".concat(Gr),vr(O,Object.assign({},rr.resizeAnchor,rr.bottomLeftAnchor)),this.bottomLeftAnchor=O;var z=document.createElement("div");z.className="trtc-resizable-resize-anchor ".concat(br),vr(z,Object.assign({},rr.resizeAnchor,rr.bottomAnchor)),this.bottomAnchor=z;var X=document.createElement("div");X.className="trtc-resizable-resize-anchor ".concat(lg),vr(X,Object.assign({},rr.resizeAnchor,rr.bottomRightAnchor)),this.bottomRightAnchor=X,this.options.anchorMode!==ra.Both&&this.options.anchorMode!==ra.Edge||((L=this.resizeTarget)===null||L===void 0||L.appendChild(Q),(sA=this.resizeTarget)===null||sA===void 0||sA.appendChild(v),(G=this.resizeTarget)===null||G===void 0||G.appendChild(N),(x=this.resizeTarget)===null||x===void 0||x.appendChild(z)),this.options.anchorMode!==ra.Both&&this.options.anchorMode!==ra.Corner||((iA=this.resizeTarget)===null||iA===void 0||iA.appendChild(Qe),(uA=this.resizeTarget)===null||uA===void 0||uA.appendChild(h),(_A=this.resizeTarget)===null||_A===void 0||_A.appendChild(O),(XA=this.resizeTarget)===null||XA===void 0||XA.appendChild(X))},q.prototype.initResizeEvent=function(){var L,sA,G,x,iA,uA,_A,XA;(L=this.topLeftAnchor)===null||L===void 0||L.addEventListener("mousedown",this.mousedown,!1),(sA=this.topAnchor)===null||sA===void 0||sA.addEventListener("mousedown",this.mousedown,!1),(G=this.topRightAnchor)===null||G===void 0||G.addEventListener("mousedown",this.mousedown,!1),(x=this.leftAnchor)===null||x===void 0||x.addEventListener("mousedown",this.mousedown,!1),(iA=this.rightAnchor)===null||iA===void 0||iA.addEventListener("mousedown",this.mousedown,!1),(uA=this.bottomLeftAnchor)===null||uA===void 0||uA.addEventListener("mousedown",this.mousedown,!1),(_A=this.bottomAnchor)===null||_A===void 0||_A.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 sA=document.defaultView.getComputedStyle(this.resizeTarget);this.originTop=window.parseInt(sA.top),this.originLeft=window.parseInt(sA.left),this.originWidth=this.resizeTarget.offsetWidth,this.originHeight=this.resizeTarget.offsetHeight,cg.debug("resize origin:",this.originTop,this.originLeft,this.originWidth,this.originHeight)}else cg.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 sA,G=this.currentAnchor.classList[1],x=this.originLeft,iA=this.originTop,uA=this.originWidth,_A=this.originHeight;switch(G){case RE:iA=(sA=this._resizeTop(L)).top,_A=sA.height,x=(sA=this._resizeLeft(L)).left,uA=sA.width,this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?(_A=uA*this.originHeight/this.originWidth,iA=this.originTop+this.originHeight-_A):(uA=_A*this.originWidth/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case Gu:iA=(sA=this._resizeTop(L)).top,_A=sA.height,this.options.keepRatio&&((uA=this.originWidth*_A/this.originHeight)<20?(uA=20,_A=this.originHeight*uA/this.originWidth,iA=this.originTop+this.originHeight-_A):!this.options.canExceedContainer&&uA>this.container.offsetWidth-this.originLeft&&(uA=this.container.offsetWidth-this.originLeft,_A=this.originHeight*uA/this.originWidth,iA=this.originTop+this.originHeight-_A));break;case bu:iA=(sA=this._resizeTop(L)).top,_A=sA.height,uA=this._resizeRight(L),this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?(_A=uA*this.originHeight/this.originWidth,iA=this.originTop+this.originHeight-_A):uA=_A*this.originWidth/this.originHeight);break;case hI:x=(sA=this._resizeLeft(L)).left,uA=sA.width,this.options.keepRatio&&((_A=this.originHeight*uA/this.originWidth)<20?(_A=20,uA=this.originWidth*_A/this.originHeight,x=this.originLeft+this.originWidth-uA):!this.options.canExceedContainer&&_A>this.container.offsetHeight-this.originTop&&(_A=this.container.offsetHeight-this.originTop,uA=this.originWidth*_A/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case rl:uA=this._resizeRight(L),this.options.keepRatio&&((_A=uA*this.originHeight/this.originWidth)<20?uA=(_A=20)*this.originWidth/this.originHeight:!this.options.canExceedContainer&&_A>this.container.offsetHeight-this.originTop&&(uA=(_A=this.container.offsetHeight-this.originTop)*this.originWidth/this.originHeight));break;case Gr:_A=this._resizeBottom(L),x=(sA=this._resizeLeft(L)).left,uA=sA.width,this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?_A=uA*this.originHeight/this.originWidth:(uA=_A*this.originWidth/this.originHeight,x=this.originLeft+this.originWidth-uA));break;case br:_A=this._resizeBottom(L),this.options.keepRatio&&((uA=_A*this.originWidth/this.originHeight)<20?_A=(uA=20)*this.originHeight/this.originWidth:!this.options.canExceedContainer&&uA>this.container.offsetWidth-this.originLeft&&(_A=(uA=this.container.offsetWidth-this.originLeft)*this.originHeight/this.originWidth));break;case lg:_A=this._resizeBottom(L),uA=this._resizeRight(L),this.options.keepRatio&&(uA/this.originWidth<_A/this.originHeight?_A=uA*this.originHeight/this.originWidth:uA=_A*this.originWidth/this.originHeight)}this.resizeTarget.style.left="".concat(x,"px"),this.resizeTarget.style.top="".concat(iA,"px"),this.resizeTarget.style.height="".concat(_A,"px"),this.resizeTarget.style.width="".concat(uA,"px"),this.emit("resize",x,iA,uA,_A)}else cg.debug("".concat(this.logPrefix,"mouseMove error. No valid inner info:"),this.container,this.resizeTarget,this.currentAnchor)},q.prototype._resizeLeft=function(L){var sA=L.screenX-this.resizeStartLeft,G=this.originLeft+sA,x=this.originWidth-sA;return!this.options.canExceedContainer&&G<0?(G=0,x=this.originWidth+this.originLeft):G>this.originLeft+this.originWidth-20&&(G=this.originLeft+this.originWidth-20,x=20),{left:G,width:x}},q.prototype._resizeTop=function(L){var sA=L.screenY-this.resizeStartTop,G=this.originTop+sA,x=this.originHeight-sA;return!this.options.canExceedContainer&&G<0?(G=0,x=this.originHeight+this.originTop):G>this.originTop+this.originHeight-20&&(G=this.originTop+this.originHeight-20,x=20),{top:G,height:x}},q.prototype._resizeRight=function(L){if(!this.container)return cg.debug("".concat(this.logPrefix,"_resizeRight error. No container:"),this.container),0;var sA=L.screenX-this.resizeStartLeft,G=this.originWidth+sA;return G<20?G=20:!this.options.canExceedContainer&&G>this.container.offsetWidth-this.originLeft&&(G=this.container.offsetWidth-this.originLeft),G},q.prototype._resizeBottom=function(L){if(!this.container)return cg.debug("".concat(this.logPrefix,"_resizeBottom error. No container:"),this.container),0;var sA=L.screenY-this.resizeStartTop,G=this.originHeight+sA;return G<20?G=20:!this.options.canExceedContainer&&G>this.container.offsetHeight-this.originTop&&(G=this.container.offsetHeight-this.originTop),G},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,sA){var G=this.callbacksMap.get(L);G?G.push(sA):this.callbacksMap.set(L,[sA])},q.prototype.off=function(L,sA){var G=this.callbacksMap.get(L);G&&(G=G.filter(function(x){return x!=sA}),this.callbacksMap.set(L,G))},q.prototype.emit=function(L){for(var sA=[],G=1;Gx?G:x,this.previewWidth=this.mixingVideoWidth*this.previewScale,this.previewHeight=this.mixingVideoHeight*this.previewScale,this.previewLeft=(L-this.previewWidth)/2,this.previewTop=(sA-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,sA=void 0,G=void 0,x=void 0;if(this.selectedMediaIndex>=0){var iA=this.mediaList[this.selectedMediaIndex],uA={left:iA.rect.left*this.previewScale,top:iA.rect.top*this.previewScale,right:iA.rect.right*this.previewScale,bottom:iA.rect.bottom*this.previewScale};L="".concat(uA.left+this.previewLeft,"px"),sA="".concat(uA.top+this.previewTop,"px"),G="".concat(uA.right-uA.left,"px"),x="".concat(uA.bottom-uA.top,"px");var _A=iA.interaction||{},XA=_A.showBorder!==!1,Qe=_A.showResizeAnchors!==!1,Q=_A.draggable!==!1,h=_A.canExceedCanvas!==!1;this.logger.debug("".concat(this.logPrefix,"updateOverlay: interaction config -"),{showBorder:XA,showResizeAnchors:Qe,draggable:Q,canExceedCanvas:h}),this.updateCanExceedContainer(h),this.moveAndResizeOverlay.style.display="block",this.moveAndResizeOverlay.style.border=XA?"1px solid #3D7EFD":"none",this.resizableHandler&&this.resizableHandler.setVisible(Qe),this.movableHandler&&(this.logger.debug("".concat(this.logPrefix,"updateOverlay: setting movableHandler.setEnabled(").concat(Q,")")),this.movableHandler.setEnabled(Q))}else L="".concat(this.previewLeft,"px"),sA="".concat(this.previewTop,"px"),G="0px",x="0px",this.moveAndResizeOverlay.style.display="none";this.moveAndResizeOverlay.style.left=L,this.moveAndResizeOverlay.style.top=sA,this.moveAndResizeOverlay.style.width=G,this.moveAndResizeOverlay.style.height=x}},q.prototype.onMove=function(L,sA){var G;console.debug("".concat(this.logPrefix,"onMove: ").concat(L," ").concat(sA));var x=this.mediaList[this.selectedMediaIndex];if(x&&this.moveAndResizeOverlay){var iA={left:L-this.previewLeft,top:sA-this.previewTop,right:L-this.previewLeft+this.moveAndResizeOverlay.offsetWidth,bottom:sA-this.previewTop+this.moveAndResizeOverlay.offsetHeight};this.doAdsorption(iA);var uA={left:Math.round(iA.left/this.previewScale),top:Math.round(iA.top/this.previewScale),right:Math.round(iA.right/this.previewScale),bottom:Math.round(iA.bottom/this.previewScale)};(G=this.eventEmitter)===null||G===void 0||G.emit("onSourceMoved",aA({},x),uA)}else console.debug("".concat(this.logPrefix,"onMove no selected media"))},q.prototype.doAdsorption=function(L){var sA=this.BOUNDARY_ADSORPTION_THRESHOLD;Math.abs(L.left)Qe&&(Qe=h,XA=L[Q])}return XA},q.prototype.emitOnSelect=function(L){var sA;if(L){for(var G=this.mediaList.length,x=0;x=Q.rect.left&&_A<=Q.rect.right&&XA>=Q.rect.top&&XA<=Q.rect.bottom&&((sA=Q.interaction)===null||sA===void 0?void 0:sA.selectable)!==!1&&(this.clickedMediaSources.push(Q),this.mediaList[this.selectedMediaIndex]&&Q.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 sA;if(L.target&&this.container&&this.mousedownLeft!==null&&this.mousedownTop!==null){var G=L.screenX-this.mousedownLeft,x=L.screenY-this.mousedownTop;(Math.abs(G)>=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),(sA=this.moveAndResizeOverlay)===null||sA===void 0||sA.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 sA=(this.oldSelectedIndex+1)%this.clickedMediaSources.length;this.newSelected=this.clickedMediaSources[sA],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 sA;console.debug("".concat(this.logPrefix,"onRightButtonClicked:"),L.target,L.currentTarget,L.buttons),L.preventDefault(),(sA=this.eventEmitter)===null||sA===void 0||sA.emit("onRightButtonClicked",aA({},this.mediaList[this.selectedMediaIndex]))},q}(),kl=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,sA,G,x,iA;return tA(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]),sA=0,G=Array.from(this.screensWithSystemAudio),uA.label=6;case 6:return sA1){var Qe=[];this.queue=this.queue.filter(function(Q,h){return h===0||Q.functionName!==x||(Qe.push(Q),!1)}),Qe.forEach(function(Q){Q.reject(new Error("aborted by newer task"))})}this.queue.push(_A)}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 sA=this.queue[0],G=sA.fn,x=sA.args,iA=sA.context,uA=sA.resolve,_A=sA.reject;this.isRunning=!0,G.apply(iA,x).then(uA,_A).finally(function(){L.isRunning=!1,L.shift(),L.callNext()})}},q}(),BI=new WeakMap,jI=new WeakMap,Ca=new WeakMap;function al(q,L){return L===void 0&&(L={}),function(sA,G,x){var iA=x.value,uA=L.deduplicate,_A=uA!==void 0&&uA;return x.value=function(){for(var XA=[],Qe=0;Qe0;if(L&&!this.isMessageListenerRegistered)return this.trtc.on(F.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),void(this.isMessageListenerRegistered=!0);!L&&this.isMessageListenerRegistered&&(this.trtc.off(F.default.EVENT.REALTIME_TRANSCRIBER_MESSAGE,this.handleMessageEvent),this.isMessageListenerRegistered=!1)},q.prototype.log=function(){for(var L,sA,G=[],x=0;x0&&clearTimeout(zI),zI=window.setTimeout(function(){_E.apply(q,L),zI=-1},xr)}));var Lu=new Map,lC=function(q){function L(G){G===void 0&&(G={});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=F.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=JI,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=cC;var iA=G.frameWorkType,uA=iA===void 0?30:iA,_A=G.component,XA=_A===void 0?0:_A,Qe=G.language,Q=Qe===void 0?0:Qe;return x._frameWorkType=uA,x._component=XA,x._language=Q,x._trtc=F.default.create({enableSEI:L.enableSEI,assetsPath:L.assetsPath,enableVolumeControlInIOS:!0,plugins:[j.default,u.LEBPlayer,w.RealtimeTranscriber]}),x._testTrtc=F.default.create(),x._log=F.default._loggerManager,x.logger=new ec(WI,{seq:ku++}),x._echoCancellation=void 0,x._noiseSuppression=void 0,x._autoGainControl=void 0,x._addTRTCEvents(),x.handleDeviceChange=x.handleDeviceChange.bind(x),Lu.set(x,{fn:x.handleDeviceChange,self:x}),x}var sA;return function(G,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");function iA(){this.constructor=G}lA(G,x),G.prototype=x===null?Object.create(x):(iA.prototype=x.prototype,new iA)}(L,q),L.getPlugin=function(G){return G==="VirtualBackground"?p.VirtualBackground:G==="BasicBeauty"?y.BasicBeauty:G==="VideoMixer"?j.default:null},L.getTRTCShareInstance=function(G){return L.shareInstance||(L.shareInstance=new L(G)),L.shareInstance},L.setLogLevel=function(G,x){var iA,uA=((iA={})[r.TRTCLogLevel.TRTCLogLevelVerbose]=0,iA[r.TRTCLogLevel.TRTCLogLevelDebug]=1,iA[r.TRTCLogLevel.TRTCLogLevelInfo]=2,iA[r.TRTCLogLevel.TRTCLogLevelWarn]=3,iA[r.TRTCLogLevel.TRTCLogLevelError]=4,iA[r.TRTCLogLevel.TRTCLogLevelFatal]=4,iA[r.TRTCLogLevel.TRTCLogLevelNone]=5,iA),_A=uA[G];Es(_A)&&(_A=uA[r.TRTCLogLevel.TRTCLogLevelInfo]);var XA=!Pi(x)||x;F.default.setLogLevel(_A,XA)},L.destroyTRTCShareInstance=function(){L.shareInstance&&(L.shareInstance._destroy(),L.shareInstance=null),Array.from(L.subCloudMap.keys()).forEach(function(G){return G._destroy()})},L.callExperimentalAPI=function(G){console.log("static ".concat(Ut,".callExperimentalAPI"),G);var x=vs(G);if(x!==G){var iA=x.api,uA=x.params;if(iA&&uA)try{switch(iA){case"enableSEI":L.enableSEI=uA.enable;break;case"setAssetsPath":L.assetsPath=uA.assetsPath}}catch(_A){throw _A}}},L.prototype.createSubCloud=function(){if(this!==L.shareInstance)return null;var G=new L;return this._inheritPropertiesToSubCloud(G),this._inheritEventsToSubCloud(G),L.subCloudMap.set(G,G),G},L.prototype.destroy=function(){this!==L.shareInstance?(L.subCloudMap.get(this)&&L.subCloudMap.delete(this),this._destroy()):L.destroyTRTCShareInstance()},L.prototype._destroy=function(){Lu.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(G,x){return IA(this,void 0,Promise,function(){var iA,uA,_A,XA,Qe,Q,h,v,N,O,z,X,rA,DA,GA,JA,ee,ue;return tA(this,function(He){switch(He.label){case 0:if(iA=G.sdkAppId,uA=G.userId,_A=G.userSig,XA=G.roomId,Qe=G.strRoomId,Q=G.role,h=G.privateMapKey,v=G.businessInfo,N=G.enableAutoPlayDialog,O=G.proxy,z=G.streamId,X=G.userDefineRecordId,this.logger.update({sdkAppId:iA,userId:uA}),this.logger.info("".concat(Ut,".enterRoom with params: "),G,x),O&&(this._networkProxy=O),!(iA&&uA&&_A))return[3,5];He.label=1;case 1:return He.trys.push([1,3,,4]),rA={sdkAppId:iA,userId:uA,userSig:_A,roomId:XA,strRoomId:Qe,role:yo[Q],scene:pA[x],autoReceiveAudio:this._autoRecvAudio,autoReceiveVideo:this._autoRecvVideo,frameWorkType:this._frameWorkType,component:this._component,language:this._language},rA=h?aA(aA({},rA),{privateMapKey:h}):rA,rA=v?aA(aA({},rA),{businessInfo:v}):rA,DA=N||this._enableAutoPlayDialog,rA=Pi(DA)?aA(aA({},rA),{enableAutoPlayDialog:DA}):rA,rA=this._networkProxy?aA(aA({},rA),{proxy:this._networkProxy}):rA,rA=z?aA(aA({},rA),{streamId:z}):rA,rA=X?aA(aA({},rA),{userDefineRecordId:X}):rA,rA=this._latencyLevel!==void 0?aA(aA({},rA),{latencyLevel:this._latencyLevel}):rA,GA=Br(),[4,this._trtc.enterRoom(rA)];case 2:return He.sent(),this._hasJoinedRoom=!0,JA=Br()-GA,this.emit("onEnterRoom",JA),[3,4];case 3:return ee=He.sent(),ue=(ue=this._transformTRTCErrorCode(ee,"enterRoom"))<0?ue:-1,this.emit("onEnterRoom",ue),this._callFunctionErrorManage(ee,"enterRoom"),[3,4];case 4:return[3,6];case 5:this._emitError(dI),He.label=6;case 6:return[2]}})})},L.prototype.exitRoom=function(){return IA(this,void 0,Promise,function(){var G;return tA(this,function(x){switch(x.label){case 0:return x.trys.push([0,2,,3]),this.logger.info("".concat(Ut,".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",ol.exitRoom),[3,3];case 2:return G=x.sent(),this._callFunctionErrorManage(G,"exitRoom"),[3,3];case 3:return[2]}})})},L.prototype.switchRole=function(G){return IA(this,void 0,void 0,function(){var x;return tA(this,function(iA){switch(iA.label){case 0:this.logger.info("".concat(Ut,".switchRole with param: "),G),iA.label=1;case 1:return iA.trys.push([1,3,,4]),[4,this._trtc.switchRole(yo[G])];case 2:return iA.sent(),this.emit("onSwitchRole",0,"switch role success, role = ".concat(G,", ").concat(yo[G])),[3,4];case 3:return x=iA.sent(),this.emit("onSwitchRole",x?.getCode(),x.message),[3,4];case 4:return[2]}})})},L.prototype.setDefaultStreamRecvMode=function(G,x){return IA(this,void 0,void 0,function(){return tA(this,function(iA){return this.logger.info("".concat(Ut,".setDefaultStreamRecvMode with param: "),{autoRecvAudio:G,autoRecvVideo:x}),Pi(G)&&(this._autoRecvAudio=G),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 G;return tA(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((G=x.sent()).code!==F.default.ERROR_CODE.OPERATION_ABORT)throw G;return[3,3];case 3:return[2]}})})},L.prototype._updateLocalTestVideo=function(){return IA(this,void 0,void 0,function(){var G;return tA(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((G=x.sent()).code!==F.default.ERROR_CODE.OPERATION_ABORT)throw G;return[3,3];case 3:return[2]}})})},L.prototype._updateLocalScreen=function(){return IA(this,void 0,void 0,function(){var G;return tA(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((G=x.sent()).code!==F.default.ERROR_CODE.OPERATION_ABORT)throw G;return[3,3];case 3:return[2]}})})},L.prototype._updateRemoteVideo=function(G,x){return IA(this,void 0,void 0,function(){var iA;return tA(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(G,x))];case 2:return uA.sent(),[3,4];case 3:if((iA=uA.sent()).code!==F.default.ERROR_CODE.OPERATION_ABORT)throw iA;return[3,4];case 4:return[2]}})})},L.prototype.startLocalPreview=function(){for(var G=[],x=0;x9)throw new Error("beautyLevel must be between 0 and 9");if(_A<0||_A>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]),h=_A/9,v=XA/9,(Q=uA/9)===0&&h===0&&v===0?[4,G.stopPlugin(rn)]:[3,3];case 2:return z.sent(),Qe?this._isTestBeautyEnabled=!1:this._isBeautyEnabled=!1,[3,7];case 3:return N={beauty:Q,brightness:h,ruddy:v},x?[3,5]:[4,G.startPlugin(rn,N)];case 4:return z.sent(),Qe?this._isTestBeautyEnabled=!0:this._isBeautyEnabled=!0,[3,7];case 5:return[4,G.updatePlugin(rn,N)];case 6:z.sent(),z.label=7;case 7:return[3,9];case 8:throw O=z.sent(),Qe?this.logger.error("".concat(Ut,".").concat("setTestBeautyStyle"," fail: "),O):this.logger.error("".concat(Ut,".").concat("setBeautyStyle"," fail: "),O),O;case 9:return[2]}})})},L.prototype._resetBeautyStyle=function(){return IA(this,void 0,void 0,function(){return tA(this,function(G){switch(G.label){case 0:return this._isBeautyEnabled?[4,this._trtc.stopPlugin(rn)]:[3,2];case 1:G.sent(),this._isBeautyEnabled=!1,G.label=2;case 2:return this._isTestBeautyEnabled?[4,this._testTrtc.stopPlugin(rn)]:[3,4];case 3:G.sent(),this._isTestBeautyEnabled=!1,G.label=4;case 4:return[2]}})})},L.prototype.getMicDevicesList=function(){return IA(this,void 0,Promise,function(){var G,x,iA;return tA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Ut,".getMicDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,F.default.getMicrophoneList()];case 2:return G=uA.sent(),x=G.map(function(_A){return aA(aA({},_A),{deviceName:_A.label})}),this._microphoneList=G,JSON.stringify(this._currentMicrophone)!=="{}"?[3,4]:(this._currentMicrophone=this.getDefaultDeviceInfo(G),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 iA=uA.sent(),this._callFunctionErrorManage(iA,"getMicDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},L.prototype.setCurrentMicDevice=function(G){var x;return IA(this,void 0,Promise,function(){var iA;return tA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Ut,".setCurrentMicDevice with params: "),{micId:G}),uA.label=1;case 1:return uA.trys.push([1,4,,5]),G?(this._setCurrentMicrophoneId(G),[4,this._updateLocalAudio()]):[2,!1];case 2:return uA.sent(),[4,this._updateLocalTestAudio()];case 3:return uA.sent(),this._currentMicrophone=this._microphoneList.find(function(_A){return _A.deviceId===G})||{},[3,5];case 4:throw iA=uA.sent(),this._setCurrentMicrophoneId((x=this._currentMicrophone)===null||x===void 0?void 0:x.deviceId),this._callFunctionErrorManage(iA,"setCurrentMicDevice"),iA;case 5:return[2]}})})},L.prototype.getCurrentMicDevice=function(){this.logger.info("".concat(Ut,".getCurrentMicDevice"));var G=this._currentMicrophone,x=G.deviceId,iA=G.label,uA=G.kind,_A=G.groupId;return new Vt(x,iA,uA,iA,_A)},L.prototype.getSpeakerDevicesList=function(){return IA(this,void 0,Promise,function(){var G,x,iA;return tA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Ut,".getSpeakerDevicesList")),uA.label=1;case 1:return uA.trys.push([1,5,,6]),[4,F.default.getSpeakerList()];case 2:return G=uA.sent(),x=G.map(function(_A){return aA(aA({},_A),{deviceName:_A.label})}),this._speakerList=G,JSON.stringify(this._currentSpeaker)!=="{}"?[3,4]:(this._currentSpeaker=this.getDefaultDeviceInfo(G),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 iA=uA.sent(),this._callFunctionErrorManage(iA,"getSpeakerDevicesList"),[2,Promise.resolve([])];case 6:return[2]}})})},L.prototype.setCurrentSpeakerDevice=function(G){return IA(this,void 0,Promise,function(){var x;return tA(this,function(iA){switch(iA.label){case 0:this.logger.info("".concat(Ut,".setCurrentSpeakerDevice with params: "),{speakerId:G}),iA.label=1;case 1:return iA.trys.push([1,3,,4]),G?[4,F.default.setCurrentSpeaker(G)]:[2,!1];case 2:return iA.sent(),this._setCurrentSpeakerId(G),this._currentSpeaker=this._speakerList.find(function(uA){return uA.deviceId===G})||{},[3,4];case 3:throw x=iA.sent(),this._callFunctionErrorManage(x,"setCurrentSpeakerDevice"),x;case 4:return[2]}})})},L.prototype.getCurrentSpeakerDevice=function(){this.logger.info("".concat(Ut,".getCurrentSpeakerDevice"));var G=this._currentSpeaker,x=G.deviceId,iA=G.label,uA=G.kind,_A=G.groupId;return new Vt(x,iA,uA,iA,_A)},L.prototype.startCameraDeviceTest=function(G){return IA(this,void 0,void 0,function(){var x;return tA(this,function(iA){switch(iA.label){case 0:if(this.logger.info("".concat(Ut,".startCameraDeviceTest with params: "),G),!G)return[2];this._setLocalTestView(G),iA.label=1;case 1:return iA.trys.push([1,3,,7]),[4,this._testTrtc.startLocalVideo(this._generateLocalTestVideoData())];case 2:return iA.sent(),[3,7];case 3:return(x=iA.sent()).code!==F.default.ERROR_CODE.OPERATION_ABORT?[3,5]:[4,this._updateLocalTestVideo()];case 4:return iA.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 tA(this,function(G){switch(G.label){case 0:return this.logger.info("".concat(Ut,".stopCameraDeviceTest")),this._setLocalTestView(null),[4,this._testTrtc.stopLocalVideo()];case 1:return G.sent(),[2]}})})},L.prototype.startMicDeviceTest=function(G){return IA(this,void 0,void 0,function(){var x,iA=this;return tA(this,function(uA){switch(uA.label){case 0:this.logger.info("".concat(Ut,".startMicDeviceTest with params: "),G),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!==F.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(F.default.EVENT.AUDIO_VOLUME,function(_A){_A?.result.forEach(function(XA){var Qe=XA.userId,Q=XA.volume;Qe===""&&iA.emit("onTestMicVolume",Q)})}),[4,this._testTrtc.enableAudioVolumeEvaluation(G)];case 8:return uA.sent(),[2]}})})},L.prototype.stopMicDeviceTest=function(){return IA(this,void 0,void 0,function(){return tA(this,function(G){switch(G.label){case 0:return this.logger.info("".concat(Ut,".stopMicDeviceTest")),[4,this._testTrtc.stopLocalAudio()];case 1:return G.sent(),[2]}})})},L.prototype.callExperimentalAPI=function(G){return IA(this,void 0,void 0,function(){var x,iA,uA;return tA(this,function(_A){switch(_A.label){case 0:if(this.logger.info("".concat(Ut,".callExperimentalAPI"),G),(x=vs(G))===G)return[2];if(iA=x.api,uA=x.params,!iA||!uA)return[2];_A.label=1;case 1:switch(_A.trys.push([1,25,,26]),iA){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 _A.sent(),[3,24];case 10:return[4,this.setTestVirtualBackground(uA)];case 11:return _A.sent(),[3,24];case 12:return[4,this.setTestBeautyStyle(uA.style,uA.beautyLevel,uA.whitenessLevel,uA.ruddinessLevel)];case 13:return _A.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 _A.sent(),[3,24];case 19:return[4,this._requestPictureInPicture()];case 20:return _A.sent(),[3,24];case 21:return[4,this._exitPictureInPicture()];case 22:return _A.sent(),[3,24];case 23:return[3,24];case 24:return[3,26];case 25:throw _A.sent();case 26:return[2]}})})},L.prototype._handleSetFrameWork=function(G){var x=G.frameWork,iA=G.component,uA=G.language;jr(x)&&(this._frameWorkType=x),jr(iA)&&(this._component=iA),jr(uA)&&(this._language=uA)},L.prototype._handleKeyMetricsStats=function(G){var x=G.key,iA=G.opt,uA=G.value,_A=G.version,XA=iA===Jn;F.default._addKVStat({type:iA,key:x,value:uA,version:_A,useUV:XA,base:100})},L.prototype._setVideoEncodeParamEx=function(G){return IA(this,void 0,void 0,function(){return tA(this,function(x){switch(x.label){case 0:switch(G.streamType){case r.TRTCVideoStreamType.TRTCVideoStreamTypeBig:return[3,1];case r.TRTCVideoStreamType.TRTCVideoStreamTypeSub:return[3,3]}return[3,5];case 1:return[4,this.setVideoEncoderParam(G)];case 2:case 4:return x.sent(),[3,6];case 3:return[4,this.setSubStreamEncoderParam(G)];case 5:return[3,6];case 6:return[2]}})})},L.prototype._switchPlaybackQuality=function(G){return IA(this,void 0,void 0,function(){var x,iA,uA,_A,XA,Qe,Q,h;return tA(this,function(v){switch(v.label){case 0:if(iA=(x=G||{}).quality,uA=x.stream_list,_A=uA===void 0?[]:uA,!iA||_A.length===0)return[2];for(XA=null,Qe=0,Q=_A;Qe1&&x[1]),height:+(x.length>2&&x[2])}},L.prototype._getTRTCVideoProfile=function(G,x){x===void 0&&(x={});var iA=x.videoWidth,uA=x.videoHeight,_A=x.videoResolution,XA=x.videoFps,Qe=x.videoBitrate,Q=x.resMode,h=x.resolutionMode,v={};switch(G){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(Es(_A))Es(iA)||(v.width=iA),Es(uA)||(v.height=uA);else{var N=this._getTRTCResolution(_A);v.width=N.width,v.height=N.height}if(!Es(Q)&&Q===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait||!Es(h)&&h===r.TRTCVideoResolutionMode.TRTCVideoResolutionModePortrait){var O=v.height,z=v.width;v.width=O,v.height=z}return XA&&(v.frameRate=XA),Qe&&(v.bitrate=Qe),v},L.prototype._getTRTCStreamType=function(G){var x;return((x={})[r.TRTCVideoStreamType.TRTCVideoStreamTypeBig]=F.default.TYPE.STREAM_TYPE_MAIN,x[r.TRTCVideoStreamType.TRTCVideoStreamTypeSmall]=F.default.TYPE.STREAM_TYPE_MAIN,x[r.TRTCVideoStreamType.TRTCVideoStreamTypeSub]=F.default.TYPE.STREAM_TYPE_SUB,x)[G]},L.prototype._getTRTCFillMode=function(G){var x;return((x={})[r.TRTCVideoFillMode.TRTCVideoFillMode_Fill]=il.COVER,x[r.TRTCVideoFillMode.TRTCVideoFillMode_Fit]=il.CONTAIN,x)[G]},L.prototype._getTRTCCloudVideoFillMode=function(G){var x;return((x={})[il.COVER]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fill,x[il.CONTAIN]=r.TRTCVideoFillMode.TRTCVideoFillMode_Fit,x)[G]},L.prototype._getTRTCCloudMirrorType=function(G){return G===!0?r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable:r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable},L.prototype._getLocalRenderMirror=function(G){var x;return G===r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto?!this._getIsMobile()||this._getIsFrontCamera():((x={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[G]},L.prototype._getTRTCLocalMirror=function(G,x){var iA=this._getLocalRenderMirror(G);return Es(x)?!!iA&&"both":iA&&x?"both":iA&&!x?"view":!iA&&x?"publish":!(!iA&&!x)&&"view"},L.prototype._getTRTCRemoteMirror=function(G){var x;return((x={})[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Auto]=!1,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Enable]=!0,x[r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable]=!1,x)[G]},L.prototype._getTRTCQosPreference=function(G){var x;return((x={})[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceSmooth]=F.default.TYPE.QOS_PREFERENCE_SMOOTH,x[r.TRTCVideoQosPreference.TRTCVideoQosPreferenceClear]=F.default.TYPE.QOS_PREFERENCE_CLEAR,x)[G]},L.prototype._getTRTCAudioQuality=function(G){var x;return((x={})[r.TRTCAudioQuality.TRTCAudioQualitySpeech]=F.default.TYPE.AUDIO_PROFILE_STANDARD,x[r.TRTCAudioQuality.TRTCAudioQualityDefault]=F.default.TYPE.AUDIO_PROFILE_STANDARD,x[r.TRTCAudioQuality.TRTCAudioQualityMusic]=F.default.TYPE.AUDIO_PROFILE_HIGH_STEREO,x)[G]},L.prototype._getTRTCCloudDeviceType=function(G){return{camera:r.TRTCDeviceType.TRTCDeviceTypeCamera,microphone:r.TRTCDeviceType.TRTCDeviceTypeMic,speaker:r.TRTCDeviceType.TRTCDeviceTypeSpeaker}[G]},L.prototype._getTRTCCloudDeviceState=function(G){return{add:r.TRTCDeviceState.TRTCDeviceStateAdd,remove:r.TRTCDeviceState.TRTCDeviceStateRemove,active:r.TRTCDeviceState.TRTCDeviceStateActive}[G]},L.prototype._getTRTCCloudQuality=function(G){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][G]},L.prototype._generateLocalVideoData=function(){var G={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?G&&Object.assign(G.option,{videoTrack:this._cameraVideoTrack}):this._getIsMobile()?G&&Object.assign(G.option,{useFrontCamera:this._getIsFrontCamera()}):G&&Object.assign(G.option,{cameraId:this._getCurrentCameraId()}),this._getQosPreference()&&G&&Object.assign(G.option,{qosPreference:this._getQosPreference()}),G},L.prototype._generateLocalTestVideoData=function(){var G={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()?G&&Object.assign(G.option,{useFrontCamera:this._getIsFrontCamera()}):G&&Object.assign(G.option,{cameraId:this._getCurrentCameraId()}),G},L.prototype._generateLocalAudioData=function(){var G={publish:this._getIsAudioPublish(),mute:this._getAudioMuteType(),muteKeepVolumeDetection:!0,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile(),captureVolume:this._getCaptureVolume()}};return Pi(this._echoCancellation)&&(G.option.echoCancellation=this._echoCancellation),Pi(this._autoGainControl)&&(G.option.autoGainControl=this._autoGainControl),Pi(this._noiseSuppression)&&(G.option.noiseSuppression=this._noiseSuppression),G},L.prototype._generateLocalTestAudioData=function(){return{publish:!1,option:{microphoneId:this._getCurrentMicrophoneId(),profile:this._getAudioProfile()}}},L.prototype._generateRemoteVideoData=function(G,x){return wn(this._remoteStreamConfig.get("".concat(G,"_").concat(this._getTRTCStreamType(x))))},L.prototype._addTRTCEvents=function(){var G=this;this._trtc.on(F.default.EVENT.ERROR,function(x){x&&G.emit("onError",x.code,x.message)}),this._trtc.on(F.default.EVENT.REMOTE_USER_ENTER,function(x){x?.userId&&G.emit("onRemoteUserEnterRoom",x.userId)}),this._trtc.on(F.default.EVENT.REMOTE_USER_EXIT,function(x){x?.userId&&G.emit("onRemoteUserLeaveRoom",x.userId)}),this._trtc.on(F.default.EVENT.REMOTE_AUDIO_AVAILABLE,function(x){x?.userId&&G.emit("onUserAudioAvailable",x.userId,!0)}),this._trtc.on(F.default.EVENT.REMOTE_AUDIO_UNAVAILABLE,function(x){x?.userId&&G.emit("onUserAudioAvailable",x.userId,!1)}),this._trtc.on(F.default.EVENT.REMOTE_VIDEO_AVAILABLE,function(x){G._emitVideoAvailable(x,!0)}),this._trtc.on(F.default.EVENT.REMOTE_VIDEO_UNAVAILABLE,function(x){G._emitVideoAvailable(x,!1)}),this._trtc.on(F.default.EVENT.AUDIO_VOLUME,function(x){x?.result&&G.emit("onUserVoiceVolume",x?.result,(x?.result||[]).length)}),this._trtc.on(F.default.EVENT.KICKED_OUT,function(x){var iA={banned:ol.banned,room_disband:ol.roomDisband};jr(iA[x.reason])&&G.emit("onExitRoom",iA[x.reason])}),this._trtc.on(F.default.EVENT.NETWORK_QUALITY,function(x){var iA=x.uplinkNetworkQuality,uA=x.downlinkNetworkQuality,_A=new Ko("",G._getTRTCCloudQuality(iA)),XA=[];G._remoteStatisticsUserIdList.length>0&&(XA=G._remoteStatisticsUserIdList.map(function(Qe){return new Ko(Qe,G._getTRTCCloudQuality(uA))})),G.emit("onNetworkQuality",_A,XA)}),this._trtc.on(F.default.EVENT.AUTOPLAY_FAILED,function(x){G.emit("onAutoPlayFailed",x)}),this._trtc.on(F.default.EVENT.SEI_MESSAGE,function(x){if(x.data&&typeof x.data=="object"&&x.data instanceof ArrayBuffer){for(var iA=new Uint8Array(x.data),uA="",_A=0;_A0?h.video.map(function(DA){var GA=new io;return GA.width=DA.width,GA.height=DA.height,GA.frameRate=DA.frameRate,GA.videoBitrate=DA.bitrate,GA.audioBitrate=h.audio.bitrate||0,GA.streamType=N[DA.videoType],GA}):[];if(O.length===0&&h.audio.bitrate>0){var z=new io;z.audioBitrate=h.audio.bitrate||0,O.push(z)}var X=[];v.forEach(function(DA){var GA=[],JA=DA.userId,ee=DA.audio.bitrate;if(DA.video&&DA.video.forEach(function(He){var At=new bi;At.userId=JA,At.width=He.width,At.height=He.height,At.frameRate=He.frameRate,At.videoBitrate=He.bitrate,At.audioBitrate=ee||0,At.streamType=N[He.videoType],GA.push(At)}),GA.length===0){var ue=new bi;ue.userId=JA,ue.audioBitrate=ee||0,GA.push(ue)}X.push.apply(X,GA)});var rA=new Ms;rA.upLoss=_A,rA.downLoss=XA,rA.rtt=uA,rA.sentBytes=Qe,rA.receivedBytes=Q,rA.localStatisticsArray=O,rA.localStatisticsArraySize=O.length,rA.remoteStatisticsArray=X,rA.remoteStatisticsArraySize=X.length,G.emit("onStatistics",rA)}),this._trtc.on(F.default.EVENT.SCREEN_SHARE_STOPPED,function(){G.emit("onScreenCaptureStopped",0),G._clearScreenShareParams(),G._isSharingScreen=!1}),this._trtc.on(F.default.EVENT.PUBLISH_STATE_CHANGED,function(x){var iA=x.mediaType;x.state==="started"&&(iA==="audio"?G.emit("onSendFirstLocalAudioFrame"):iA==="video"?G.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeBig):iA==="screen"&&G.emit("onSendFirstLocalVideoFrame",r.TRTCVideoStreamType.TRTCVideoStreamTypeSub))}),this._trtc.on(F.default.EVENT.FIRST_VIDEO_FRAME,function(x){var iA=x.userId,uA=x.streamType,_A=x.width,XA=x.height;G.emit("onFirstVideoFrame",iA,uA,_A,XA)}),this._trtc.on(F.default.EVENT.AUDIO_PLAY_STATE_CHANGED,function(x){var iA=x.userId;x.state==="PLAYING"&&G.emit("onFirstAudioFrame",iA)}),this._trtc.on(F.default.EVENT.DEVICE_CHANGED,function(x){var iA=x.type,uA=x.device,_A=x.action,XA=uA.deviceId;if(_A==="active"){switch(iA){case"camera":G._currentCameraId=XA,G._currentCamera=uA;break;case"microphone":G._currentMicrophoneId=XA,G._currentMicrophone=uA;break;case"speaker":G._currentSpeakerId=XA,G._currentSpeaker=uA}G.emitOnDeviceChange(XA,G._getTRTCCloudDeviceType(iA),G._getTRTCCloudDeviceState(_A))}}),this._trtc.on(F.default.EVENT.CUSTOM_MESSAGE,function(x){x&&G.emit("onRecvCustomCmdMsg",x.userId,x.cmdId,x.seq,x?.data)}),this._trtc.on(F.default.EVENT.CONNECTION_STATE_CHANGED,function(x){G._hasJoinedRoom&&!G._isExitingRoom&&(x.prevState==="CONNECTED"&&x.state==="DISCONNECTED"?G.emit("onConnectionLost"):x.prevState==="DISCONNECTED"&&x.state==="CONNECTING"?G.emit("onTryToReconnect"):x.prevState==="CONNECTING"&&x.state==="CONNECTED"&&G.emit("onConnectionRecovery"))}),this._trtc.on(F.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(x){G.emit("onPictureInPictureStateChanged",x)})},L.prototype._removeTRTCEvents=function(){this._trtc.off("*")},L.prototype._emitVideoAvailable=function(G,x){var iA=G.userId,uA=G.streamType;x?this._remoteStreamMap.set("".concat(iA,"_").concat(uA),!0):this._remoteStreamMap.delete("".concat(iA,"_").concat(uA)),uA===F.default.TYPE.STREAM_TYPE_SUB?iA&&this.emit("onUserSubStreamAvailable",iA,x):iA&&this.emit("onUserVideoAvailable",iA,x)},L.prototype._setLocalView=function(G){this._localView=G},L.prototype._getLocalView=function(){return this._localView},L.prototype._setIsMobile=function(G){this._isMobile=G},L.prototype._getIsMobile=function(){return this._isMobile},L.prototype._setIsFrontCamera=function(G){this._isFrontCamera=G},L.prototype._getIsFrontCamera=function(){return this._isFrontCamera},L.prototype._getSmallStreamVideoProfile=function(){return this._smallStreamVideoProfile},L.prototype._setSmallStreamVideoProfile=function(G){this._smallStreamVideoProfile=G},L.prototype._setIsVideoPublish=function(G){this._isVideoPublish=G},L.prototype._getIsVideoPublish=function(){return this._isVideoPublish},L.prototype._setVideoProfile=function(G){this._videoProfile=G},L.prototype._getVideoProfile=function(){return this._videoProfile},L.prototype._setQosPreference=function(G){this._qosPreference=G},L.prototype._getQosPreference=function(){return this._qosPreference},L.prototype._setLocalTestView=function(G){this._localTestView=G},L.prototype._getLocalTestView=function(){return this._localTestView},L.prototype._setScreenShareParams=function(G){var x=G.view,iA=G.systemAudio,uA=G.fillMode,_A=G.profile,XA=G.videoTrack,Qe=G.qosPreference;Es(x)||(this._screenShareParams.view=x),Es(iA)||(this._screenShareParams.option.systemAudio=iA),Es(uA)||(this._screenShareParams.option.fillMode=uA),Es(_A)||(this._screenShareParams.option.profile=_A),Es(XA)||(this._screenShareParams.option.videoTrack=XA),Es(Qe)||(this._screenShareParams.option.qosPreference=Qe),Es(G.streamType)||(this._screenShareParams.streamType=this._getTRTCStreamType(G.streamType))},L.prototype._clearScreenShareParams=function(){var G,x,iA,uA,_A;!((G=this._screenShareParams)===null||G===void 0)&&G.view&&delete this._screenShareParams.view,!((iA=(x=this._screenShareParams)===null||x===void 0?void 0:x.option)===null||iA===void 0)&&iA.systemAudio&&delete this._screenShareParams.option.systemAudio,!((_A=(uA=this._screenShareParams)===null||uA===void 0?void 0:uA.option)===null||_A===void 0)&&_A.videoTrack&&delete this._screenShareParams.option.videoTrack},L.prototype._getScreenShareParams=function(){return this._screenShareParams},L.prototype._setIsAudioPublish=function(G){this._isAudioPublish=G},L.prototype._getIsAudioPublish=function(){return this._isAudioPublish},L.prototype._setAudioMuteType=function(G){this._audioMuteType=G},L.prototype._getAudioMuteType=function(){return this._audioMuteType},L.prototype._setAudioProfile=function(G){this._audioProfile=G},L.prototype._getAudioProfile=function(){return this._audioProfile},L.prototype._getCaptureVolume=function(){return this._captureVolume},L.prototype._setCaptureVolume=function(G){this._captureVolume=G},L.prototype._setCurrentCameraId=function(G){this._currentCameraId=G},L.prototype._getCurrentCameraId=function(){return this._currentCameraId},L.prototype._setCurrentMicrophoneId=function(G){this._currentMicrophoneId=G},L.prototype._getCurrentMicrophoneId=function(){return this._currentMicrophoneId},L.prototype._setCurrentSpeakerId=function(G){this._currentSpeakerId=G},L.prototype._getCurrentSpeakerId=function(){return this._currentSpeakerId},L.prototype._setRemoteStreamConfig=function(G,x,iA){var uA=this._remoteStreamConfig.get("".concat(G,"_").concat(this._getTRTCStreamType(x)));uA||(uA={userId:G,streamType:this._getTRTCStreamType(x),option:{mirror:this._getTRTCRemoteMirror(r.TRTCVideoMirrorType.TRTCVideoMirrorType_Disable),fillMode:this._getTRTCFillMode(r.TRTCVideoFillMode.TRTCVideoFillMode_Fit)}});var _A=iA.view,XA=iA.mirrorType,Qe=iA.fillMode,Q=iA.small;Es(_A)||(uA.view=_A),Es(XA)||(uA.option.mirror=this._getTRTCRemoteMirror(XA)),Es(Qe)||(uA.option.fillMode=this._getTRTCFillMode(Qe)),Es(Q)||(uA.option.small=Q),this._remoteStreamConfig.set("".concat(G,"_").concat(this._getTRTCStreamType(x)),uA)},L.prototype._inheritPropertiesToSubCloud=function(G){G._frameWorkType=this._frameWorkType,G._component=this._component,G._language=this._language,G._networkProxy=aA({},this._networkProxy),G._latencyLevel=this._latencyLevel,G._enableAutoPlayDialog=this._enableAutoPlayDialog},L.prototype._inheritEventsToSubCloud=function(G){var x=this;G._trtc.on(F.default.EVENT.AUTOPLAY_FAILED,function(iA){x.emit("onAutoPlayFailed",iA)}),G._trtc.on(F.default.EVENT.PICTURE_IN_PICTURE_STATE_CHANGED,function(iA){x.emit("onPictureInPictureStateChanged",iA)})},L.prototype.handleDeviceChange=function(){return IA(this,void 0,void 0,function(){var G=this;return tA(this,function(x){return F.default.getCameraList().then(function(iA){return IA(G,void 0,void 0,function(){return tA(this,function(uA){switch(uA.label){case 0:return this._cameraList.length===iA.length?[2]:[4,this.deviceChangeManage(this._cameraList,iA,r.TRTCDeviceType.TRTCDeviceTypeCamera)];case 1:return uA.sent(),this._cameraList=iA,[2]}})})}),F.default.getMicrophoneList().then(function(iA){return IA(G,void 0,void 0,function(){return tA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._microphoneList,iA,r.TRTCDeviceType.TRTCDeviceTypeMic)];case 1:return uA.sent(),this._microphoneList=iA,[2]}})})}),F.default.getSpeakerList().then(function(iA){return IA(G,void 0,void 0,function(){return tA(this,function(uA){switch(uA.label){case 0:return[4,this.deviceChangeManage(this._speakerList,iA,r.TRTCDeviceType.TRTCDeviceTypeSpeaker)];case 1:return uA.sent(),this._speakerList=iA,[2]}})})}),[2]})})},L.prototype.isSameDevice=function(G,x){var iA=G&&G.deviceId&&G.groupId&&G.label,uA=x&&x.deviceId&&x.groupId&&x.label;return!(!iA||!uA)&&G.deviceId===x.deviceId&&G.groupId===x.groupId&&G.label===x.label},L.prototype.deviceChangeManage=function(G,x,iA){return IA(this,void 0,void 0,function(){var uA,_A,XA,Qe,Q;return tA(this,function(h){switch(h.label){case 0:return uA=void 0,G.length!==x.length&&(_A=(x||[]).map(function(v){return v.deviceId}),XA=new Vt,G.length>x.length?(XA=G.filter(function(v){return!_A.includes(v.deviceId)})[0]||{},uA=r.TRTCDeviceState.TRTCDeviceStateRemove):(_A=(G||[]).map(function(v){return v.deviceId}),XA=x.filter(function(v){return!_A.includes(v.deviceId)})[0]||{},uA=r.TRTCDeviceState.TRTCDeviceStateAdd),Qe=XA.deviceId,this.emitOnDeviceChange(Qe,iA,uA)),Q=this.getDefaultDeviceInfo(x),iA!==r.TRTCDeviceType.TRTCDeviceTypeCamera||uA!==r.TRTCDeviceState.TRTCDeviceStateRemove?[3,3]:this.isSameDevice(this._currentCamera,Q)?[2]:Q.deviceId?[4,this.autoChangeDevice(iA,Q)]:[3,2];case 1:h.sent(),h.label=2;case 2:h.label=3;case 3:return iA!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,6]:this.isSameDevice(this._currentMicrophone,Q)?[2]:Q.deviceId?[4,this.autoChangeDevice(iA,Q)]:[3,5];case 4:h.sent(),h.label=5;case 5:h.label=6;case 6:return iA!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,9]:this.isSameDevice(this._currentSpeaker,Q)?[2]:Q.deviceId?[4,this.autoChangeDevice(iA,Q)]:[3,8];case 7:h.sent(),h.label=8;case 8:h.label=9;case 9:return[2]}})})},L.prototype.getDefaultDeviceInfo=function(G){var x=new Vt;if(G.length===0)return x;var iA=G.filter(function(uA){return uA.deviceId==="default"});return x=iA.length>0?iA[0]:G[0]},L.prototype.autoChangeDevice=function(G,x){return IA(this,void 0,void 0,function(){var iA,uA,_A;return tA(this,function(XA){switch(XA.label){case 0:return iA=x.deviceId,G!==r.TRTCDeviceType.TRTCDeviceTypeCamera?[3,6]:(this._setCurrentCameraId(iA),[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:iA}})];case 3:return XA.sent(),[3,5];case 4:return uA=XA.sent(),console.log("testTRTC error",JSON.stringify(uA)),uA.code,F.default.ERROR_CODE.OPERATION_ABORT,[3,5];case 5:this._currentCameraId=iA,this._currentCamera=x,this.emitOnDeviceChange(iA,G,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=6;case 6:return G!==r.TRTCDeviceType.TRTCDeviceTypeMic?[3,12]:(this._setCurrentMicrophoneId(iA),[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:iA}})];case 9:return XA.sent(),[3,11];case 10:return _A=XA.sent(),console.log("testTRTC error",JSON.stringify(_A)),_A.code,F.default.ERROR_CODE.OPERATION_ABORT,[3,11];case 11:this._currentMicrophoneId=iA,this._currentMicrophone=x,this.emitOnDeviceChange(iA,G,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=12;case 12:return G!==r.TRTCDeviceType.TRTCDeviceTypeSpeaker?[3,14]:[4,F.default.setCurrentSpeaker(iA)];case 13:XA.sent(),this._currentSpeakerId=iA,this._currentSpeaker=x,this.emitOnDeviceChange(iA,G,r.TRTCDeviceState.TRTCDeviceStateActive),XA.label=14;case 14:return[2]}})})},L.prototype.emitOnDeviceChange=function(G,x,iA){this.emit("onDeviceChange",G,x,iA)},L.prototype.getMediaMixingManager=function(){return new kl({logger:this.logger,trtc:this._trtc,trtcCloud:this})},L.prototype.getAITranscriberManager=function(){return new wE({logger:this.logger,trtc:this._trtc})},L.shareInstance=null,L.subCloudMap=new Map,L.enableSEI=!1,L.assetsPath="",mA([(sA="exitRoom",function(G,x,iA){var uA=iA.value;return iA.value=function(){for(var _A,XA,Qe,Q,h=[],v=0;vH.length)&&(BA=H.length);for(var yA=0,NA=new Array(BA);yA=0;--tn){var ts=this.tryEntries[tn],ug=ts.completion;if(ts.tryLoc==="root")return fo("end");if(ts.tryLoc<=this.prev){var Ll=zA.call(ts,"catchLoc"),ld=zA.call(ts,"finallyLoc");if(Ll&&ld){if(this.prev=0;--fo){var tn=this.tryEntries[fo];if(tn.tryLoc<=this.prev&&zA.call(tn,"finallyLoc")&&this.prev=0;--ti){var fo=this.tryEntries[ti];if(fo.finallyLoc===Ri)return this.complete(fo.completion,fo.afterLoc),Vr(fo),ai}},catch:function(Ri){for(var ti=this.tryEntries.length-1;ti>=0;--ti){var fo=this.tryEntries[ti];if(fo.tryLoc===Ri){var tn=fo.completion;if(tn.type==="throw"){var ts=tn.arg;Vr(fo)}return ts}}throw new Error("illegal catch attempt")},delegateYield:function(Ri,ti,fo){return this.delegate={iterator:Uu(Ri),resultName:ti,nextLoc:fo},this.method==="next"&&(this.arg=void 0),ai}},yA}(H.exports);try{regeneratorRuntime=BA}catch{typeof globalThis=="object"?globalThis.regeneratorRuntime=BA:Function("r","regeneratorRuntime = r")(BA)}});var aA,mA,IA=function(H){return H&&H.Math==Math&&H},tA=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")(),MA=function(H){try{return!!H()}catch{return!0}},PA=!MA(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ge={}.propertyIsEnumerable,de=Object.getOwnPropertyDescriptor,Ve={f:de&&!ge.call({1:2},1)?function(H){var BA=de(this,H);return!!BA&&BA.enumerable}:ge},Be=function(H,BA){return{enumerable:!(1&H),configurable:!(2&H),writable:!(4&H),value:BA}},ct={}.toString,mt=function(H){return ct.call(H).slice(8,-1)},Ke="".split,Dt=MA(function(){return!Object("z").propertyIsEnumerable(0)})?function(H){return mt(H)=="String"?Ke.call(H,""):Object(H)}:Object,qt=function(H){if(H==null)throw TypeError("Can't call method on "+H);return H},It=function(H){return Dt(qt(H))},re=function(H){return typeof H=="function"},qe=function(H){return typeof H=="object"?H!==null:re(H)},ft=function(H){return re(H)?H:void 0},si=function(H,BA){return arguments.length<2?ft(tA[H]):tA[H]&&tA[H][BA]},Vt=si("navigator","userAgent")||"",gi=tA.process,Fi=tA.Deno,_o=gi&&gi.versions||Fi&&Fi.version,to=_o&&_o.v8;to?mA=(aA=to.split("."))[0]<4?1:aA[0]+aA[1]:Vt&&(!(aA=Vt.match(/Edge\/(\d+)/))||aA[1]>=74)&&(aA=Vt.match(/Chrome\/(\d+)/))&&(mA=aA[1]);var uo=mA&&+mA,Ys=!!Object.getOwnPropertySymbols&&!MA(function(){var H=Symbol();return!String(H)||!(Object(H)instanceof Symbol)||!Symbol.sham&&uo&&uo<41}),ki=Ys&&!Symbol.sham&&typeof Symbol.iterator=="symbol",os=ki?function(H){return typeof H=="symbol"}:function(H){var BA=si("Symbol");return re(BA)&&Object(H)instanceof BA},Ko=function(H){try{return String(H)}catch{return"Object"}},$i=function(H){if(re(H))return H;throw TypeError(Ko(H)+" is not a function")},jt=function(H,BA){var yA=H[BA];return yA==null?void 0:$i(yA)},io=function(H,BA){try{Object.defineProperty(tA,H,{value:BA,configurable:!0,writable:!0})}catch{tA[H]=BA}return BA},bi=tA["__core-js_shared__"]||io("__core-js_shared__",{}),Ms=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)"})}),qA=function(H){return Object(qt(H))},ce={}.hasOwnProperty,Pe=Object.hasOwn||function(H,BA){return ce.call(qA(H),BA)},kt=0,it=Math.random(),gt=function(H){return"Symbol("+String(H===void 0?"":H)+")_"+(++kt+it).toString(36)},Xt=Ms("wks"),$t=tA.Symbol,Ge=ki?$t:$t&&$t.withoutSetter||gt,je=function(H){return Pe(Xt,H)&&(Ys||typeof Xt[H]=="string")||(Ys&&Pe($t,H)?Xt[H]=$t[H]:Xt[H]=Ge("Symbol."+H)),Xt[H]},Mt=je("toPrimitive"),Rt=function(H,BA){if(!qe(H)||os(H))return H;var yA,NA=jt(H,Mt);if(NA){if(yA=NA.call(H,BA),!qe(yA)||os(yA))return yA;throw TypeError("Can't convert object to primitive value")}return function(zA,ve){var le,Te;if(re(le=zA.toString)&&!qe(Te=le.call(zA))||re(le=zA.valueOf)&&!qe(Te=le.call(zA)))return Te;throw TypeError("Can't convert object to primitive value")}(H)},Oi=function(H){var BA=Rt(H,"string");return os(BA)?BA:String(BA)},Qo=tA.document,To=qe(Qo)&&qe(Qo.createElement),oo=function(H){return To?Qo.createElement(H):{}},No=!PA&&!MA(function(){return Object.defineProperty(oo("div"),"a",{get:function(){return 7}}).a!=7}),$s=Object.getOwnPropertyDescriptor,rn={f:PA?$s:function(H,BA){if(H=It(H),BA=Oi(BA),No)try{return $s(H,BA)}catch{}if(Pe(H,BA))return Be(!Ve.f.call(H,BA),H[BA])}},us=function(H){if(qe(H))return H;throw TypeError(String(H)+" is not an object")},an=Object.defineProperty,yo={f:PA?an:function(H,BA,yA){if(us(H),BA=Oi(BA),us(yA),No)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=PA?function(H,BA,yA){return yo.f(H,BA,Be(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 Br,Es,jr,Pi=bi.inspectSource,vs=tA.WeakMap,ir=re(vs)&&/native code/.test(Pi(vs)),An=Ms("keys"),wn=function(H){return An[H]||(An[H]=gt(H))},Jt={},fg=tA.WeakMap;if(ir||bi.state){var On=bi.state||(bi.state=new fg),Gn=On.get,Vs=On.has,Qr=On.set;Br=function(H,BA){if(Vs.call(On,H))throw new TypeError("Object already initialized");return BA.facade=H,Qr.call(On,H,BA),BA},Es=function(H){return Gn.call(On,H)||{}},jr=function(H){return Vs.call(On,H)}}else{var Pn=wn("state");Jt[Pn]=!0,Br=function(H,BA){if(Pe(H,Pn))throw new TypeError("Object already initialized");return BA.facade=H,pA(H,Pn,BA),BA},Es=function(H){return Pe(H,Pn)?H[Pn]:{}},jr=function(H){return Pe(H,Pn)}}var pr={set:Br,get:Es,has:jr,enforce:function(H){return jr(H)?Es(H):Br(H,{})},getterFor:function(H){return function(BA){var yA;if(!qe(BA)||(yA=Es(BA)).type!==H)throw TypeError("Incompatible receiver, "+H+" required");return yA}}},po=Function.prototype,gn=PA&&Object.getOwnPropertyDescriptor,fl=Pe(po,"name"),cn={PROPER:fl&&function(){}.name==="something",CONFIGURABLE:fl&&(!PA||PA&&gn(po,"name").configurable)},mr=lA(function(H){var BA=cn.CONFIGURABLE,yA=pr.get,NA=pr.enforce,zA=String(String).split("String");(H.exports=function(ve,le,Te,ne){var Le,yt=!!ne&&!!ne.unsafe,Kt=!!ne&&!!ne.enumerable,ai=!!ne&&!!ne.noTargetGet,Qt=ne&&ne.name!==void 0?ne.name:le;re(Te)&&(String(Qt).slice(0,7)==="Symbol("&&(Qt="["+String(Qt).replace(/^Symbol\(([^)]*)\)/,"$1")+"]"),(!Pe(Te,"name")||BA&&Te.name!==Qt)&&pA(Te,"name",Qt),(Le=NA(Te)).source||(Le.source=zA.join(typeof Qt=="string"?Qt:""))),ve!==tA?(yt?!ai&&ve[le]&&(Kt=!0):delete ve[le],Kt?ve[le]=Te:pA(ve,le,Te)):Kt?ve[le]=Te:io(le,Te)})(Function.prototype,"toString",function(){return re(this)&&yA(this).source||Pi(this)})}),ks=Math.ceil,Yc=Math.floor,ps=function(H){var BA=+H;return BA!=BA||BA===0?0:(BA>0?Yc:ks)(BA)},rs=Math.max,Bu=Math.min,ja=Math.min,ds=function(H){return H>0?ja(ps(H),9007199254740991):0},og=function(H){return ds(H.length)},LI=function(H){return function(BA,yA,NA){var zA,ve=It(BA),le=og(ve),Te=function(ne,Le){var yt=ps(ne);return yt<0?rs(yt+Le,0):Bu(yt,Le)}(NA,le);if(H&&yA!=yA){for(;le>Te;)if((zA=ve[Te++])!=zA)return!0}else for(;le>Te;Te++)if((H||Te in ve)&&ve[Te]===yA)return H||Te||0;return!H&&-1}},Xo={indexOf:LI(!1)},Zi=Xo.indexOf,Qc=function(H,BA){var yA,NA=It(H),zA=0,ve=[];for(yA in NA)!Pe(Jt,yA)&&Pe(NA,yA)&&ve.push(yA);for(;BA.length>zA;)Pe(NA,yA=BA[zA++])&&(~Zi(ve,yA)||ve.push(yA));return ve},sg=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],yg=sg.concat("length","prototype"),la={f:Object.getOwnPropertyNames||function(H){return Qc(H,yg)}},Go={f:Object.getOwnPropertySymbols},Wr=si("Reflect","ownKeys")||function(H){var BA=la.f(us(H)),yA=Go.f;return yA?BA.concat(yA(H)):BA},wo=function(H,BA){for(var yA=Wr(BA),NA=yo.f,zA=rn.f,ve=0;ve=51||!MA(function(){var BA=[];return(BA.constructor={})[li]=function(){return{foo:1}},BA[H](Boolean).foo!==1})},Ft=je("isConcatSpreadable"),Ji=uo>=51||!MA(function(){var H=[];return H[Ft]=!1,H.concat()[0]!==H}),qi=nt("concat"),Hs=function(H){if(!qe(H))return!1;var BA=H[Ft];return BA!==void 0?!!BA:Ia(H)};ms({target:"Array",proto:!0,forced:!Ji||!qi},{concat:function(H){var BA,yA,NA,zA,ve,le=qA(this),Te=Ot(le,0),ne=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(Te,ne++,ve)}return Te.length=ne,Te}});var Mi,Wo=Object.keys||function(H){return Qc(H,sg)},Sg=PA?Object.defineProperties:function(H,BA){us(H);for(var yA,NA=Wo(BA),zA=NA.length,ve=0;zA>ve;)yo.f(H,yA=NA[ve++],BA[yA]);return H},or=si("document","documentElement"),fr=wn("IE_PROTO"),xn=function(){},yl=function(H){return" - + +
diff --git a/app/video_companion/index.html b/app/video_companion/index.html index 4a91af378..8facfff4e 100644 --- a/app/video_companion/index.html +++ b/app/video_companion/index.html @@ -3,7 +3,7 @@ - + 视频面诊 diff --git a/app/video_companion/package-lock.json b/app/video_companion/package-lock.json index 8858207ac..338455c90 100644 --- a/app/video_companion/package-lock.json +++ b/app/video_companion/package-lock.json @@ -8,7 +8,9 @@ "name": "doctor-video-companion", "version": "0.1.0", "dependencies": { + "@tencentcloud/lite-chat": "1.6.18", "@trtc/calls-uikit-vue": "4.4.6", + "tim-upload-plugin": "1.4.3", "vue": "3.5.13" }, "devDependencies": { @@ -1432,6 +1434,12 @@ "node": ">=0.10.0" } }, + "node_modules/tim-upload-plugin": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/tim-upload-plugin/-/tim-upload-plugin-1.4.3.tgz", + "integrity": "sha512-3ZmbA36dr3eG9YGDon9MLBUtbNawYWkL+TBa+VS0Uviguc7PlVSOIVRG2C4irXX16slDT2Kj+HAZapp+Xqp2xg==", + "license": "ISC" + }, "node_modules/trtc-cloud-js-sdk": { "version": "2.10.19", "resolved": "https://registry.npmjs.org/trtc-cloud-js-sdk/-/trtc-cloud-js-sdk-2.10.19.tgz", diff --git a/app/video_companion/package.json b/app/video_companion/package.json index 2e69023fc..1f8eb765e 100644 --- a/app/video_companion/package.json +++ b/app/video_companion/package.json @@ -9,7 +9,9 @@ "preview": "vite preview --port 4173" }, "dependencies": { + "@tencentcloud/lite-chat": "1.6.18", "@trtc/calls-uikit-vue": "4.4.6", + "tim-upload-plugin": "1.4.3", "vue": "3.5.13" }, "devDependencies": { diff --git a/app/video_companion/src/App.vue b/app/video_companion/src/App.vue index cf80f9e8c..c6023bd52 100644 --- a/app/video_companion/src/App.vue +++ b/app/video_companion/src/App.vue @@ -1,33 +1,263 @@